title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
DirectX - Picking
|
The traditional method which is needed to perform the action of picking relies on the technique is called ray-casting. The user can shoot a ray from the camera position through the selected point which the aspect of near plane of the required frustum which intersects the resulting ray. The first object intersected by the way is considered as the ray of object which is picked.
We will be creating the Picking Demo project as mentioned in the figure below −
Here, you can see that only the required part is hand-picked or the picking process is created.
To pick the respective object, the user should convert the selected screen pixel into the mentioned camera’s view space. The screen-space coordinate is used to view the required space with the conversion of pixel position. Now let us focus on the process of picking the ray. The ray starts with the given point and extends the direction until it reaches the point of infinity. The specialized class called SlimDX provides the required position and the maintained direction properties which is referred to as intersection tests with bounding boxes, spheres, triangles and planes.
Normalized device coordinates map the screen with respect to x and y coordinates within the range of [-1,1].
The parameters which are used for transformation into the required world space by transforming the origin to the mentioned direction of vectors include ray with the inverse of camera’s view matrix. The code snippet which can be used is mentioned below −
public Ray GetPickingRay(Vector2 sp, Vector2 screenDims) {
var p = Proj;
// convert screen pixel to view space
var vx = (2.0f * sp.X / screenDims.X - 1.0f) / p.M11;
var vy = (-2.0f * sp.Y / screenDims.Y + 1.0f) / p.M22;
var ray = new Ray(new Vector3(), new Vector3(vx, vy, 1.0f));
var v = View;
var invView = Matrix.Invert(v);
var toWorld = invView;
ray = new Ray(Vector3.TransformCoordinate(ray.Position, toWorld),
Vector3.TransformNormal(ray.Direction, toWorld));
ray.Direction.Normalize();
return ray;
}
Now we will focus on picking the object with respect to the 3D scene to select a triangle from our car mesh in this example. This changes our OnMouseDown override slightly, consider the code snippet which is mentioned below −
protected override void OnMouseDown(object sender, MouseEventArgs mouseEventArgs) {
if (mouseEventArgs.Button == MouseButtons.Left) {
_lastMousePos = mouseEventArgs.Location;
Window.Capture = true;
}
else if (mouseEventArgs.Button == MouseButtons.Right) {
Pick(mouseEventArgs.X, mouseEventArgs.Y);
}
}
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2677,
"s": 2298,
"text": "The traditional method which is needed to perform the action of picking relies on the technique is called ray-casting. The user can shoot a ray from the camera position through the selected point which the aspect of near plane of the required frustum which intersects the resulting ray. The first object intersected by the way is considered as the ray of object which is picked."
},
{
"code": null,
"e": 2757,
"s": 2677,
"text": "We will be creating the Picking Demo project as mentioned in the figure below −"
},
{
"code": null,
"e": 2853,
"s": 2757,
"text": "Here, you can see that only the required part is hand-picked or the picking process is created."
},
{
"code": null,
"e": 3432,
"s": 2853,
"text": "To pick the respective object, the user should convert the selected screen pixel into the mentioned camera’s view space. The screen-space coordinate is used to view the required space with the conversion of pixel position. Now let us focus on the process of picking the ray. The ray starts with the given point and extends the direction until it reaches the point of infinity. The specialized class called SlimDX provides the required position and the maintained direction properties which is referred to as intersection tests with bounding boxes, spheres, triangles and planes."
},
{
"code": null,
"e": 3541,
"s": 3432,
"text": "Normalized device coordinates map the screen with respect to x and y coordinates within the range of [-1,1]."
},
{
"code": null,
"e": 3795,
"s": 3541,
"text": "The parameters which are used for transformation into the required world space by transforming the origin to the mentioned direction of vectors include ray with the inverse of camera’s view matrix. The code snippet which can be used is mentioned below −"
},
{
"code": null,
"e": 4345,
"s": 3795,
"text": "public Ray GetPickingRay(Vector2 sp, Vector2 screenDims) {\n var p = Proj;\n // convert screen pixel to view space\n var vx = (2.0f * sp.X / screenDims.X - 1.0f) / p.M11;\n var vy = (-2.0f * sp.Y / screenDims.Y + 1.0f) / p.M22;\n var ray = new Ray(new Vector3(), new Vector3(vx, vy, 1.0f));\n var v = View;\n var invView = Matrix.Invert(v);\n var toWorld = invView;\n ray = new Ray(Vector3.TransformCoordinate(ray.Position, toWorld), \n Vector3.TransformNormal(ray.Direction, toWorld));\n ray.Direction.Normalize();\n return ray;\n}"
},
{
"code": null,
"e": 4571,
"s": 4345,
"text": "Now we will focus on picking the object with respect to the 3D scene to select a triangle from our car mesh in this example. This changes our OnMouseDown override slightly, consider the code snippet which is mentioned below −"
},
{
"code": null,
"e": 4904,
"s": 4571,
"text": "protected override void OnMouseDown(object sender, MouseEventArgs mouseEventArgs) {\n if (mouseEventArgs.Button == MouseButtons.Left) {\n _lastMousePos = mouseEventArgs.Location;\n Window.Capture = true;\n } \n else if (mouseEventArgs.Button == MouseButtons.Right) {\n Pick(mouseEventArgs.X, mouseEventArgs.Y);\n }\n}"
},
{
"code": null,
"e": 4911,
"s": 4904,
"text": " Print"
},
{
"code": null,
"e": 4922,
"s": 4911,
"text": " Add Notes"
}
] |
How to Display Validation Message for Radio Buttons with Inline Images using Bootstrap 4 ? - GeeksforGeeks
|
18 Nov, 2021
By Default, Bootstrap 4 has various form features for radio buttons with images inline. Here HTML 5 has default validation features, However, for custom validation, we must use JavaScript or jQuery. The following approaches would help in the display validation message for radio buttons with images inline.Approach 1: First wrap Radio buttons and its label by using form-check-inline class. Then add img tag within the above wrap after label tag. Use default required validation by adding required attribute of radio button. Finally, display message using alert class and trigger it with jQueries attr(), addClass() and html() methods only if radio button not checked.
Example: The below program illustrates to display validation message for radio buttons with images inline based on the the above approach.
html
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <div class="container"> <h1>GeeksforGeeeks</h1> <br><br> <p>Select Your Gender</p> <form> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio2" value="option2" required> <label class="form-check-label" for="inlineRadio2"> <img id="option2img" src="https://media.geeksforgeeks.org/wp-content/uploads/20200114123932/malelogo.png" class="rounded-circle rounded-sm img-fluid img-thumbnail"> </label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio3" value="option3" required> <label class="form-check-label" for="inlineRadio3"> <img id="option3img" src="https://media.geeksforgeeks.org/wp-content/uploads/20200114123931/femalelogo.png" class="rounded-circle rounded-sm img-fluid img-thumbnail"> </label> </div> <br> <div class="form-check form-check-inline"> <input type="submit" class="form-control mt-3 " value="Submit" name="submit" id="checked" /> </div> </form> <br><br> <span id="msg"></span> </div> <script> // On clicking submit do following $("input[type=submit]").click(function() { var atLeastOneChecked = false; $("input[type=radio]").each(function() { // If radio button not checked // display alert message if ($(this).attr("checked") != "checked") { // Alert message by displaying // error message $("#msg").html( "<span class='alert alert-danger' id='error'>" + "Please Choose atleast one</span>"); } }); }); </script></body> </html>
Output:
Approach 2: Wrap the radio buttons along with img tag for inline by using form-inline and input-group class. Then display message using alert class and trigger it with jQuery attr(), addClass() and html() methods only if radio button not checked. Finally, get checked values using jQuery val() function and concatenate it with Bootstrap alert component to display message for successful/failure of form submission. Also, use preventDefault() function to prevent form reset after submission because to display successful/failure message of submission. Don’t forget to add img tag within the above wrap after label tag.Note: Run this code in wider window.Example: The below example illustrates how to display validation message for radio buttons with images inline based on the above approach.
html
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> body { text-align: center; } #option3img { transform: rotate(270deg); } #option1img { transform: rotate(180deg); } body { margin: 55px; } input[type=submit] { position: absolute; left: 43%; top: 52%; } h1 { color: green; } </style></head> <body> <div class="container"> <h1>GeeksforGeeeks</h1> <br> <p><strong> Choose the Correct logo for GeeksforGeeks </strong></p> <form> <div class="form-inline"> <!--form group with image inline--> <div class="input-group mr-sm-2"> <div class="form-check-inline"> <label class="form-check-label input-group-text ml-2"> <input type="radio" aria-label= "Radio button for following text input" name="Radiobtn" id="option1" value="option1"> <img id="option1img" src="https://media.geeksforgeeks.org/wp-content/uploads/20200108110429/icon4.png" class="bd-placeholder-img rounded-right rounded-sm img-fluid ml-2"> </label> </div> </div> <div class="input-group mr-sm-2"> <div class="form-check-inline"> <label class="form-check-label input-group-text "> <input type="radio" aria-label="Radio button for following text input" name="Radiobtn" id="option2" value="option2"> <img id="option2img" src="https://media.geeksforgeeks.org/wp-content/uploads/20200108110429/icon4.png" class="bd-placeholder-img rounded-right rounded-sm img-fluid ml-2"> </label> </div> </div> <div class="input-group mr-sm-2"> <div class="input-group-prepend"> <div class="form-check-inline"> <label class="form-check-label input-group-text ml-2"> <input type="radio" aria-label="Radio button for following text input" name="Radiobtn" id="option3" value="option3"> <img id="option3img" src="https://media.geeksforgeeks.org/wp-content/uploads/20200108110429/icon4.png" class= "bd-placeholder-img rounded-right rounded-sm img-fluid ml-2"> </label> </div> </div> </div> </div> <div class="form-inline mt-5"> <input class="form-control mr-3 btn btn-info" type="submit" value="Submit"> </div> </form> <div class="mt-3" id="msg"></div> <div class="mt-3" id="ans"></div> </div> <script> // On clicking submit do following $("input[type=submit]").click(function() { var atLeastOneChecked = false; // If radio button not checked // display alert message $("input[type=radio]").each(function() { if ($(this).attr("checked") != "checked") { // Alert message by displaying // error message $("#msg").html('<span class="alert alert-danger alert-dismissible fade show" id="alert1">'+'Make atleast one choice'+' <button type="button" class="close" data-dismiss="alert" aria-label="Close">'+'<span aria-hidden="true" >×</span></button></span>'); } else { $("#msg").html('<span class="alert alert-success alert-dismissible fade show" id="alert2">'+'Success Choise Made'+'<button type="button" class="close" data-dismiss="alert" aria-label="Close">'+'<span aria-hidden="true" >×</span></button></span>'); } }); }); </script> <script> $(document).ready(function() { // Validation message for empty choice submission $("input[type='submit']").click(function() { var radioValue = $("input[name='Radiobtn']:checked").val(); if (radioValue) { $("#msg").html('<span class="alert alert-success alert-dismissible fade show" id="alert3">'+'Success..! You Made your Choise : <strong>' + radioValue + '</strong><button type="button" class="close" data-dismiss="alert" aria-label="Close">'+ '<span aria-hidden="true" >×</span></button></span>'); if (radioValue == 'option2') { // Validation message for correct choice $("#ans").html('<span class="alert alert-success alert-dismissible fade show" id="alert4">'+'You Have Made Correct Choise : <strong>' + radioValue +'</strong><button type="button" class="close" data-dismiss="alert" aria-label="Close">'+'<span aria-hidden="true" >×</span></button></span>'); } else { // Validation message for wrong choice $("#ans").html('<span class="alert alert-warning alert-dismissible fade show" id="alert5">'+'Warning ..! You Have Made Wrong Choise : <strong>' + radioValue +'</strong><button type="button" class="close" data-dismiss="alert" aria-label="Close">'+'<span aria-hidden="true" >×</span></button></span>'); } } }); }); // To avoid form reload after submission// $("form").submit(function(e) { e.preventDefault(); }); </script></body> </html>
Output:
Reference: https://getbootstrap.com/docs/4.4/components/forms/
kapoorsagar226
Bootstrap-4
Bootstrap-Misc
JavaScript-Misc
Picked
Bootstrap
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to pass data into a bootstrap modal?
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
Difference between Bootstrap 4 and Bootstrap 5
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24979,
"s": 24951,
"text": "\n18 Nov, 2021"
},
{
"code": null,
"e": 25649,
"s": 24979,
"text": "By Default, Bootstrap 4 has various form features for radio buttons with images inline. Here HTML 5 has default validation features, However, for custom validation, we must use JavaScript or jQuery. The following approaches would help in the display validation message for radio buttons with images inline.Approach 1: First wrap Radio buttons and its label by using form-check-inline class. Then add img tag within the above wrap after label tag. Use default required validation by adding required attribute of radio button. Finally, display message using alert class and trigger it with jQueries attr(), addClass() and html() methods only if radio button not checked. "
},
{
"code": null,
"e": 25789,
"s": 25649,
"text": "Example: The below program illustrates to display validation message for radio buttons with images inline based on the the above approach. "
},
{
"code": null,
"e": 25794,
"s": 25789,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <div class=\"container\"> <h1>GeeksforGeeeks</h1> <br><br> <p>Select Your Gender</p> <form> <div class=\"form-check form-check-inline\"> <input class=\"form-check-input\" type=\"radio\" name=\"inlineRadioOptions\" id=\"inlineRadio2\" value=\"option2\" required> <label class=\"form-check-label\" for=\"inlineRadio2\"> <img id=\"option2img\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200114123932/malelogo.png\" class=\"rounded-circle rounded-sm img-fluid img-thumbnail\"> </label> </div> <div class=\"form-check form-check-inline\"> <input class=\"form-check-input\" type=\"radio\" name=\"inlineRadioOptions\" id=\"inlineRadio3\" value=\"option3\" required> <label class=\"form-check-label\" for=\"inlineRadio3\"> <img id=\"option3img\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200114123931/femalelogo.png\" class=\"rounded-circle rounded-sm img-fluid img-thumbnail\"> </label> </div> <br> <div class=\"form-check form-check-inline\"> <input type=\"submit\" class=\"form-control mt-3 \" value=\"Submit\" name=\"submit\" id=\"checked\" /> </div> </form> <br><br> <span id=\"msg\"></span> </div> <script> // On clicking submit do following $(\"input[type=submit]\").click(function() { var atLeastOneChecked = false; $(\"input[type=radio]\").each(function() { // If radio button not checked // display alert message if ($(this).attr(\"checked\") != \"checked\") { // Alert message by displaying // error message $(\"#msg\").html( \"<span class='alert alert-danger' id='error'>\" + \"Please Choose atleast one</span>\"); } }); }); </script></body> </html>",
"e": 29002,
"s": 25794,
"text": null
},
{
"code": null,
"e": 29011,
"s": 29002,
"text": "Output: "
},
{
"code": null,
"e": 29804,
"s": 29011,
"text": "Approach 2: Wrap the radio buttons along with img tag for inline by using form-inline and input-group class. Then display message using alert class and trigger it with jQuery attr(), addClass() and html() methods only if radio button not checked. Finally, get checked values using jQuery val() function and concatenate it with Bootstrap alert component to display message for successful/failure of form submission. Also, use preventDefault() function to prevent form reset after submission because to display successful/failure message of submission. Don’t forget to add img tag within the above wrap after label tag.Note: Run this code in wider window.Example: The below example illustrates how to display validation message for radio buttons with images inline based on the above approach. "
},
{
"code": null,
"e": 29809,
"s": 29804,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> body { text-align: center; } #option3img { transform: rotate(270deg); } #option1img { transform: rotate(180deg); } body { margin: 55px; } input[type=submit] { position: absolute; left: 43%; top: 52%; } h1 { color: green; } </style></head> <body> <div class=\"container\"> <h1>GeeksforGeeeks</h1> <br> <p><strong> Choose the Correct logo for GeeksforGeeks </strong></p> <form> <div class=\"form-inline\"> <!--form group with image inline--> <div class=\"input-group mr-sm-2\"> <div class=\"form-check-inline\"> <label class=\"form-check-label input-group-text ml-2\"> <input type=\"radio\" aria-label= \"Radio button for following text input\" name=\"Radiobtn\" id=\"option1\" value=\"option1\"> <img id=\"option1img\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200108110429/icon4.png\" class=\"bd-placeholder-img rounded-right rounded-sm img-fluid ml-2\"> </label> </div> </div> <div class=\"input-group mr-sm-2\"> <div class=\"form-check-inline\"> <label class=\"form-check-label input-group-text \"> <input type=\"radio\" aria-label=\"Radio button for following text input\" name=\"Radiobtn\" id=\"option2\" value=\"option2\"> <img id=\"option2img\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200108110429/icon4.png\" class=\"bd-placeholder-img rounded-right rounded-sm img-fluid ml-2\"> </label> </div> </div> <div class=\"input-group mr-sm-2\"> <div class=\"input-group-prepend\"> <div class=\"form-check-inline\"> <label class=\"form-check-label input-group-text ml-2\"> <input type=\"radio\" aria-label=\"Radio button for following text input\" name=\"Radiobtn\" id=\"option3\" value=\"option3\"> <img id=\"option3img\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200108110429/icon4.png\" class= \"bd-placeholder-img rounded-right rounded-sm img-fluid ml-2\"> </label> </div> </div> </div> </div> <div class=\"form-inline mt-5\"> <input class=\"form-control mr-3 btn btn-info\" type=\"submit\" value=\"Submit\"> </div> </form> <div class=\"mt-3\" id=\"msg\"></div> <div class=\"mt-3\" id=\"ans\"></div> </div> <script> // On clicking submit do following $(\"input[type=submit]\").click(function() { var atLeastOneChecked = false; // If radio button not checked // display alert message $(\"input[type=radio]\").each(function() { if ($(this).attr(\"checked\") != \"checked\") { // Alert message by displaying // error message $(\"#msg\").html('<span class=\"alert alert-danger alert-dismissible fade show\" id=\"alert1\">'+'Make atleast one choice'+' <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">'+'<span aria-hidden=\"true\" >×</span></button></span>'); } else { $(\"#msg\").html('<span class=\"alert alert-success alert-dismissible fade show\" id=\"alert2\">'+'Success Choise Made'+'<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">'+'<span aria-hidden=\"true\" >×</span></button></span>'); } }); }); </script> <script> $(document).ready(function() { // Validation message for empty choice submission $(\"input[type='submit']\").click(function() { var radioValue = $(\"input[name='Radiobtn']:checked\").val(); if (radioValue) { $(\"#msg\").html('<span class=\"alert alert-success alert-dismissible fade show\" id=\"alert3\">'+'Success..! You Made your Choise : <strong>' + radioValue + '</strong><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">'+ '<span aria-hidden=\"true\" >×</span></button></span>'); if (radioValue == 'option2') { // Validation message for correct choice $(\"#ans\").html('<span class=\"alert alert-success alert-dismissible fade show\" id=\"alert4\">'+'You Have Made Correct Choise : <strong>' + radioValue +'</strong><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">'+'<span aria-hidden=\"true\" >×</span></button></span>'); } else { // Validation message for wrong choice $(\"#ans\").html('<span class=\"alert alert-warning alert-dismissible fade show\" id=\"alert5\">'+'Warning ..! You Have Made Wrong Choise : <strong>' + radioValue +'</strong><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">'+'<span aria-hidden=\"true\" >×</span></button></span>'); } } }); }); // To avoid form reload after submission// $(\"form\").submit(function(e) { e.preventDefault(); }); </script></body> </html>",
"e": 36775,
"s": 29809,
"text": null
},
{
"code": null,
"e": 36785,
"s": 36775,
"text": "Output: "
},
{
"code": null,
"e": 36849,
"s": 36785,
"text": "Reference: https://getbootstrap.com/docs/4.4/components/forms/ "
},
{
"code": null,
"e": 36864,
"s": 36849,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 36876,
"s": 36864,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 36891,
"s": 36876,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 36907,
"s": 36891,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 36914,
"s": 36907,
"text": "Picked"
},
{
"code": null,
"e": 36924,
"s": 36914,
"text": "Bootstrap"
},
{
"code": null,
"e": 36941,
"s": 36924,
"text": "Web Technologies"
},
{
"code": null,
"e": 36968,
"s": 36941,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 37066,
"s": 36968,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37075,
"s": 37066,
"text": "Comments"
},
{
"code": null,
"e": 37088,
"s": 37075,
"text": "Old Comments"
},
{
"code": null,
"e": 37129,
"s": 37088,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 37170,
"s": 37129,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 37233,
"s": 37170,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 37266,
"s": 37233,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 37313,
"s": 37266,
"text": "Difference between Bootstrap 4 and Bootstrap 5"
},
{
"code": null,
"e": 37369,
"s": 37313,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 37402,
"s": 37369,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 37464,
"s": 37402,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 37507,
"s": 37464,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Permutations of a given string using STL - GeeksforGeeks
|
03 Feb, 2021
A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Source: Mathword
Below are the permutations of string ABC.
“ABC”, “ACB”, “BAC”, “BCA”, “CBA”, “CAB”
We have discussed C implementation to print all permutations of a given string using backtracking here. In this post, C++ implementation using STL is discussed.
Method 1 (Using rotate()) std::rotate function rotates elements of a vector/string such that the passed middle element becomes first. For example, if we call rotate for “ABCD” with middle as second element, the string becomes “BCDA” and if we again call rotate with middle as second element, the string becomes “CDAB”. Refer this for a sample program.
Below is C++ implementation.
C++
// C++ program to print all permutations with// duplicates allowed using rotate() in STL#include <bits/stdc++.h>using namespace std; // Function to print permutations of string str,// out is used to store permutations one by onevoid permute(string str, string out){ // When size of str becomes 0, out has a // permutation (length of out is n) if (str.size() == 0) { cout << out << endl; return; } // One be one move all characters at // the beginning of out (or result) for (int i = 0; i < str.size(); i++) { // Remove first character from str and // add it to out permute(str.substr(1), out + str[0]); // Rotate string in a way second character // moves to the beginning. rotate(str.begin(), str.begin() + 1, str.end()); }} // Driver codeint main(){ string str = "ABC"; permute(str, ""); return 0;}
ABC
ACB
BCA
BAC
CAB
CBA
Method 2 (using next_permutation) We can use next_permutation that modifies a string so that it stores lexicographically next permutation. If current string is lexicographically largest, i.e., “CBA”, then next_permutation returns false.
We first sort the string, so that it is converted to lexicographically smallest permutation. Then we one by one call next_permutation until it returns false.
C++
// C++ program to print all permutations with// duplicates allowed using next_permutation#include <bits/stdc++.h>using namespace std; // Function to print permutations of string str// using next_permutationvoid permute(string str){ // Sort the string in lexicographically // ascending order sort(str.begin(), str.end()); // Keep printing next permutation while there // is next permutation do { cout << str << endl; } while (next_permutation(str.begin(), str.end()));} // Driver codeint main(){ string str = "CBA"; permute(str); return 0;}
ABC
ACB
BAC
BCA
CAB
CBA
Note that the second method always prints permutations in lexicographically sorted order irrespective of input string.This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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
_dayanand
kryptonian
surajv
permutation
STL
Combinatorial
Strings
Strings
permutation
Combinatorial
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find the Number of Permutations that satisfy the given condition in an array
Python program to get all subsets of given size of a set
Print all subsets of given size of a set
Find all distinct subsets of a given set using BitMasking Approach
Make all combinations of size k
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Python program to check if a string is palindrome or not
|
[
{
"code": null,
"e": 24665,
"s": 24637,
"text": "\n03 Feb, 2021"
},
{
"code": null,
"e": 24890,
"s": 24665,
"text": "A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Source: Mathword"
},
{
"code": null,
"e": 24933,
"s": 24890,
"text": "Below are the permutations of string ABC. "
},
{
"code": null,
"e": 24975,
"s": 24933,
"text": "“ABC”, “ACB”, “BAC”, “BCA”, “CBA”, “CAB” "
},
{
"code": null,
"e": 25136,
"s": 24975,
"text": "We have discussed C implementation to print all permutations of a given string using backtracking here. In this post, C++ implementation using STL is discussed."
},
{
"code": null,
"e": 25489,
"s": 25136,
"text": "Method 1 (Using rotate()) std::rotate function rotates elements of a vector/string such that the passed middle element becomes first. For example, if we call rotate for “ABCD” with middle as second element, the string becomes “BCDA” and if we again call rotate with middle as second element, the string becomes “CDAB”. Refer this for a sample program. "
},
{
"code": null,
"e": 25519,
"s": 25489,
"text": "Below is C++ implementation. "
},
{
"code": null,
"e": 25523,
"s": 25519,
"text": "C++"
},
{
"code": "// C++ program to print all permutations with// duplicates allowed using rotate() in STL#include <bits/stdc++.h>using namespace std; // Function to print permutations of string str,// out is used to store permutations one by onevoid permute(string str, string out){ // When size of str becomes 0, out has a // permutation (length of out is n) if (str.size() == 0) { cout << out << endl; return; } // One be one move all characters at // the beginning of out (or result) for (int i = 0; i < str.size(); i++) { // Remove first character from str and // add it to out permute(str.substr(1), out + str[0]); // Rotate string in a way second character // moves to the beginning. rotate(str.begin(), str.begin() + 1, str.end()); }} // Driver codeint main(){ string str = \"ABC\"; permute(str, \"\"); return 0;}",
"e": 26420,
"s": 25523,
"text": null
},
{
"code": null,
"e": 26444,
"s": 26420,
"text": "ABC\nACB\nBCA\nBAC\nCAB\nCBA"
},
{
"code": null,
"e": 26681,
"s": 26444,
"text": "Method 2 (using next_permutation) We can use next_permutation that modifies a string so that it stores lexicographically next permutation. If current string is lexicographically largest, i.e., “CBA”, then next_permutation returns false."
},
{
"code": null,
"e": 26839,
"s": 26681,
"text": "We first sort the string, so that it is converted to lexicographically smallest permutation. Then we one by one call next_permutation until it returns false."
},
{
"code": null,
"e": 26843,
"s": 26839,
"text": "C++"
},
{
"code": "// C++ program to print all permutations with// duplicates allowed using next_permutation#include <bits/stdc++.h>using namespace std; // Function to print permutations of string str// using next_permutationvoid permute(string str){ // Sort the string in lexicographically // ascending order sort(str.begin(), str.end()); // Keep printing next permutation while there // is next permutation do { cout << str << endl; } while (next_permutation(str.begin(), str.end()));} // Driver codeint main(){ string str = \"CBA\"; permute(str); return 0;}",
"e": 27420,
"s": 26843,
"text": null
},
{
"code": null,
"e": 27444,
"s": 27420,
"text": "ABC\nACB\nBAC\nBCA\nCAB\nCBA"
},
{
"code": null,
"e": 27951,
"s": 27444,
"text": "Note that the second method always prints permutations in lexicographically sorted order irrespective of input string.This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 "
},
{
"code": null,
"e": 27961,
"s": 27951,
"text": "_dayanand"
},
{
"code": null,
"e": 27972,
"s": 27961,
"text": "kryptonian"
},
{
"code": null,
"e": 27979,
"s": 27972,
"text": "surajv"
},
{
"code": null,
"e": 27991,
"s": 27979,
"text": "permutation"
},
{
"code": null,
"e": 27995,
"s": 27991,
"text": "STL"
},
{
"code": null,
"e": 28009,
"s": 27995,
"text": "Combinatorial"
},
{
"code": null,
"e": 28017,
"s": 28009,
"text": "Strings"
},
{
"code": null,
"e": 28025,
"s": 28017,
"text": "Strings"
},
{
"code": null,
"e": 28037,
"s": 28025,
"text": "permutation"
},
{
"code": null,
"e": 28051,
"s": 28037,
"text": "Combinatorial"
},
{
"code": null,
"e": 28055,
"s": 28051,
"text": "STL"
},
{
"code": null,
"e": 28153,
"s": 28055,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28162,
"s": 28153,
"text": "Comments"
},
{
"code": null,
"e": 28175,
"s": 28162,
"text": "Old Comments"
},
{
"code": null,
"e": 28252,
"s": 28175,
"text": "Find the Number of Permutations that satisfy the given condition in an array"
},
{
"code": null,
"e": 28309,
"s": 28252,
"text": "Python program to get all subsets of given size of a set"
},
{
"code": null,
"e": 28350,
"s": 28309,
"text": "Print all subsets of given size of a set"
},
{
"code": null,
"e": 28417,
"s": 28350,
"text": "Find all distinct subsets of a given set using BitMasking Approach"
},
{
"code": null,
"e": 28449,
"s": 28417,
"text": "Make all combinations of size k"
},
{
"code": null,
"e": 28474,
"s": 28449,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 28520,
"s": 28474,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 28554,
"s": 28520,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 28569,
"s": 28554,
"text": "C++ Data Types"
}
] |
Get data from sessionStorage in JavaScript?
|
The localStorage and sessionStorage properties allow to save key/value pairs in a web browser. The sessionStorage object stores data for only one session. The data will be deleted when the browser is closed. It works the same as local storage. Initially, we have to check whether the browser supports the session storage or not. Later on, we have to create the data and have to retrieve the data.
sessionStorage.setItem();
Live Demo
<html>
<body>
<p> id = "storage"</p>
<script>
if (typeof(Storage) !== "undefined") {
sessionStorage.setItem("product", "Tutorix");
document.getElementById("storage").innerHTML = sessionStorage.getItem("product");
}
else {
document.getElementById("storage").innerHTML = "Sorry,no Web Storage compatibility...";
}
</script>
</body>
</html>
Tutorix
|
[
{
"code": null,
"e": 1460,
"s": 1062,
"text": "The localStorage and sessionStorage properties allow to save key/value pairs in a web browser. The sessionStorage object stores data for only one session. The data will be deleted when the browser is closed. It works the same as local storage. Initially, we have to check whether the browser supports the session storage or not. Later on, we have to create the data and have to retrieve the data. "
},
{
"code": null,
"e": 1486,
"s": 1460,
"text": "sessionStorage.setItem();"
},
{
"code": null,
"e": 1496,
"s": 1486,
"text": "Live Demo"
},
{
"code": null,
"e": 1864,
"s": 1496,
"text": "<html>\n<body>\n<p> id = \"storage\"</p>\n<script>\n if (typeof(Storage) !== \"undefined\") {\n sessionStorage.setItem(\"product\", \"Tutorix\");\n document.getElementById(\"storage\").innerHTML = sessionStorage.getItem(\"product\");\n }\n else {\n document.getElementById(\"storage\").innerHTML = \"Sorry,no Web Storage compatibility...\";\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1872,
"s": 1864,
"text": "Tutorix"
}
] |
How to Install Azure PowerShell Cmdlets?
|
Before Installing the Azure cmdlets for PowerShell, it is recommended to upgrade it to the PowerShell version 7.X to leverage the new features.
To install the PowerShell cmdlets for Azure, you need to download and install the AZ module.
Install-Module -Name Az -AllowClobber -Scope CurrentUser
To install it for all the users,
Install-Module -Name Az -AllowClobber -Scope AllUsers
If the AzureRM module is already installed, you first need to uninstall it because both modules AzureRM and AZ cannot reside in the same console and the AzureRm module is going to decommission soon. So anyway we need to upgrade it to the latest AZ Module.
To uninstall the AzureRM module use command,
Uninstall-Module AzureRm -Force -Verbose
|
[
{
"code": null,
"e": 1206,
"s": 1062,
"text": "Before Installing the Azure cmdlets for PowerShell, it is recommended to upgrade it to the PowerShell version 7.X to leverage the new features."
},
{
"code": null,
"e": 1299,
"s": 1206,
"text": "To install the PowerShell cmdlets for Azure, you need to download and install the AZ module."
},
{
"code": null,
"e": 1356,
"s": 1299,
"text": "Install-Module -Name Az -AllowClobber -Scope CurrentUser"
},
{
"code": null,
"e": 1389,
"s": 1356,
"text": "To install it for all the users,"
},
{
"code": null,
"e": 1443,
"s": 1389,
"text": "Install-Module -Name Az -AllowClobber -Scope AllUsers"
},
{
"code": null,
"e": 1699,
"s": 1443,
"text": "If the AzureRM module is already installed, you first need to uninstall it because both modules AzureRM and AZ cannot reside in the same console and the AzureRm module is going to decommission soon. So anyway we need to upgrade it to the latest AZ Module."
},
{
"code": null,
"e": 1744,
"s": 1699,
"text": "To uninstall the AzureRM module use command,"
},
{
"code": null,
"e": 1785,
"s": 1744,
"text": "Uninstall-Module AzureRm -Force -Verbose"
}
] |
Code Optimization Technique (logical AND and logical OR) - GeeksforGeeks
|
14 Dec, 2021
While using && (logical AND), we must put the condition first whose probability of getting false is high so that compiler doesn’t need to check the second condition if the first condition is false.
C++14
Python3
#include <bits/stdc++.h>using namespace std;// Function to check whether n is oddbool isOdd(int n) { return (n & 1); } // Function to check whether n is primebool isPrime(int n){ if (n <= 1) return false; for (int i = 2; i <= sqrt(n); i++) if ((n % i) == 0) return false; return true;} int main(){ int cnt = 0, n = 10; // Implementation 1 for (int i = 2; i <= n; i++) { if (isOdd(i) && isPrime(i)) cnt++; } cnt = 0; n = 10; // Implementation 2 for (int i = 2; i <= n; i++) { if (isPrime(i) && isOdd(i)) cnt++; }}
# Function to check whether n is odddef isOdd(n): pass # Function to check whether n is primedef isPrime(n): pass if __name__ == '__main__': cnt = 0; n = 10 # Implementation 1 for i in range(2,n) : if isOdd(i) and isPrime(i): cnt+=1 cnt = 0 n = 10 # Implementation 2 for i in range(2,n): if isPrime(i) and isOdd(i): cnt+=1
Consider the above implementation:
In implementation 1, we avoid checking even numbers whether they are prime or not as primality test requires more computation than checking a number for even/odd. Probability of a number getting odd is more than of it being a prime that’s why we first check whether the number is odd before checking it for prime.
On the other hand in implementation 2, we are checking whether the number is prime or not before checking whether it is odd which makes unnecessary computation as all even numbers other than 2 are not prime but the implementation still checks them for prime.
While using || (logical OR), we must put the condition first whose probability of getting true is high so that compiler doesn’t need to check the second condition if the first condition is true.
C
Python3
#include <iostream.h> // Function to check whether n is oddbool isEven(int n); // Function to check whether n is primebool isPrime(int n); int main(){ int cnt = 0, n = 10; // Implementation 1 for (int i = 3; i <= n; i++) { if (isEven(i) || !isPrime(i)) cnt++; }}
# Function to check whether n is evendef isEven(n): pass # Function to check whether n is primedef isPrime(n): pass if __name__ == '__main__': cnt = 0; n = 10 # Implementation 1 for i in range(3,n) : if isOdd(i) or not isPrime(i): cnt+=1
As described earlier that the probability of a number being even is more than that of it being a non-prime. The current order of execution of the statements doesn’t allow even numbers greater than 2 to be checked whether they are non-prime (as they are all non-primes).
Note: For larger inputs, the order of the execution of statements can affect the overall execution time for the program.
amartyaghoshgfg
Algorithms
Analysis
Articles
C Language
Programming Language
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SCAN (Elevator) Disk Scheduling Algorithms
Rail Fence Cipher - Encryption and Decryption
Program for SSTF disk scheduling algorithm
Quadratic Probing in Hashing
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Time Complexity and Space Complexity
Practice Questions on Time Complexity Analysis
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
|
[
{
"code": null,
"e": 24702,
"s": 24674,
"text": "\n14 Dec, 2021"
},
{
"code": null,
"e": 24901,
"s": 24702,
"text": "While using && (logical AND), we must put the condition first whose probability of getting false is high so that compiler doesn’t need to check the second condition if the first condition is false. "
},
{
"code": null,
"e": 24907,
"s": 24901,
"text": "C++14"
},
{
"code": null,
"e": 24915,
"s": 24907,
"text": "Python3"
},
{
"code": "#include <bits/stdc++.h>using namespace std;// Function to check whether n is oddbool isOdd(int n) { return (n & 1); } // Function to check whether n is primebool isPrime(int n){ if (n <= 1) return false; for (int i = 2; i <= sqrt(n); i++) if ((n % i) == 0) return false; return true;} int main(){ int cnt = 0, n = 10; // Implementation 1 for (int i = 2; i <= n; i++) { if (isOdd(i) && isPrime(i)) cnt++; } cnt = 0; n = 10; // Implementation 2 for (int i = 2; i <= n; i++) { if (isPrime(i) && isOdd(i)) cnt++; }}",
"e": 25528,
"s": 24915,
"text": null
},
{
"code": "# Function to check whether n is odddef isOdd(n): pass # Function to check whether n is primedef isPrime(n): pass if __name__ == '__main__': cnt = 0; n = 10 # Implementation 1 for i in range(2,n) : if isOdd(i) and isPrime(i): cnt+=1 cnt = 0 n = 10 # Implementation 2 for i in range(2,n): if isPrime(i) and isOdd(i): cnt+=1 ",
"e": 25926,
"s": 25528,
"text": null
},
{
"code": null,
"e": 25963,
"s": 25926,
"text": "Consider the above implementation: "
},
{
"code": null,
"e": 26279,
"s": 25963,
"text": "In implementation 1, we avoid checking even numbers whether they are prime or not as primality test requires more computation than checking a number for even/odd. Probability of a number getting odd is more than of it being a prime that’s why we first check whether the number is odd before checking it for prime. "
},
{
"code": null,
"e": 26542,
"s": 26281,
"text": "On the other hand in implementation 2, we are checking whether the number is prime or not before checking whether it is odd which makes unnecessary computation as all even numbers other than 2 are not prime but the implementation still checks them for prime. "
},
{
"code": null,
"e": 26740,
"s": 26544,
"text": "While using || (logical OR), we must put the condition first whose probability of getting true is high so that compiler doesn’t need to check the second condition if the first condition is true. "
},
{
"code": null,
"e": 26742,
"s": 26740,
"text": "C"
},
{
"code": null,
"e": 26750,
"s": 26742,
"text": "Python3"
},
{
"code": "#include <iostream.h> // Function to check whether n is oddbool isEven(int n); // Function to check whether n is primebool isPrime(int n); int main(){ int cnt = 0, n = 10; // Implementation 1 for (int i = 3; i <= n; i++) { if (isEven(i) || !isPrime(i)) cnt++; }}",
"e": 27044,
"s": 26750,
"text": null
},
{
"code": "# Function to check whether n is evendef isEven(n): pass # Function to check whether n is primedef isPrime(n): pass if __name__ == '__main__': cnt = 0; n = 10 # Implementation 1 for i in range(3,n) : if isOdd(i) or not isPrime(i): cnt+=1",
"e": 27316,
"s": 27044,
"text": null
},
{
"code": null,
"e": 27588,
"s": 27316,
"text": "As described earlier that the probability of a number being even is more than that of it being a non-prime. The current order of execution of the statements doesn’t allow even numbers greater than 2 to be checked whether they are non-prime (as they are all non-primes). "
},
{
"code": null,
"e": 27710,
"s": 27588,
"text": "Note: For larger inputs, the order of the execution of statements can affect the overall execution time for the program. "
},
{
"code": null,
"e": 27726,
"s": 27710,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 27737,
"s": 27726,
"text": "Algorithms"
},
{
"code": null,
"e": 27746,
"s": 27737,
"text": "Analysis"
},
{
"code": null,
"e": 27755,
"s": 27746,
"text": "Articles"
},
{
"code": null,
"e": 27766,
"s": 27755,
"text": "C Language"
},
{
"code": null,
"e": 27787,
"s": 27766,
"text": "Programming Language"
},
{
"code": null,
"e": 27798,
"s": 27787,
"text": "Algorithms"
},
{
"code": null,
"e": 27896,
"s": 27798,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27921,
"s": 27896,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 27964,
"s": 27921,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 28010,
"s": 27964,
"text": "Rail Fence Cipher - Encryption and Decryption"
},
{
"code": null,
"e": 28053,
"s": 28010,
"text": "Program for SSTF disk scheduling algorithm"
},
{
"code": null,
"e": 28082,
"s": 28053,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 28135,
"s": 28082,
"text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)"
},
{
"code": null,
"e": 28172,
"s": 28135,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 28219,
"s": 28172,
"text": "Practice Questions on Time Complexity Analysis"
},
{
"code": null,
"e": 28302,
"s": 28219,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
}
] |
fold command in Linux with examples - GeeksforGeeks
|
15 May, 2019
fold command in Linux wraps each line in an input file to fit a specified width and prints it to the standard output. By default, it wraps lines at a maximum width of 80 columns but this is configurable. To fold input using the fold command pass a file or standard input to the command.
Syntax:
$ fold [OPTION]... [FILE]...
Using fold command:
$ fold GfG.txt
In the above example we have passed a text file named GfG to fold command and as you can see in output it wraps the line up to 80 columns.
Different options of fold command :
-w :By using this option in fold command, we can limit the width by number of columns. By using this command we change the column width from default width of 80.Syntax:$ fold -w[n] GfG.txtIn the above example, we wrap the lines of GfG.txt to a width of 60 columns.
Syntax:
$ fold -w[n] GfG.txt
In the above example, we wrap the lines of GfG.txt to a width of 60 columns.
-b :this option of fold command is used to limit the width of the output by the number of bytes rather than the number of columns. By using this we can enforce the width of the output to the number of bytes.Syntax:$ fold -b[n] GfG.txtIn the above example, we have limited the output width of the file to 40 bytes and the command breaks the output at 40 bytes.
Syntax:
$ fold -b[n] GfG.txt
In the above example, we have limited the output width of the file to 40 bytes and the command breaks the output at 40 bytes.
-s : This option is used to break the lines on spaces so that words are not broken. If a segment of the line contains a blank character within the first width column positions, break the line after the last such blank character meeting the width constraints.Syntax:$ fold -w[n] -s GfG.txtIf you compare the above example with the previous one, you will see that the lines only break at spaces, whereas, in other examples, the output is displayed in such a way that some of the words are broken between the lines.
Syntax:
$ fold -w[n] -s GfG.txt
If you compare the above example with the previous one, you will see that the lines only break at spaces, whereas, in other examples, the output is displayed in such a way that some of the words are broken between the lines.
linux-command
Linux-text-processing-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
Cat command in Linux with examples
Tail command in Linux with examples
touch command in Linux with Examples
Mutex lock for Linux Thread Synchronization
echo command in Linux with Examples
tee command in Linux with examples
Compiling with g++
|
[
{
"code": null,
"e": 24028,
"s": 24000,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 24315,
"s": 24028,
"text": "fold command in Linux wraps each line in an input file to fit a specified width and prints it to the standard output. By default, it wraps lines at a maximum width of 80 columns but this is configurable. To fold input using the fold command pass a file or standard input to the command."
},
{
"code": null,
"e": 24323,
"s": 24315,
"text": "Syntax:"
},
{
"code": null,
"e": 24352,
"s": 24323,
"text": "$ fold [OPTION]... [FILE]..."
},
{
"code": null,
"e": 24372,
"s": 24352,
"text": "Using fold command:"
},
{
"code": null,
"e": 24387,
"s": 24372,
"text": "$ fold GfG.txt"
},
{
"code": null,
"e": 24526,
"s": 24387,
"text": "In the above example we have passed a text file named GfG to fold command and as you can see in output it wraps the line up to 80 columns."
},
{
"code": null,
"e": 24562,
"s": 24526,
"text": "Different options of fold command :"
},
{
"code": null,
"e": 24827,
"s": 24562,
"text": "-w :By using this option in fold command, we can limit the width by number of columns. By using this command we change the column width from default width of 80.Syntax:$ fold -w[n] GfG.txtIn the above example, we wrap the lines of GfG.txt to a width of 60 columns."
},
{
"code": null,
"e": 24835,
"s": 24827,
"text": "Syntax:"
},
{
"code": null,
"e": 24856,
"s": 24835,
"text": "$ fold -w[n] GfG.txt"
},
{
"code": null,
"e": 24933,
"s": 24856,
"text": "In the above example, we wrap the lines of GfG.txt to a width of 60 columns."
},
{
"code": null,
"e": 25293,
"s": 24933,
"text": "-b :this option of fold command is used to limit the width of the output by the number of bytes rather than the number of columns. By using this we can enforce the width of the output to the number of bytes.Syntax:$ fold -b[n] GfG.txtIn the above example, we have limited the output width of the file to 40 bytes and the command breaks the output at 40 bytes."
},
{
"code": null,
"e": 25301,
"s": 25293,
"text": "Syntax:"
},
{
"code": null,
"e": 25322,
"s": 25301,
"text": "$ fold -b[n] GfG.txt"
},
{
"code": null,
"e": 25448,
"s": 25322,
"text": "In the above example, we have limited the output width of the file to 40 bytes and the command breaks the output at 40 bytes."
},
{
"code": null,
"e": 25961,
"s": 25448,
"text": "-s : This option is used to break the lines on spaces so that words are not broken. If a segment of the line contains a blank character within the first width column positions, break the line after the last such blank character meeting the width constraints.Syntax:$ fold -w[n] -s GfG.txtIf you compare the above example with the previous one, you will see that the lines only break at spaces, whereas, in other examples, the output is displayed in such a way that some of the words are broken between the lines."
},
{
"code": null,
"e": 25969,
"s": 25961,
"text": "Syntax:"
},
{
"code": null,
"e": 25993,
"s": 25969,
"text": "$ fold -w[n] -s GfG.txt"
},
{
"code": null,
"e": 26218,
"s": 25993,
"text": "If you compare the above example with the previous one, you will see that the lines only break at spaces, whereas, in other examples, the output is displayed in such a way that some of the words are broken between the lines."
},
{
"code": null,
"e": 26232,
"s": 26218,
"text": "linux-command"
},
{
"code": null,
"e": 26263,
"s": 26232,
"text": "Linux-text-processing-commands"
},
{
"code": null,
"e": 26270,
"s": 26263,
"text": "Picked"
},
{
"code": null,
"e": 26281,
"s": 26270,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26379,
"s": 26281,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26414,
"s": 26379,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 26452,
"s": 26414,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 26490,
"s": 26452,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 26525,
"s": 26490,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 26561,
"s": 26525,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 26598,
"s": 26561,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 26642,
"s": 26598,
"text": "Mutex lock for Linux Thread Synchronization"
},
{
"code": null,
"e": 26678,
"s": 26642,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 26713,
"s": 26678,
"text": "tee command in Linux with examples"
}
] |
How to stop multiple services using PowerShell?
|
To stop multiple services can be stopped using Name or displayname by providing command (,) between them.
With name and DisplayName,
Stop-Service -Name Spooler, W32Time -Verbose
Stop-Service -DisplayName "Print Spooler","Windows Time" –Verbose
|
[
{
"code": null,
"e": 1168,
"s": 1062,
"text": "To stop multiple services can be stopped using Name or displayname by providing command (,) between them."
},
{
"code": null,
"e": 1195,
"s": 1168,
"text": "With name and DisplayName,"
},
{
"code": null,
"e": 1306,
"s": 1195,
"text": "Stop-Service -Name Spooler, W32Time -Verbose\nStop-Service -DisplayName \"Print Spooler\",\"Windows Time\" –Verbose"
}
] |
SQL - RDBMS Concepts
|
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
A Relational database management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced by E. F. Codd.
The data in an RDBMS is stored in database objects which are called as tables. This table is basically a collection of related data entries and it consists of numerous columns and rows.
Remember, a table is the most common and simplest form of data storage in a relational database. The following program is an example of a CUSTOMERS table −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY.
A field is a column in a table that is designed to maintain specific information about every record in the table.
A record is also called as a row of data is each individual entry that exists in a table. For example, there are 7 records in the above CUSTOMERS table. Following is a single row of data or record in the CUSTOMERS table −
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+
A record is a horizontal entity in a table.
A column is a vertical entity in a table that contains all information associated with a specific field in a table.
For example, a column in the CUSTOMERS table is ADDRESS, which represents location description and would be as shown below −
+-----------+
| ADDRESS |
+-----------+
| Ahmedabad |
| Delhi |
| Kota |
| Mumbai |
| Bhopal |
| MP |
| Indore |
+----+------+
A NULL value in a table is a value in a field that appears to be blank, which means a field with a NULL value is a field with no value.
It is very important to understand that a NULL value is different than a zero value or a field that contains spaces. A field with a NULL value is the one that has been left blank during a record creation.
Constraints are the rules enforced on data columns on a table. These are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the database.
Constraints can either be column level or table level. Column level constraints are applied only to one column whereas, table level constraints are applied to the entire table.
Following are some of the most commonly used constraints available in SQL −
NOT NULL Constraint − Ensures that a column cannot have a NULL value.
NOT NULL Constraint − Ensures that a column cannot have a NULL value.
DEFAULT Constraint − Provides a default value for a column when none is specified.
DEFAULT Constraint − Provides a default value for a column when none is specified.
UNIQUE Constraint − Ensures that all the values in a column are different.
UNIQUE Constraint − Ensures that all the values in a column are different.
PRIMARY Key − Uniquely identifies each row/record in a database table.
PRIMARY Key − Uniquely identifies each row/record in a database table.
FOREIGN Key − Uniquely identifies a row/record in any another database table.
FOREIGN Key − Uniquely identifies a row/record in any another database table.
CHECK Constraint − The CHECK constraint ensures that all values in a column satisfy certain conditions.
CHECK Constraint − The CHECK constraint ensures that all values in a column satisfy certain conditions.
INDEX − Used to create and retrieve data from the database very quickly.
INDEX − Used to create and retrieve data from the database very quickly.
The following categories of data integrity exist with each RDBMS −
Entity Integrity − There are no duplicate rows in a table.
Entity Integrity − There are no duplicate rows in a table.
Domain Integrity − Enforces valid entries for a given column by restricting the type, the format, or the range of values.
Domain Integrity − Enforces valid entries for a given column by restricting the type, the format, or the range of values.
Referential integrity − Rows cannot be deleted, which are used by other records.
Referential integrity − Rows cannot be deleted, which are used by other records.
User-Defined Integrity − Enforces some specific business rules that do not fall into entity, domain or referential integrity.
User-Defined Integrity − Enforces some specific business rules that do not fall into entity, domain or referential integrity.
Database normalization is the process of efficiently organizing data in a database. There are two reasons of this normalization process −
Eliminating redundant data, for example, storing the same data in more than one table.
Eliminating redundant data, for example, storing the same data in more than one table.
Ensuring data dependencies make sense.
Ensuring data dependencies make sense.
Both these reasons are worthy goals as they reduce the amount of space a database consumes and ensures that data is logically stored. Normalization consists of a series of guidelines that help guide you in creating a good database structure.
Normalization guidelines are divided into normal forms; think of a form as the format or the way a database structure is laid out. The aim of normal forms is to organize the database structure, so that it complies with the rules of first normal form, then second normal form and finally the third normal form.
It is your choice to take it further and go to the fourth normal form, fifth normal form and so on, but in general, the third normal form is more than enough.
First Normal Form (1NF)
Second Normal Form (2NF)
Third Normal Form (3NF)
42 Lectures
5 hours
Anadi Sharma
14 Lectures
2 hours
Anadi Sharma
44 Lectures
4.5 hours
Anadi Sharma
94 Lectures
7 hours
Abhishek And Pukhraj
80 Lectures
6.5 hours
Oracle Master Training | 150,000+ Students Worldwide
31 Lectures
6 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2639,
"s": 2453,
"text": "RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access."
},
{
"code": null,
"e": 2793,
"s": 2639,
"text": "A Relational database management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced by E. F. Codd."
},
{
"code": null,
"e": 2979,
"s": 2793,
"text": "The data in an RDBMS is stored in database objects which are called as tables. This table is basically a collection of related data entries and it consists of numerous columns and rows."
},
{
"code": null,
"e": 3135,
"s": 2979,
"text": "Remember, a table is the most common and simplest form of data storage in a relational database. The following program is an example of a CUSTOMERS table −"
},
{
"code": null,
"e": 3652,
"s": 3135,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+"
},
{
"code": null,
"e": 3794,
"s": 3652,
"text": "Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY."
},
{
"code": null,
"e": 3908,
"s": 3794,
"text": "A field is a column in a table that is designed to maintain specific information about every record in the table."
},
{
"code": null,
"e": 4130,
"s": 3908,
"text": "A record is also called as a row of data is each individual entry that exists in a table. For example, there are 7 records in the above CUSTOMERS table. Following is a single row of data or record in the CUSTOMERS table −"
},
{
"code": null,
"e": 4271,
"s": 4130,
"text": "+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n+----+----------+-----+-----------+----------+"
},
{
"code": null,
"e": 4315,
"s": 4271,
"text": "A record is a horizontal entity in a table."
},
{
"code": null,
"e": 4431,
"s": 4315,
"text": "A column is a vertical entity in a table that contains all information associated with a specific field in a table."
},
{
"code": null,
"e": 4556,
"s": 4431,
"text": "For example, a column in the CUSTOMERS table is ADDRESS, which represents location description and would be as shown below −"
},
{
"code": null,
"e": 4710,
"s": 4556,
"text": "+-----------+\n| ADDRESS |\n+-----------+\n| Ahmedabad |\n| Delhi |\n| Kota |\n| Mumbai |\n| Bhopal |\n| MP |\n| Indore |\n+----+------+"
},
{
"code": null,
"e": 4846,
"s": 4710,
"text": "A NULL value in a table is a value in a field that appears to be blank, which means a field with a NULL value is a field with no value."
},
{
"code": null,
"e": 5051,
"s": 4846,
"text": "It is very important to understand that a NULL value is different than a zero value or a field that contains spaces. A field with a NULL value is the one that has been left blank during a record creation."
},
{
"code": null,
"e": 5252,
"s": 5051,
"text": "Constraints are the rules enforced on data columns on a table. These are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the database."
},
{
"code": null,
"e": 5429,
"s": 5252,
"text": "Constraints can either be column level or table level. Column level constraints are applied only to one column whereas, table level constraints are applied to the entire table."
},
{
"code": null,
"e": 5505,
"s": 5429,
"text": "Following are some of the most commonly used constraints available in SQL −"
},
{
"code": null,
"e": 5575,
"s": 5505,
"text": "NOT NULL Constraint − Ensures that a column cannot have a NULL value."
},
{
"code": null,
"e": 5645,
"s": 5575,
"text": "NOT NULL Constraint − Ensures that a column cannot have a NULL value."
},
{
"code": null,
"e": 5728,
"s": 5645,
"text": "DEFAULT Constraint − Provides a default value for a column when none is specified."
},
{
"code": null,
"e": 5811,
"s": 5728,
"text": "DEFAULT Constraint − Provides a default value for a column when none is specified."
},
{
"code": null,
"e": 5886,
"s": 5811,
"text": "UNIQUE Constraint − Ensures that all the values in a column are different."
},
{
"code": null,
"e": 5961,
"s": 5886,
"text": "UNIQUE Constraint − Ensures that all the values in a column are different."
},
{
"code": null,
"e": 6032,
"s": 5961,
"text": "PRIMARY Key − Uniquely identifies each row/record in a database table."
},
{
"code": null,
"e": 6103,
"s": 6032,
"text": "PRIMARY Key − Uniquely identifies each row/record in a database table."
},
{
"code": null,
"e": 6181,
"s": 6103,
"text": "FOREIGN Key − Uniquely identifies a row/record in any another database table."
},
{
"code": null,
"e": 6259,
"s": 6181,
"text": "FOREIGN Key − Uniquely identifies a row/record in any another database table."
},
{
"code": null,
"e": 6363,
"s": 6259,
"text": "CHECK Constraint − The CHECK constraint ensures that all values in a column satisfy certain conditions."
},
{
"code": null,
"e": 6467,
"s": 6363,
"text": "CHECK Constraint − The CHECK constraint ensures that all values in a column satisfy certain conditions."
},
{
"code": null,
"e": 6540,
"s": 6467,
"text": "INDEX − Used to create and retrieve data from the database very quickly."
},
{
"code": null,
"e": 6613,
"s": 6540,
"text": "INDEX − Used to create and retrieve data from the database very quickly."
},
{
"code": null,
"e": 6680,
"s": 6613,
"text": "The following categories of data integrity exist with each RDBMS −"
},
{
"code": null,
"e": 6739,
"s": 6680,
"text": "Entity Integrity − There are no duplicate rows in a table."
},
{
"code": null,
"e": 6798,
"s": 6739,
"text": "Entity Integrity − There are no duplicate rows in a table."
},
{
"code": null,
"e": 6920,
"s": 6798,
"text": "Domain Integrity − Enforces valid entries for a given column by restricting the type, the format, or the range of values."
},
{
"code": null,
"e": 7042,
"s": 6920,
"text": "Domain Integrity − Enforces valid entries for a given column by restricting the type, the format, or the range of values."
},
{
"code": null,
"e": 7123,
"s": 7042,
"text": "Referential integrity − Rows cannot be deleted, which are used by other records."
},
{
"code": null,
"e": 7204,
"s": 7123,
"text": "Referential integrity − Rows cannot be deleted, which are used by other records."
},
{
"code": null,
"e": 7330,
"s": 7204,
"text": "User-Defined Integrity − Enforces some specific business rules that do not fall into entity, domain or referential integrity."
},
{
"code": null,
"e": 7456,
"s": 7330,
"text": "User-Defined Integrity − Enforces some specific business rules that do not fall into entity, domain or referential integrity."
},
{
"code": null,
"e": 7594,
"s": 7456,
"text": "Database normalization is the process of efficiently organizing data in a database. There are two reasons of this normalization process −"
},
{
"code": null,
"e": 7681,
"s": 7594,
"text": "Eliminating redundant data, for example, storing the same data in more than one table."
},
{
"code": null,
"e": 7768,
"s": 7681,
"text": "Eliminating redundant data, for example, storing the same data in more than one table."
},
{
"code": null,
"e": 7807,
"s": 7768,
"text": "Ensuring data dependencies make sense."
},
{
"code": null,
"e": 7846,
"s": 7807,
"text": "Ensuring data dependencies make sense."
},
{
"code": null,
"e": 8088,
"s": 7846,
"text": "Both these reasons are worthy goals as they reduce the amount of space a database consumes and ensures that data is logically stored. Normalization consists of a series of guidelines that help guide you in creating a good database structure."
},
{
"code": null,
"e": 8398,
"s": 8088,
"text": "Normalization guidelines are divided into normal forms; think of a form as the format or the way a database structure is laid out. The aim of normal forms is to organize the database structure, so that it complies with the rules of first normal form, then second normal form and finally the third normal form."
},
{
"code": null,
"e": 8557,
"s": 8398,
"text": "It is your choice to take it further and go to the fourth normal form, fifth normal form and so on, but in general, the third normal form is more than enough."
},
{
"code": null,
"e": 8581,
"s": 8557,
"text": "First Normal Form (1NF)"
},
{
"code": null,
"e": 8606,
"s": 8581,
"text": "Second Normal Form (2NF)"
},
{
"code": null,
"e": 8630,
"s": 8606,
"text": "Third Normal Form (3NF)"
},
{
"code": null,
"e": 8663,
"s": 8630,
"text": "\n 42 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 8677,
"s": 8663,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8710,
"s": 8677,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8724,
"s": 8710,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8759,
"s": 8724,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8773,
"s": 8759,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8806,
"s": 8773,
"text": "\n 94 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 8828,
"s": 8806,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 8863,
"s": 8828,
"text": "\n 80 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 8917,
"s": 8863,
"text": " Oracle Master Training | 150,000+ Students Worldwide"
},
{
"code": null,
"e": 8950,
"s": 8917,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 8978,
"s": 8950,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 8985,
"s": 8978,
"text": " Print"
},
{
"code": null,
"e": 8996,
"s": 8985,
"text": " Add Notes"
}
] |
Huber and Ridge Regressions in Python: Dealing with Outliers | by Michael Grogan | Towards Data Science
|
Traditional linear regression can prove to have some shortcomings when it comes to handling outliers in a set of data.
Specifically, if a data point lies very far away from other points in the set — this can significantly influence the least squares regression line, i.e. the line that approximates the overall direction of the set of data points will be skewed by the presence of outliers.
In an attempt to guard against this shortcoming, it is possible to use modified regression models that are robust to outliers. In this particular instance, we will take a look at the Huber and Ridge regression models.
The dataset that is used in this instance is the Pima Indians Diabetes dataset as originally from the National Institute of Diabetes and Digestive and Kidney Diseases and made available under the CC0 1.0 Universal (CC0 1.0) Public Domain Dedication license.
For this particular scenario, a regression model will be built to predict body mass index (BMI) levels across patients.
When looking at a boxplot of BMI, we can see that there exist significant outliers as evidenced by the data points in the top half of the graph.
# Creating plotplt.boxplot(bmi)plt.ylabel("BMI")plt.title("Body Mass Index")# show plotplt.show()
A correlation matrix across the data was then created:
corr = a.corr()corr
Here is a visual using seaborn:
sns.heatmap(a.corr());
Of the independent variables, Skin Thickness and Glucose were chosen as the two variables that are hypothesised to have a significant effect on BMI.
A regression was run across the training data which produced the following results:
According to the above results:
A 1 unit increase in Skin Thickness leads to a 0.1597 increase in BMI — holding all other variables constant.
A 1 unit increase in Glucose levels leads to a 0.0418 increase in BMI — holding all other variables constant.
We see that these two variables are highly significant at all levels (given p-values of 0). While the R-Squared of 17.5% is low — this does not necessarily mean that the model is bad. Given that there are a wide range of variables that can influence BMI fluctuations — this simply indicates that there are many variables that this model does not account for. However, the two independent variables being used show a highly significant relationship.
Predictions were generated across the validation set and a root mean squared error (RMSE) value was calculated. RMSE is used in this instance as the score is more sensitive to outliers. The higher the score, the more error in the forecast predictions.
>>> olspredictions = results.predict(X_val)>>> print(olspredictions)[36.32534071 31.09716546 28.67493585 34.29867119 35.03070074... 36.50971909 35.97416079 36.57591618 35.10923948 34.3672371]
The root mean squared error is calculated:
>>> mean_squared_error(y_val, olspredictions)>>> math.sqrt(mean_squared_error(y_val, olspredictions))5.830559762277098>>> np.mean(y_val)31.809333333333342
The value of the root mean squared error is 5.83 relative to the mean of 31.81 across the validation set.
Now, we will generate Huber and Ridge regression models. In the same way, predictions will be made against the validation set using these models and the root mean squared error will be calculated.
Both the Huber and Ridge regressions are designed to produce a regression line that is less sensitive to outliers than standard linear regression.
However, the way in which these models work in doing so differ slightly.
Specifically, Huber regression relies on what is known as the M-estimate, or measures of location that are less sensitive to outliers than the mean (as described in the Oxford Dictionary of Statistics (Upton and Cook, 2014)).
A Ridge regression uses what is known as L2 regularization — which makes the weights of the outlier values smaller so as to have less of an effect on the regression line. Additionally, L2 regularization attempts to estimate the mean of the data to avoid overfitting, whereas L1 regularization (as used in a Lasso regression) attempts to estimate the median of the data.
In this example, predictions will be made using the Huber and Ridge regressions, in order to compute the RMSE of the predictions against the validation set. The best-performing model will then be used to make predictions across the test set.
Here is a sample Huber regression:
hb1 = linear_model.HuberRegressor(epsilon=1.1, max_iter=100, alpha=0.0001, warm_start=False, fit_intercept=True, tol=1e-05)
In particular, the value of epsilon measures the number of samples that should be classified as outliers. The smaller this value, the more robust the model is to outliers.
From this standpoint, five separate Huber regressions with varying epsilon values were computed.
hb1 = linear_model.HuberRegressor(epsilon=1.1, max_iter=100, alpha=0.0001, warm_start=False, fit_intercept=True, tol=1e-05)hb2 = linear_model.HuberRegressor(epsilon=1.8, max_iter=1000, alpha=0.0001, warm_start=False, fit_intercept=True, tol=1e-05)hb3 = linear_model.HuberRegressor(epsilon=2.5, max_iter=1000, alpha=0.0001, warm_start=False, fit_intercept=True, tol=1e-05)hb4 = linear_model.HuberRegressor(epsilon=3.2, max_iter=1000, alpha=0.0001, warm_start=False, fit_intercept=True, tol=1e-05)hb5 = linear_model.HuberRegressor(epsilon=3.9, max_iter=1000, alpha=0.0001, warm_start=False, fit_intercept=True, tol=1e-05)
Predictions were made across the five models against the validation set. Using the first model as an example:
>>> hubermodel1 = hb1.fit(X_train,y_train)>>> huberpredictions1 = hb1.predict(X_val)>>> print(huberpredictions1)[35.67051275 29.43501067 27.18925225 33.91769821 34.47019359... 31.52694684 31.0940833 35.37464065 30.99181107 36.11032014]
The calculated mean squared errors were as follows:
hb1 = 5.803
hb2 = 5.800
hb3 = 5.816
hb4 = 5.825
hb5 = 5.828
We see that the RMSE values are all slightly less than the 5.83 computed when using the OLS regression. hb2, or the model with an epsilon value of 1.8, showed the best performance — albeit marginal.
In the same manner as previously, predictions are made using the Ridge regression and the RMSE is subsequently calculated:
>>> rg = Ridge(fit_intercept=True, alpha=0.0, random_state=0, normalize=True)>>> ridgemodel = rg.fit(X_train,y_train)>>> ridgepredictions = rg.predict(X_val)[36.32534071 31.09716546 28.67493585 34.29867119 35.03070074...31.79765405 36.18771132 31.86883756 36.98120033 35.68182273]
The mean squared error is virtually identical to that calculated using the OLS regression:
>>> mean_squared_error(y_val, ridgepredictions)>>> math.sqrt(mean_squared_error(y_val, ridgepredictions))5.8305
Given that the Huber regression with epsilon = 1.8 showed the best performance against the validation set (albeit marginal), let’s see how it performs against the test set.
In this case, a portion of the Pima Indians Diabetes dataset was made physically separate from the rest of the data — in order to examine how the model would perform across unseen data.
Here are the predictions:
>>> btest = t_bmi>>> btest=btest.values>>> bpred = hb2.predict(atest)>>> bpredarray([33.14957023, 30.36001456, 32.93500157, 28.91518701, ...34.72666166,36.29947658, 39.13505914, 33.77051646])
The RMSE and mean value of the test set are calculated:
>>> math.sqrt(mean_squared_error(btest, bpred))5.744712507435319>>> np.mean(btest)32.82418300653595
With the RMSE value accounting for just over 17% of the mean value — the model does reasonably well at predicting BMI values across the test set.
As we have seen, the RMSE values across all models were more or less similar — with the Huber regressions delivering slightly lower RMSE values. However, depending on the size of the outliers, there are instances where Huber and Ridge regressions can significantly outperform OLS.
In this example, you have seen:
How to visually detect outliers in a data sample
The differences between Huber and Ridge regressions
How to modify outlier sensitivity within a Huber regression
Use of RMSE to determine model accuracy
Many thanks for your time, and any questions or feedback are greatly appreciated. You can find more of my content at michael-grogan.com.
Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice. The findings and interpretations in this article are those of the author and are not endorsed by or affiliated with any third-party mentioned in this article. The author has no relationship with any third parties mentioned in this article.
|
[
{
"code": null,
"e": 291,
"s": 172,
"text": "Traditional linear regression can prove to have some shortcomings when it comes to handling outliers in a set of data."
},
{
"code": null,
"e": 563,
"s": 291,
"text": "Specifically, if a data point lies very far away from other points in the set — this can significantly influence the least squares regression line, i.e. the line that approximates the overall direction of the set of data points will be skewed by the presence of outliers."
},
{
"code": null,
"e": 781,
"s": 563,
"text": "In an attempt to guard against this shortcoming, it is possible to use modified regression models that are robust to outliers. In this particular instance, we will take a look at the Huber and Ridge regression models."
},
{
"code": null,
"e": 1039,
"s": 781,
"text": "The dataset that is used in this instance is the Pima Indians Diabetes dataset as originally from the National Institute of Diabetes and Digestive and Kidney Diseases and made available under the CC0 1.0 Universal (CC0 1.0) Public Domain Dedication license."
},
{
"code": null,
"e": 1159,
"s": 1039,
"text": "For this particular scenario, a regression model will be built to predict body mass index (BMI) levels across patients."
},
{
"code": null,
"e": 1304,
"s": 1159,
"text": "When looking at a boxplot of BMI, we can see that there exist significant outliers as evidenced by the data points in the top half of the graph."
},
{
"code": null,
"e": 1402,
"s": 1304,
"text": "# Creating plotplt.boxplot(bmi)plt.ylabel(\"BMI\")plt.title(\"Body Mass Index\")# show plotplt.show()"
},
{
"code": null,
"e": 1457,
"s": 1402,
"text": "A correlation matrix across the data was then created:"
},
{
"code": null,
"e": 1477,
"s": 1457,
"text": "corr = a.corr()corr"
},
{
"code": null,
"e": 1509,
"s": 1477,
"text": "Here is a visual using seaborn:"
},
{
"code": null,
"e": 1532,
"s": 1509,
"text": "sns.heatmap(a.corr());"
},
{
"code": null,
"e": 1681,
"s": 1532,
"text": "Of the independent variables, Skin Thickness and Glucose were chosen as the two variables that are hypothesised to have a significant effect on BMI."
},
{
"code": null,
"e": 1765,
"s": 1681,
"text": "A regression was run across the training data which produced the following results:"
},
{
"code": null,
"e": 1797,
"s": 1765,
"text": "According to the above results:"
},
{
"code": null,
"e": 1907,
"s": 1797,
"text": "A 1 unit increase in Skin Thickness leads to a 0.1597 increase in BMI — holding all other variables constant."
},
{
"code": null,
"e": 2017,
"s": 1907,
"text": "A 1 unit increase in Glucose levels leads to a 0.0418 increase in BMI — holding all other variables constant."
},
{
"code": null,
"e": 2466,
"s": 2017,
"text": "We see that these two variables are highly significant at all levels (given p-values of 0). While the R-Squared of 17.5% is low — this does not necessarily mean that the model is bad. Given that there are a wide range of variables that can influence BMI fluctuations — this simply indicates that there are many variables that this model does not account for. However, the two independent variables being used show a highly significant relationship."
},
{
"code": null,
"e": 2718,
"s": 2466,
"text": "Predictions were generated across the validation set and a root mean squared error (RMSE) value was calculated. RMSE is used in this instance as the score is more sensitive to outliers. The higher the score, the more error in the forecast predictions."
},
{
"code": null,
"e": 2910,
"s": 2718,
"text": ">>> olspredictions = results.predict(X_val)>>> print(olspredictions)[36.32534071 31.09716546 28.67493585 34.29867119 35.03070074... 36.50971909 35.97416079 36.57591618 35.10923948 34.3672371]"
},
{
"code": null,
"e": 2953,
"s": 2910,
"text": "The root mean squared error is calculated:"
},
{
"code": null,
"e": 3108,
"s": 2953,
"text": ">>> mean_squared_error(y_val, olspredictions)>>> math.sqrt(mean_squared_error(y_val, olspredictions))5.830559762277098>>> np.mean(y_val)31.809333333333342"
},
{
"code": null,
"e": 3214,
"s": 3108,
"text": "The value of the root mean squared error is 5.83 relative to the mean of 31.81 across the validation set."
},
{
"code": null,
"e": 3411,
"s": 3214,
"text": "Now, we will generate Huber and Ridge regression models. In the same way, predictions will be made against the validation set using these models and the root mean squared error will be calculated."
},
{
"code": null,
"e": 3558,
"s": 3411,
"text": "Both the Huber and Ridge regressions are designed to produce a regression line that is less sensitive to outliers than standard linear regression."
},
{
"code": null,
"e": 3631,
"s": 3558,
"text": "However, the way in which these models work in doing so differ slightly."
},
{
"code": null,
"e": 3857,
"s": 3631,
"text": "Specifically, Huber regression relies on what is known as the M-estimate, or measures of location that are less sensitive to outliers than the mean (as described in the Oxford Dictionary of Statistics (Upton and Cook, 2014))."
},
{
"code": null,
"e": 4227,
"s": 3857,
"text": "A Ridge regression uses what is known as L2 regularization — which makes the weights of the outlier values smaller so as to have less of an effect on the regression line. Additionally, L2 regularization attempts to estimate the mean of the data to avoid overfitting, whereas L1 regularization (as used in a Lasso regression) attempts to estimate the median of the data."
},
{
"code": null,
"e": 4469,
"s": 4227,
"text": "In this example, predictions will be made using the Huber and Ridge regressions, in order to compute the RMSE of the predictions against the validation set. The best-performing model will then be used to make predictions across the test set."
},
{
"code": null,
"e": 4504,
"s": 4469,
"text": "Here is a sample Huber regression:"
},
{
"code": null,
"e": 4628,
"s": 4504,
"text": "hb1 = linear_model.HuberRegressor(epsilon=1.1, max_iter=100, alpha=0.0001, warm_start=False, fit_intercept=True, tol=1e-05)"
},
{
"code": null,
"e": 4800,
"s": 4628,
"text": "In particular, the value of epsilon measures the number of samples that should be classified as outliers. The smaller this value, the more robust the model is to outliers."
},
{
"code": null,
"e": 4897,
"s": 4800,
"text": "From this standpoint, five separate Huber regressions with varying epsilon values were computed."
},
{
"code": null,
"e": 5517,
"s": 4897,
"text": "hb1 = linear_model.HuberRegressor(epsilon=1.1, max_iter=100, alpha=0.0001, warm_start=False, fit_intercept=True, tol=1e-05)hb2 = linear_model.HuberRegressor(epsilon=1.8, max_iter=1000, alpha=0.0001, warm_start=False, fit_intercept=True, tol=1e-05)hb3 = linear_model.HuberRegressor(epsilon=2.5, max_iter=1000, alpha=0.0001, warm_start=False, fit_intercept=True, tol=1e-05)hb4 = linear_model.HuberRegressor(epsilon=3.2, max_iter=1000, alpha=0.0001, warm_start=False, fit_intercept=True, tol=1e-05)hb5 = linear_model.HuberRegressor(epsilon=3.9, max_iter=1000, alpha=0.0001, warm_start=False, fit_intercept=True, tol=1e-05)"
},
{
"code": null,
"e": 5627,
"s": 5517,
"text": "Predictions were made across the five models against the validation set. Using the first model as an example:"
},
{
"code": null,
"e": 5864,
"s": 5627,
"text": ">>> hubermodel1 = hb1.fit(X_train,y_train)>>> huberpredictions1 = hb1.predict(X_val)>>> print(huberpredictions1)[35.67051275 29.43501067 27.18925225 33.91769821 34.47019359... 31.52694684 31.0940833 35.37464065 30.99181107 36.11032014]"
},
{
"code": null,
"e": 5916,
"s": 5864,
"text": "The calculated mean squared errors were as follows:"
},
{
"code": null,
"e": 5928,
"s": 5916,
"text": "hb1 = 5.803"
},
{
"code": null,
"e": 5940,
"s": 5928,
"text": "hb2 = 5.800"
},
{
"code": null,
"e": 5952,
"s": 5940,
"text": "hb3 = 5.816"
},
{
"code": null,
"e": 5964,
"s": 5952,
"text": "hb4 = 5.825"
},
{
"code": null,
"e": 5976,
"s": 5964,
"text": "hb5 = 5.828"
},
{
"code": null,
"e": 6175,
"s": 5976,
"text": "We see that the RMSE values are all slightly less than the 5.83 computed when using the OLS regression. hb2, or the model with an epsilon value of 1.8, showed the best performance — albeit marginal."
},
{
"code": null,
"e": 6298,
"s": 6175,
"text": "In the same manner as previously, predictions are made using the Ridge regression and the RMSE is subsequently calculated:"
},
{
"code": null,
"e": 6579,
"s": 6298,
"text": ">>> rg = Ridge(fit_intercept=True, alpha=0.0, random_state=0, normalize=True)>>> ridgemodel = rg.fit(X_train,y_train)>>> ridgepredictions = rg.predict(X_val)[36.32534071 31.09716546 28.67493585 34.29867119 35.03070074...31.79765405 36.18771132 31.86883756 36.98120033 35.68182273]"
},
{
"code": null,
"e": 6670,
"s": 6579,
"text": "The mean squared error is virtually identical to that calculated using the OLS regression:"
},
{
"code": null,
"e": 6782,
"s": 6670,
"text": ">>> mean_squared_error(y_val, ridgepredictions)>>> math.sqrt(mean_squared_error(y_val, ridgepredictions))5.8305"
},
{
"code": null,
"e": 6955,
"s": 6782,
"text": "Given that the Huber regression with epsilon = 1.8 showed the best performance against the validation set (albeit marginal), let’s see how it performs against the test set."
},
{
"code": null,
"e": 7141,
"s": 6955,
"text": "In this case, a portion of the Pima Indians Diabetes dataset was made physically separate from the rest of the data — in order to examine how the model would perform across unseen data."
},
{
"code": null,
"e": 7167,
"s": 7141,
"text": "Here are the predictions:"
},
{
"code": null,
"e": 7359,
"s": 7167,
"text": ">>> btest = t_bmi>>> btest=btest.values>>> bpred = hb2.predict(atest)>>> bpredarray([33.14957023, 30.36001456, 32.93500157, 28.91518701, ...34.72666166,36.29947658, 39.13505914, 33.77051646])"
},
{
"code": null,
"e": 7415,
"s": 7359,
"text": "The RMSE and mean value of the test set are calculated:"
},
{
"code": null,
"e": 7515,
"s": 7415,
"text": ">>> math.sqrt(mean_squared_error(btest, bpred))5.744712507435319>>> np.mean(btest)32.82418300653595"
},
{
"code": null,
"e": 7661,
"s": 7515,
"text": "With the RMSE value accounting for just over 17% of the mean value — the model does reasonably well at predicting BMI values across the test set."
},
{
"code": null,
"e": 7942,
"s": 7661,
"text": "As we have seen, the RMSE values across all models were more or less similar — with the Huber regressions delivering slightly lower RMSE values. However, depending on the size of the outliers, there are instances where Huber and Ridge regressions can significantly outperform OLS."
},
{
"code": null,
"e": 7974,
"s": 7942,
"text": "In this example, you have seen:"
},
{
"code": null,
"e": 8023,
"s": 7974,
"text": "How to visually detect outliers in a data sample"
},
{
"code": null,
"e": 8075,
"s": 8023,
"text": "The differences between Huber and Ridge regressions"
},
{
"code": null,
"e": 8135,
"s": 8075,
"text": "How to modify outlier sensitivity within a Huber regression"
},
{
"code": null,
"e": 8175,
"s": 8135,
"text": "Use of RMSE to determine model accuracy"
},
{
"code": null,
"e": 8312,
"s": 8175,
"text": "Many thanks for your time, and any questions or feedback are greatly appreciated. You can find more of my content at michael-grogan.com."
}
] |
C# Abstraction
|
Data abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can be achieved with either abstract classes or
interfaces (which you will learn more about in the next chapter).
The abstract keyword is used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the
derived class (inherited from).
An abstract class can have both abstract and regular methods:
abstract class Animal
{
public abstract void animalSound();
public void sleep()
{
Console.WriteLine("Zzz");
}
}
From the example above, it is not possible to create an object of the Animal class:
Animal myObj = new Animal(); // Will generate an error (Cannot create an instance of the abstract class or interface 'Animal')
To access the abstract class, it must be inherited from another class. Let's convert the Animal class we used in the Polymorphism
chapter to an abstract class.
Remember from the Inheritance chapter that we use the
: symbol to inherit from a class,
and that we use the override keyword to override the base class method.
// Abstract class
abstract class Animal
{
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep()
{
Console.WriteLine("Zzz");
}
}
// Derived class (inherit from Animal)
class Pig : Animal
{
public override void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound(); // Call the abstract method
myPig.sleep(); // Call the regular method
}
}
Try it Yourself »
To achieve security - hide certain details and only show the important
details of an object.
Note: Abstraction can also be achieved with Interfaces, which you will learn more about in the next chapter.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 237,
"s": 0,
"text": "Data abstraction is the process of hiding certain details and showing only essential information to the user.\nAbstraction can be achieved with either abstract classes or \ninterfaces (which you will learn more about in the next chapter)."
},
{
"code": null,
"e": 292,
"s": 237,
"text": "The abstract keyword is used for classes and methods:\n"
},
{
"code": null,
"e": 425,
"s": 292,
"text": "Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class)."
},
{
"code": null,
"e": 571,
"s": 425,
"text": "Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the \nderived class (inherited from)."
},
{
"code": null,
"e": 633,
"s": 571,
"text": "An abstract class can have both abstract and regular methods:"
},
{
"code": null,
"e": 764,
"s": 633,
"text": "abstract class Animal \n{\n public abstract void animalSound();\n public void sleep() \n {\n Console.WriteLine(\"Zzz\");\n }\n}\n \n \n"
},
{
"code": null,
"e": 848,
"s": 764,
"text": "From the example above, it is not possible to create an object of the Animal class:"
},
{
"code": null,
"e": 976,
"s": 848,
"text": "Animal myObj = new Animal(); // Will generate an error (Cannot create an instance of the abstract class or interface 'Animal')\n"
},
{
"code": null,
"e": 1137,
"s": 976,
"text": "To access the abstract class, it must be inherited from another class. Let's convert the Animal class we used in the Polymorphism \nchapter to an abstract class."
},
{
"code": null,
"e": 1299,
"s": 1137,
"text": "Remember from the Inheritance chapter that we use the \n: symbol to inherit from a class, \nand that we use the override keyword to override the base class method."
},
{
"code": null,
"e": 1935,
"s": 1299,
"text": "// Abstract class\nabstract class Animal\n{\n // Abstract method (does not have a body)\n public abstract void animalSound();\n // Regular method\n public void sleep()\n {\n Console.WriteLine(\"Zzz\");\n }\n}\n\n// Derived class (inherit from Animal)\nclass Pig : Animal\n{\n public override void animalSound()\n {\n // The body of animalSound() is provided here\n Console.WriteLine(\"The pig says: wee wee\");\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Pig myPig = new Pig(); // Create a Pig object\n myPig.animalSound(); // Call the abstract method\n myPig.sleep(); // Call the regular method\n }\n} \n \n \n \n \n \n"
},
{
"code": null,
"e": 1955,
"s": 1935,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 2049,
"s": 1955,
"text": "To achieve security - hide certain details and only show the important \ndetails of an object."
},
{
"code": null,
"e": 2158,
"s": 2049,
"text": "Note: Abstraction can also be achieved with Interfaces, which you will learn more about in the next chapter."
},
{
"code": null,
"e": 2191,
"s": 2158,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2233,
"s": 2191,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2340,
"s": 2233,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 2359,
"s": 2340,
"text": "[email protected]"
}
] |
TestNG - Basic Annotations - BeforeSuite
|
@BeforeSuite annotated method will be run before the execution of all the test cases defined in the folder or inside a TestNG suite. For example, this annotation is used when you have separate URLs to test all your test cases. Environment variables can be set in a @BeforeSuite annotated method. Next, before executing all the test cases, you need to first load all the environment variables for your framework, and then start executing the test cases.
The following is a list of attributes supported by the @BeforeSuite annotation:
alwaysRun
For before methods (beforeSuite, beforeTest, beforeTestClass and beforeTestMethod, but not beforeGroups): If set to true, this configuration method will be run regardless of what groups it belongs to.
For after methods (afterSuite, afterClass, ...): If set to true, this configuration method will be run even if one or more methods invoked previously failed or was skipped.
dependsOnGroups
The list of groups this method depends on.
dependsOnMethods
The list of methods this method depends on.
enabled
Whether methods on this class/method are enabled.
groups
The list of groups this class/method belongs to.
inheritGroups
If true, this method will belong to groups specified in the @Test annotation at the class level.
onlyForGroups
Only for @BeforeMethod and @AfterMethod. If specified, then this setup/teardown method will only be invoked if the corresponding test method belongs to one of the listed groups.
Create a java class to be tested, say, MessageUtil.java in /work/testng/src.
/*
* This class prints the given message on console.
*/
public class MessageUtil {
private String message;
//Constructor
//@param message to be printed
public MessageUtil(String message) {
this.message = message;
}
// prints the message
public String printMessage() {
System.out.println(message);
return message;
}
}
Create a java test class, say, TestAnnotationBeforeSuite.java in /work/testng/src.
Create a java test class, say, TestAnnotationBeforeSuite.java in /work/testng/src.
Add a test method testMethod() to your test class.
Add a test method testMethod() to your test class.
Add an Annotation @Test to method testMethod().
Add an Annotation @Test to method testMethod().
Add a method beforeSuite to the test class with annotation @BeforeSuite
Add a method beforeSuite to the test class with annotation @BeforeSuite
Implement the test condition and check the behaviour of @BeforeSuite annotation.
Implement the test condition and check the behaviour of @BeforeSuite annotation.
Following are the TestAnnotationBeforeSuite.java contents:
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeSuite;
public class TestAnnotationBeforeSuite {
MessageUtil messageUtil = new MessageUtil("Test method");
@BeforeSuite
public void beforeSuite(){
System.out.println("Before Suite method");
}
@Test
public void testMethod(){
Assert.assertEquals("Test method", messageUtil.printMessage());
}
}
Next, let's create testng.xml file in /work/testng/src, to execute test case(s). This file captures your entire testing in XML. This file makes it easy to describe all your test suites and their parameters in one file, which you can check in your code repository or e-mail to coworkers. It also makes it easy to extract subsets of your tests or split several runtime configurations (e.g., testngdatabase.xml would run only tests that exercise your database).
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test thread-count="5" name="Test">
<classes>
<class name="TestAnnotationBeforeSuite"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
Compile the test case using javac.
/work/testng/src$ javac TestAnnotationBeforeSuite.java MessageUtil.java
Now, run the testng.xml, which will run the test case defined in <test> tag. As you can see the @BeforeSuite is called before all other test cases.
/work/testng/src$ java org.testng.TestNG testng.xml
Verify the output.
Before Suite method
Test method
===============================================
Suite
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================
38 Lectures
4.5 hours
Lets Kode It
15 Lectures
1.5 hours
Quaatso Learning
28 Lectures
3 hours
Dezlearn Education
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2513,
"s": 2060,
"text": "@BeforeSuite annotated method will be run before the execution of all the test cases defined in the folder or inside a TestNG suite. For example, this annotation is used when you have separate URLs to test all your test cases. Environment variables can be set in a @BeforeSuite annotated method. Next, before executing all the test cases, you need to first load all the environment variables for your framework, and then start executing the test cases."
},
{
"code": null,
"e": 2593,
"s": 2513,
"text": "The following is a list of attributes supported by the @BeforeSuite annotation:"
},
{
"code": null,
"e": 2603,
"s": 2593,
"text": "alwaysRun"
},
{
"code": null,
"e": 2804,
"s": 2603,
"text": "For before methods (beforeSuite, beforeTest, beforeTestClass and beforeTestMethod, but not beforeGroups): If set to true, this configuration method will be run regardless of what groups it belongs to."
},
{
"code": null,
"e": 2977,
"s": 2804,
"text": "For after methods (afterSuite, afterClass, ...): If set to true, this configuration method will be run even if one or more methods invoked previously failed or was skipped."
},
{
"code": null,
"e": 2993,
"s": 2977,
"text": "dependsOnGroups"
},
{
"code": null,
"e": 3036,
"s": 2993,
"text": "The list of groups this method depends on."
},
{
"code": null,
"e": 3053,
"s": 3036,
"text": "dependsOnMethods"
},
{
"code": null,
"e": 3097,
"s": 3053,
"text": "The list of methods this method depends on."
},
{
"code": null,
"e": 3105,
"s": 3097,
"text": "enabled"
},
{
"code": null,
"e": 3155,
"s": 3105,
"text": "Whether methods on this class/method are enabled."
},
{
"code": null,
"e": 3162,
"s": 3155,
"text": "groups"
},
{
"code": null,
"e": 3211,
"s": 3162,
"text": "The list of groups this class/method belongs to."
},
{
"code": null,
"e": 3225,
"s": 3211,
"text": "inheritGroups"
},
{
"code": null,
"e": 3322,
"s": 3225,
"text": "If true, this method will belong to groups specified in the @Test annotation at the class level."
},
{
"code": null,
"e": 3336,
"s": 3322,
"text": "onlyForGroups"
},
{
"code": null,
"e": 3514,
"s": 3336,
"text": "Only for @BeforeMethod and @AfterMethod. If specified, then this setup/teardown method will only be invoked if the corresponding test method belongs to one of the listed groups."
},
{
"code": null,
"e": 3591,
"s": 3514,
"text": "Create a java class to be tested, say, MessageUtil.java in /work/testng/src."
},
{
"code": null,
"e": 3954,
"s": 3591,
"text": "/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n public MessageUtil(String message) {\n this.message = message;\n }\n\n // prints the message\n public String printMessage() {\n System.out.println(message);\n return message;\n }\n}"
},
{
"code": null,
"e": 4037,
"s": 3954,
"text": "Create a java test class, say, TestAnnotationBeforeSuite.java in /work/testng/src."
},
{
"code": null,
"e": 4120,
"s": 4037,
"text": "Create a java test class, say, TestAnnotationBeforeSuite.java in /work/testng/src."
},
{
"code": null,
"e": 4171,
"s": 4120,
"text": "Add a test method testMethod() to your test class."
},
{
"code": null,
"e": 4222,
"s": 4171,
"text": "Add a test method testMethod() to your test class."
},
{
"code": null,
"e": 4270,
"s": 4222,
"text": "Add an Annotation @Test to method testMethod()."
},
{
"code": null,
"e": 4318,
"s": 4270,
"text": "Add an Annotation @Test to method testMethod()."
},
{
"code": null,
"e": 4390,
"s": 4318,
"text": "Add a method beforeSuite to the test class with annotation @BeforeSuite"
},
{
"code": null,
"e": 4462,
"s": 4390,
"text": "Add a method beforeSuite to the test class with annotation @BeforeSuite"
},
{
"code": null,
"e": 4543,
"s": 4462,
"text": "Implement the test condition and check the behaviour of @BeforeSuite annotation."
},
{
"code": null,
"e": 4624,
"s": 4543,
"text": "Implement the test condition and check the behaviour of @BeforeSuite annotation."
},
{
"code": null,
"e": 4683,
"s": 4624,
"text": "Following are the TestAnnotationBeforeSuite.java contents:"
},
{
"code": null,
"e": 5123,
"s": 4683,
"text": " import org.testng.Assert;\n import org.testng.annotations.Test;\n import org.testng.annotations.BeforeSuite;\n\n public class TestAnnotationBeforeSuite {\n MessageUtil messageUtil = new MessageUtil(\"Test method\");\n @BeforeSuite\n public void beforeSuite(){\n System.out.println(\"Before Suite method\");\n }\n @Test\n public void testMethod(){\n Assert.assertEquals(\"Test method\", messageUtil.printMessage());\n }\n }"
},
{
"code": null,
"e": 5582,
"s": 5123,
"text": "Next, let's create testng.xml file in /work/testng/src, to execute test case(s). This file captures your entire testing in XML. This file makes it easy to describe all your test suites and their parameters in one file, which you can check in your code repository or e-mail to coworkers. It also makes it easy to extract subsets of your tests or split several runtime configurations (e.g., testngdatabase.xml would run only tests that exercise your database)."
},
{
"code": null,
"e": 5883,
"s": 5582,
"text": " <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <!DOCTYPE suite SYSTEM \"https://testng.org/testng-1.0.dtd\">\n <suite name=\"Suite\">\n <test thread-count=\"5\" name=\"Test\">\n <classes>\n <class name=\"TestAnnotationBeforeSuite\"/>\n </classes>\n </test> <!-- Test -->\n </suite> <!-- Suite -->"
},
{
"code": null,
"e": 5918,
"s": 5883,
"text": "Compile the test case using javac."
},
{
"code": null,
"e": 5991,
"s": 5918,
"text": "/work/testng/src$ javac TestAnnotationBeforeSuite.java MessageUtil.java\n"
},
{
"code": null,
"e": 6139,
"s": 5991,
"text": "Now, run the testng.xml, which will run the test case defined in <test> tag. As you can see the @BeforeSuite is called before all other test cases."
},
{
"code": null,
"e": 6192,
"s": 6139,
"text": "/work/testng/src$ java org.testng.TestNG testng.xml\n"
},
{
"code": null,
"e": 6211,
"s": 6192,
"text": "Verify the output."
},
{
"code": null,
"e": 6412,
"s": 6211,
"text": " Before Suite method\n Test method\n\n ===============================================\n Suite\n Total tests run: 1, Passes: 1, Failures: 0, Skips: 0\n ===============================================\n"
},
{
"code": null,
"e": 6447,
"s": 6412,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6461,
"s": 6447,
"text": " Lets Kode It"
},
{
"code": null,
"e": 6496,
"s": 6461,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6514,
"s": 6496,
"text": " Quaatso Learning"
},
{
"code": null,
"e": 6547,
"s": 6514,
"text": "\n 28 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6567,
"s": 6547,
"text": " Dezlearn Education"
},
{
"code": null,
"e": 6574,
"s": 6567,
"text": " Print"
},
{
"code": null,
"e": 6585,
"s": 6574,
"text": " Add Notes"
}
] |
Drawing an image from a data URL to a HTML5 canvas
|
If you have a data url, you can create an image to a canvas. This can be done as shown in the following code snippet −
var myImg = new Image;
myImg.src = strDataURI;
The drawImage() method draws an image, canvas, or video onto the canvas. The drawImage() method can also draw parts of an image, and/or increase/reduce the image size.
The code given below is also appropriate with the sequence - create the image, set the onload to use the new image, and then set the src −
// load image from data url
Var Obj = new Image();
Obj.onload = function() {
context.drawImage(myImg, 0, 0);
};
Obj.src = dataURL;
|
[
{
"code": null,
"e": 1181,
"s": 1062,
"text": "If you have a data url, you can create an image to a canvas. This can be done as shown in the following code snippet −"
},
{
"code": null,
"e": 1228,
"s": 1181,
"text": "var myImg = new Image;\nmyImg.src = strDataURI;"
},
{
"code": null,
"e": 1396,
"s": 1228,
"text": "The drawImage() method draws an image, canvas, or video onto the canvas. The drawImage() method can also draw parts of an image, and/or increase/reduce the image size."
},
{
"code": null,
"e": 1535,
"s": 1396,
"text": "The code given below is also appropriate with the sequence - create the image, set the onload to use the new image, and then set the src −"
},
{
"code": null,
"e": 1669,
"s": 1535,
"text": "// load image from data url\nVar Obj = new Image();\nObj.onload = function() {\n context.drawImage(myImg, 0, 0);\n};\nObj.src = dataURL;"
}
] |
How to Align Text in HTML? - GeeksforGeeks
|
24 Jun, 2021
HTML stands for HyperText Markup Language. It is used to design web pages using a markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. A markup language is used to define the text document within tag which defines the structure of web pages.
HTML is used by the browser to manipulate text, images, and other content to display it in the required format.
We can change the alignment of the text using the text-align property. We can align the text in the center, Left, Right.
The text alignment can be done with CSS(Cascading Style Sheets) and HTML Attribute tag.
Note: The left alignment of the text is default. If we do not write text align attribute then our text will automatically be aligned to the left.
CSS stands for Cascading Style Sheets, HTML allows the use of these CSS to perform changes in the style of the content on a Webpage. For example, here we will use CSS to align text in an HTML Code.
Method 1: Align text to the center
HTML
<html><head> <title>Text alignment</title> <style> h1{text-align: center;} </style></head><body> <h1>GeeksforGeeks</h1></body></html>
Method 2: Align text to right
HTML
<html><head> <title>Text alignment</title> <style> h1{text-align: right;} </style></head><body> <h1>GeeksforGeeks</h1></body></html>
Method 3: Align text to left
HTML
<html><head> <title>Text alignment</title> <style> h1{text-align: left;} </style></head><body> <h1>GeeksforGeeks</h1></body></html>
Note: The text aligned to left is default.
Method 1: Align text to center
HTML
<html><head> <title>Text alignment</title></head><body> <h1 align="center">GeeksforGeeks</h1></body></html>
Method 2: Align text to right
HTML
<html><head> <title>Text alignment</title></head><body> <h1 align="right">GeeksforGeeks</h1></body></html>
Method 3: Align Text to Left
HTML
<html><head> <title>Text alignment</title></head><body> <h1 align="left">GeeksforGeeks</h1></body></html>
Note: The text aligned to left is default.
Picked
class 7
How To
School Learning
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML Background Images
Understanding Layers in Photoshop
How to Use the Patch Tool in Photoshop?
Learn Photoshop Note and Count Tool
How to Use the Blur and Sharpen Tool in Photoshop?
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Install OpenCV for Python on Windows?
How to filter object array based on attributes?
|
[
{
"code": null,
"e": 24358,
"s": 24330,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 24672,
"s": 24358,
"text": "HTML stands for HyperText Markup Language. It is used to design web pages using a markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. A markup language is used to define the text document within tag which defines the structure of web pages."
},
{
"code": null,
"e": 24784,
"s": 24672,
"text": "HTML is used by the browser to manipulate text, images, and other content to display it in the required format."
},
{
"code": null,
"e": 24905,
"s": 24784,
"text": "We can change the alignment of the text using the text-align property. We can align the text in the center, Left, Right."
},
{
"code": null,
"e": 24993,
"s": 24905,
"text": "The text alignment can be done with CSS(Cascading Style Sheets) and HTML Attribute tag."
},
{
"code": null,
"e": 25139,
"s": 24993,
"text": "Note: The left alignment of the text is default. If we do not write text align attribute then our text will automatically be aligned to the left."
},
{
"code": null,
"e": 25337,
"s": 25139,
"text": "CSS stands for Cascading Style Sheets, HTML allows the use of these CSS to perform changes in the style of the content on a Webpage. For example, here we will use CSS to align text in an HTML Code."
},
{
"code": null,
"e": 25372,
"s": 25337,
"text": "Method 1: Align text to the center"
},
{
"code": null,
"e": 25377,
"s": 25372,
"text": "HTML"
},
{
"code": "<html><head> <title>Text alignment</title> <style> h1{text-align: center;} </style></head><body> <h1>GeeksforGeeks</h1></body></html>",
"e": 25530,
"s": 25377,
"text": null
},
{
"code": null,
"e": 25560,
"s": 25530,
"text": "Method 2: Align text to right"
},
{
"code": null,
"e": 25565,
"s": 25560,
"text": "HTML"
},
{
"code": "<html><head> <title>Text alignment</title> <style> h1{text-align: right;} </style></head><body> <h1>GeeksforGeeks</h1></body></html>",
"e": 25717,
"s": 25565,
"text": null
},
{
"code": null,
"e": 25746,
"s": 25717,
"text": "Method 3: Align text to left"
},
{
"code": null,
"e": 25751,
"s": 25746,
"text": "HTML"
},
{
"code": "<html><head> <title>Text alignment</title> <style> h1{text-align: left;} </style></head><body> <h1>GeeksforGeeks</h1></body></html>",
"e": 25902,
"s": 25751,
"text": null
},
{
"code": null,
"e": 25945,
"s": 25902,
"text": "Note: The text aligned to left is default."
},
{
"code": null,
"e": 25976,
"s": 25945,
"text": "Method 1: Align text to center"
},
{
"code": null,
"e": 25981,
"s": 25976,
"text": "HTML"
},
{
"code": "<html><head> <title>Text alignment</title></head><body> <h1 align=\"center\">GeeksforGeeks</h1></body></html>",
"e": 26095,
"s": 25981,
"text": null
},
{
"code": null,
"e": 26125,
"s": 26095,
"text": "Method 2: Align text to right"
},
{
"code": null,
"e": 26130,
"s": 26125,
"text": "HTML"
},
{
"code": "<html><head> <title>Text alignment</title></head><body> <h1 align=\"right\">GeeksforGeeks</h1></body></html>",
"e": 26243,
"s": 26130,
"text": null
},
{
"code": null,
"e": 26272,
"s": 26243,
"text": "Method 3: Align Text to Left"
},
{
"code": null,
"e": 26277,
"s": 26272,
"text": "HTML"
},
{
"code": "<html><head> <title>Text alignment</title></head><body> <h1 align=\"left\">GeeksforGeeks</h1></body></html>",
"e": 26389,
"s": 26277,
"text": null
},
{
"code": null,
"e": 26432,
"s": 26389,
"text": "Note: The text aligned to left is default."
},
{
"code": null,
"e": 26439,
"s": 26432,
"text": "Picked"
},
{
"code": null,
"e": 26447,
"s": 26439,
"text": "class 7"
},
{
"code": null,
"e": 26454,
"s": 26447,
"text": "How To"
},
{
"code": null,
"e": 26470,
"s": 26454,
"text": "School Learning"
},
{
"code": null,
"e": 26489,
"s": 26470,
"text": "School Programming"
},
{
"code": null,
"e": 26587,
"s": 26489,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26610,
"s": 26587,
"text": "HTML Background Images"
},
{
"code": null,
"e": 26644,
"s": 26610,
"text": "Understanding Layers in Photoshop"
},
{
"code": null,
"e": 26684,
"s": 26644,
"text": "How to Use the Patch Tool in Photoshop?"
},
{
"code": null,
"e": 26720,
"s": 26684,
"text": "Learn Photoshop Note and Count Tool"
},
{
"code": null,
"e": 26771,
"s": 26720,
"text": "How to Use the Blur and Sharpen Tool in Photoshop?"
},
{
"code": null,
"e": 26803,
"s": 26771,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26856,
"s": 26803,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 26900,
"s": 26856,
"text": "How to install Jupyter Notebook on Windows?"
},
{
"code": null,
"e": 26945,
"s": 26900,
"text": "How to Install OpenCV for Python on Windows?"
}
] |
Why do we get ClassNotFoundException when the class exists in Java?
|
Whenever we try to load a class, if the class loader is not able to find the class at the specified path a ClassNotFoundException is generated.
This may occur while executing java program, loading a class explicitly using forName() method of the class named Class or the loadClass() method of the ClassLoader class. These two classes accept string values representing the class names and loads the specified classes.
While passing class names to these methods you need to make sure that −
The class names you pass to these methods should be accurate.
The class names you pass to these methods should be accurate.
The specified class (along with the package) should be either in the current directory or, its path should be listed in the environment variable classpath.
The specified class (along with the package) should be either in the current directory or, its path should be listed in the environment variable classpath.
Assume we have created a class named Sample in the directory D:// and compiled as shown below −
package myPackage.example;
public class Sample {
static {
System.out.println("The class named Sample loaded successfully.........");
}
}
D:\>javac -d . Sample.java
This will create a package in the current directory myPackage.example and generates the .class file of the Sample class in it. Therefore, while loading this class, you need to have your it in the same directory and pass the absolute class name to Class.forName() or, loadClass()
Live Demo
public class ClassNotFoundExample {
public static void main(String args[]) {
try {
Class.forName("myPackage.exampl.Sample");
}catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
}
On executing the above program, since the name of the package is wrongly spelt you will get the following exception.
D:\>java ClassNotFoundExample
java.lang.ClassNotFoundException: myPackage.exampl.Sample
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Unknown Source)
at ClassNotFoundExample.main(ClassNotFoundExample.java:4)
If you are trying to access a particular class from another directory you need to set the class path for −
The folder (outer most package) containing the .class file.or,
The folder (outer most package) containing the .class file.
or,
The jar file containing the class.
The jar file containing the class.
Suppose, we have rectified the spelling issue and trying to load the class from a Java file which is in the directory E://
Live Demo
public class ClassNotFoundExample {
public static void main(String args[]) {
try {
Class.forName("myPackage.example.Sample");
}catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
}
Still you get the same exception since the package containing the .class file of the specified class (or jar file containing it) is neither in the current directory nor in the list of the paths in the environment variable classpath.
E:\>java ClassNotFoundExample
java.lang.ClassNotFoundException: myPackage.example.Sample
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Unknown Source)
at ClassNotFoundExample.main(ClassNotFoundExample.java:4)
In the current scenario set class path to the directory containing the package holding the required class i.e. “D://” and execute the above java program, to make it work.
E:\>javac ClassNotFoundExample.java
E:\>java ClassNotFoundExample
The class named Sample loaded successfully.........
|
[
{
"code": null,
"e": 1206,
"s": 1062,
"text": "Whenever we try to load a class, if the class loader is not able to find the class at the specified path a ClassNotFoundException is generated."
},
{
"code": null,
"e": 1479,
"s": 1206,
"text": "This may occur while executing java program, loading a class explicitly using forName() method of the class named Class or the loadClass() method of the ClassLoader class. These two classes accept string values representing the class names and loads the specified classes."
},
{
"code": null,
"e": 1551,
"s": 1479,
"text": "While passing class names to these methods you need to make sure that −"
},
{
"code": null,
"e": 1613,
"s": 1551,
"text": "The class names you pass to these methods should be accurate."
},
{
"code": null,
"e": 1675,
"s": 1613,
"text": "The class names you pass to these methods should be accurate."
},
{
"code": null,
"e": 1831,
"s": 1675,
"text": "The specified class (along with the package) should be either in the current directory or, its path should be listed in the environment variable classpath."
},
{
"code": null,
"e": 1987,
"s": 1831,
"text": "The specified class (along with the package) should be either in the current directory or, its path should be listed in the environment variable classpath."
},
{
"code": null,
"e": 2083,
"s": 1987,
"text": "Assume we have created a class named Sample in the directory D:// and compiled as shown below −"
},
{
"code": null,
"e": 2232,
"s": 2083,
"text": "package myPackage.example;\npublic class Sample {\n static {\n System.out.println(\"The class named Sample loaded successfully.........\");\n }\n}"
},
{
"code": null,
"e": 2259,
"s": 2232,
"text": "D:\\>javac -d . Sample.java"
},
{
"code": null,
"e": 2538,
"s": 2259,
"text": "This will create a package in the current directory myPackage.example and generates the .class file of the Sample class in it. Therefore, while loading this class, you need to have your it in the same directory and pass the absolute class name to Class.forName() or, loadClass()"
},
{
"code": null,
"e": 2549,
"s": 2538,
"text": " Live Demo"
},
{
"code": null,
"e": 2781,
"s": 2549,
"text": "public class ClassNotFoundExample {\n public static void main(String args[]) {\n try {\n Class.forName(\"myPackage.exampl.Sample\");\n }catch (ClassNotFoundException ex) {\n ex.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 2898,
"s": 2781,
"text": "On executing the above program, since the name of the package is wrongly spelt you will get the following exception."
},
{
"code": null,
"e": 3394,
"s": 2898,
"text": "D:\\>java ClassNotFoundExample\njava.lang.ClassNotFoundException: myPackage.exampl.Sample\n at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)\n at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)\n at java.base/java.lang.ClassLoader.loadClass(Unknown Source)\n at java.base/java.lang.Class.forName0(Native Method)\n at java.base/java.lang.Class.forName(Unknown Source)\n at ClassNotFoundExample.main(ClassNotFoundExample.java:4)"
},
{
"code": null,
"e": 3501,
"s": 3394,
"text": "If you are trying to access a particular class from another directory you need to set the class path for −"
},
{
"code": null,
"e": 3564,
"s": 3501,
"text": "The folder (outer most package) containing the .class file.or,"
},
{
"code": null,
"e": 3624,
"s": 3564,
"text": "The folder (outer most package) containing the .class file."
},
{
"code": null,
"e": 3628,
"s": 3624,
"text": "or,"
},
{
"code": null,
"e": 3663,
"s": 3628,
"text": "The jar file containing the class."
},
{
"code": null,
"e": 3698,
"s": 3663,
"text": "The jar file containing the class."
},
{
"code": null,
"e": 3821,
"s": 3698,
"text": "Suppose, we have rectified the spelling issue and trying to load the class from a Java file which is in the directory E://"
},
{
"code": null,
"e": 3832,
"s": 3821,
"text": " Live Demo"
},
{
"code": null,
"e": 4065,
"s": 3832,
"text": "public class ClassNotFoundExample {\n public static void main(String args[]) {\n try {\n Class.forName(\"myPackage.example.Sample\");\n }catch (ClassNotFoundException ex) {\n ex.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 4298,
"s": 4065,
"text": "Still you get the same exception since the package containing the .class file of the specified class (or jar file containing it) is neither in the current directory nor in the list of the paths in the environment variable classpath."
},
{
"code": null,
"e": 4795,
"s": 4298,
"text": "E:\\>java ClassNotFoundExample\njava.lang.ClassNotFoundException: myPackage.example.Sample\n at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)\n at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)\n at java.base/java.lang.ClassLoader.loadClass(Unknown Source)\n at java.base/java.lang.Class.forName0(Native Method)\n at java.base/java.lang.Class.forName(Unknown Source)\n at ClassNotFoundExample.main(ClassNotFoundExample.java:4)"
},
{
"code": null,
"e": 4966,
"s": 4795,
"text": "In the current scenario set class path to the directory containing the package holding the required class i.e. “D://” and execute the above java program, to make it work."
},
{
"code": null,
"e": 5084,
"s": 4966,
"text": "E:\\>javac ClassNotFoundExample.java\nE:\\>java ClassNotFoundExample\nThe class named Sample loaded successfully........."
}
] |
How to get the FPS value in OpenCV using C++?
|
To get the FPS value, we used the 'get()' command of and 'CAP_PROP_FPS' as the argument of the 'get()'. This argument returns the FPS in integer form.
At the starting of the program, we have taken an integer variable named 'FPS'. Then we used FPS = cap.get(CAP_PROP_FPS); to store the FPS value in the variable.
The following program gets the FPS of a video and shows it in the console window.
#include<opencv2/opencv.hpp>//OpenCV header to use VideoCapture class//
#include<iostream>
using namespace std;
using namespace cv;
int main() {
int FPS;//Declaring an integer variable to store the number of total frames//
VideoCapture cap("video1.mp4");//Declaring an object to capture stream of frames from default camera//
FPS = cap.get(CAP_PROP_FPS);//Getting the total number of frames//
cout << "Total Number of frames are:" << FPS << endl;//Showing the number in console window//
system("pause");//Pausing the system to see the result
cap.release();//Releasing the buffer memory//
return 0;
}
After launching this program, we will get the FPS value in the console window.
|
[
{
"code": null,
"e": 1213,
"s": 1062,
"text": "To get the FPS value, we used the 'get()' command of and 'CAP_PROP_FPS' as the argument of the 'get()'. This argument returns the FPS in integer form."
},
{
"code": null,
"e": 1374,
"s": 1213,
"text": "At the starting of the program, we have taken an integer variable named 'FPS'. Then we used FPS = cap.get(CAP_PROP_FPS); to store the FPS value in the variable."
},
{
"code": null,
"e": 1456,
"s": 1374,
"text": "The following program gets the FPS of a video and shows it in the console window."
},
{
"code": null,
"e": 2077,
"s": 1456,
"text": "#include<opencv2/opencv.hpp>//OpenCV header to use VideoCapture class//\n#include<iostream>\nusing namespace std;\nusing namespace cv;\nint main() {\n int FPS;//Declaring an integer variable to store the number of total frames//\n VideoCapture cap(\"video1.mp4\");//Declaring an object to capture stream of frames from default camera//\n FPS = cap.get(CAP_PROP_FPS);//Getting the total number of frames//\n cout << \"Total Number of frames are:\" << FPS << endl;//Showing the number in console window//\n system(\"pause\");//Pausing the system to see the result\n cap.release();//Releasing the buffer memory//\n return 0;\n}"
},
{
"code": null,
"e": 2156,
"s": 2077,
"text": "After launching this program, we will get the FPS value in the console window."
}
] |
How To Write a Number Systems Calculator in Python | by Martin Andersson Aaberge | Towards Data Science
|
In this article, we will build a calculator we can use to convert any number from any base to any other base. In number systems, “Base” tells us how many numbers you have available. Binary has 2, octal has 8, decimal has 10 etc.
The program we are about to write can handle any number and base we throw at it. When we figure out the math behind it, it is very easy to set up.
This calculator is based on math (Aren’t they all?). We might need to refresh our memory on the theory of converting between bases (or learn something new.)
If you had science-driven math in school or studied computers at any level, chances are you have converted from one number system to another. You might remember the binary table or talks about “the decimal system”, “the octal system”, and “the hexadecimal system”.
The decimal system (Base-10) is the one we use daily when we count. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. When we run out of numbers, we add another position to the left → 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21... etc. When we run out of numbers again, we add a new position → 100, 101, 102...118, 119, 120.
Yes, yes... I remember elementary school....
We don’t think about it, because we learn this when we are 2–3 years old. Tell a kid to count using an octal system (Base-8) and they will most likely look at you for a few seconds before returning to their homework on their iPad. The theory is easy and identical to the decimal system, we are just not used to it.
Counting in the octal system would look like this:
0,1,2,3,4,5,6,7 → 10,11,12,13,14,15,16,17 → 20,21...
The first conversion we should look at is going from any base (Base-N) to the decimal system(Base-10). It is very easy to convert from The decimal system to any other base. Therefore, it is valuable to know how to get to the decimal system.
If we keep using decimal and octal as examples, we can convert a number in the octal system to its equivalent in the decimal system. Let’s pick a random number.
256(Base-8) → ???(Base-10)
(I promise, 256 was actually random)
We have three positions 2 (hundreds), 5(tens) and 6(ones). These positions can hold between 0–7 (8 numbers)as you remember from the intro.
We need to convert each of the numbers in all positions to the decimal system. The decimal system can hold 0–9 (10 numbers)
The way we do this is that we take each number and multiply it with the base powered by the position index (num * (base^position)). If we start from the lowest number to the right, we multiply 6 with 80, 5 with 81 and 2 with 82.
Here is an illustration that will make this a lot easier to understand:
When we have the number in the decimal system (Base-10) it is really easy to go to any system. Let’s go back from 174 (Base-10) to 256 (Base-8)
We find the number in another base is by dividing it with the base and keep the remainder. The remainders will construct the number in the other base for us. When we have the remainders, we read the number from the least significant number to the most significant number, meaning from bottom to top. There you have your new number represented in your new base!
174/2 gives us 21.75. Notice how 21 is red and .75 is green. We send 21 to the next line and deal with 0.75. If we multiply 0.75 with the base, we are left with the remainder (which is the number we are after). This number is sent to the far right in blue.
When we reach 0, we are officially done and can pack our bags with a beautiful number in our new base.
Not only does this mean we can go from Base-10 to Base-8 and vice versa. We can go from Base-X to Base-Y. Any Base we want.
It feels something like this:
If you are still not sure how this works, I suggest checking out “The Organic Chemistry Tutor”. His videos are the best I know on the subject:
www.youtube.com
It’s time to dive into the code!
Note: I do most of my programming manually. This means that I don’t use too many libraries because I want to learn as much as possible. In this code I do use standard python functions like bin() because I want to show you it’s possible, but instead of using hex(), I think it was more fun to manually code the same functions. In a production environment, you probably want to keep it short and use libraries that solve your problems instead of coding everything from scratch
This program is just one main.py file with all the code in one document. If you wish you can extend this however you like. A Number Class? Sure, why not. GUI? Also something we should look into.
I recommend working with a base converter calculator online while coding to double-check that your code outputs the right values.
Here is the gist:
The logic behind the code is that we pass three arguments to the function convert_number_system():
input_number is the number we want to convert.
input_base is the base we wish to convert from.
output_base is the base we wish to convert to.
I haven’t used multiline string to print menus before, but it would make perfect sense to create a menu like this.
The function returns the whole menu string so we can use it anywhere we want. We don’t have to worry about newline either.
return ( '''----------------------------------------------------------Welcome to the Number Base converter!The system will ask you for:- The Number to convert- What base you want to convert FROM- What base you want to convert TO** REMEMBER: All numbers must be integers!(unless HEX) **---------------------------------------------------------- ''')
Instead of checking the user input in the converter function, I wanted to create validators as functions. By doing that we create code that is re-usable.
This function just checks if the number is a valid binary number.
We don’t want to check a long string with several occurrences of the same number. If we convert it to a set we remove duplicates. Sets can not hold multiple instances of an item. We use list comprehension to convert the input to an int and check it against [0,1]
[int(item) for item in set(list(check_number))]
I chose to pass strings from the user interaction and create integers of the input when needed. int(item) makes sure all the numbers are integers (we could check a string against a string as well (‘0’ , ‘1’) if we wanted to).
This is how it would look behind the scene:
‘10010011’ → [‘1’,’0',’0',’1',’0',’0',’1',’1'] → [0,1]
if 0 is in [0,1] it checks out fine, if 1 is in [0,1], that also checks out fine. If you had a number like 23, both digits would fail and the function would return False
Nothing fancy here... The code checks if the input contains the defined legal characters. We work with numbers 0–9 and because we support HEX, we include a-f as valid input as well.
This function makes use of the other validators and validates all the input so we know if there is a point in proceeding with the conversion.
First it checks if we have entered a number or a hex value.
Then we check the bases. If input_base is 2, we are converting a binary number. Therefore, the input_number must be digits only and if it is, it has to be 0s or 1s.
If the input is both numbers and letters it is a hexadecimal number. If the input_base is NOT 16, then we can’t convert it. HEX is Base-16 and any other base would calculate incorrectly. We could consider making a pre-filled input base during the interaction when someone types in a hexadecimal number.
Last we check if the user tries to convert to- or from a Base-1. That is not possible so instead of crashing the program, we want to return an error.
Now, it is time for the main part of the code. This is where we will make use of our math skills. This function is carrying out the match we looked at earlier, and it has a few safety steps to make sure we output correctly
remainder_list holds the numbers we want to return. If you remember the math you should instantly recognize the keyword remainder.
sum_base_10. We want to use the Base-10 as an intermediate step. We set the initial value to 0 and then we add whatever values we calculate to this variable.
output binary:
if output_base == 2: return (bin(input_number)[2:])
If the user wants a binary output, we can use the built-in function bin(). We don’t have to because the math is the same no matter what we pass, but it is fun to try.
bin() returns 0b and the binary. The 0b tells us it is a binary number. We want to return the actual number. That’s what the [2:] is for. If you run this in your terminal you can see the difference:
>>> check_number = 23>>> print(bin(check_number))0b10111>>> print(bin(check_number)[2:])10111
It will print from index 2 and onward.
Note that I have left the hex() version in the code, but commented out. You can use it if you want to.
The Base is NOT 10:If the base is not 10, we go through our intermediate step. First, we reverse the list (you don’t have to do this, but then you need to flip the index in the loop later. I find it easier to flip the list.) Reversing lists in Python can be done with this fantastic built-in code [::-1]
reversed_input_number = input_number[::-1]
hex_helper_dict helps us handling numbers above 9 if the user sent a hex input. If you remember our formula, we are multiplying the numbers in each position with the base index powered by position.
Here is 256 again from octal to decimal:
2*(82) + 5*(81) + 6*(80) = 174
If the number is hexadecimal, like 23e, it actually reads 2 , 3, 14
2*(162) + 3*(161) + 14*(160) = 574
This loop helps us with all of that:
for index, number in enumerate(reversed_input_number): for key,value in hex_helper_dict.items(): if str(number).lower() == key: number = value sum_base_10 += (int(number)*(int(input_base)**index))
If you look at the code above, you can see that we use both enumerate and .items() to make sure we can access everything we need to carry out our operation.
By using enumerate, we can access both the value and the index of the variable. When we loop through the variable we check if the number (ex. e) is equal to any of the keys in the dictionary. In the case of 23e, it is and we want to set the number to 14 instead so we can use it for the actual calculation.
sum_base_10 += (int(number)*(int(input_base)**index))
Now that we are sure no numbers are actually letters, we can iterate through the numbers (let’s stay with 256) and do the operations. For each number we loop through, we do the multiplication we talked about earlier.
(int(number)*(int(input_base)**index))6*(8**0)
The values we end up with are added to sum_base_10.
The Base IS 10:Great, carry on. We just assign the input number to sum_base_10:
elif input_base == 10: sum_base_10 = int(input_number)
Do the mathNow that we have the Base-10 value, we can do the division to find the remainders and find our new number.
while sum_base_10 > 0: divided = sum_base_10// int(output_base) remainder_list.append(str(sum_base_10 % int(output_base)) sum_base_10 = divided
We need to divide until we hit 0. The while loop makes sure we do.
By using floor division // we divide the number and are left with the integral part of the quotient. this means we only carry the integer (21) over and not what is after the dot (75) based on our example in the intro (174/8=21.75)
By assigning this number to divided we can also send this value to sum_base_10 for the next iteration in the end.
By using modulo,%, we will get the remainder. This is appended to the remainder_list so we can output it later.
It is a while loop that keeps going until we hit 0
If output base is 16If output_base is 16, that means the user wants a hexadecimal output. We need to convert any number greater than 9 to a letter.
Just as we did earlier, we create a dictionary to help converting. If we find a match, we convert the number to a letter and append it to the list.
And Finally:
return ''.join(remainder_list[::-1])
This reverses and turns our list into a string we can return. If you want to return an int, you can use int(). Make sure you account for Hexadecimal numbers if the user asks for a Base-16 output.
Phew! The majority of our code is done.
The last piece of the puzzle is to interact with the user. It is a straight forward while loop where the user types in numbers, we validate them and run the converter if it validates. The user has the option to do it as many times as he/she wants.
I like to create user interactions with while loops based on the state of a variable; like proceed we have here. This way we can just keep going as long as the user wants.
It has two levels. The first while initiates the main loop based on proceed.lower() == ‘y’.
The second declare valid_input=False , because we want to validate all the input before we pass it to convert_number_system(). As long as the input is False we need new input. After the user gives us his/her input, it runs the validator. If it passes, we can initiate convert_number_system()
In the end, we ask the user if he/she wants to go again. If the user types ‘y’ , we run the code again. If he/she types anything else, we quit the program.
An alternative way to do this is to ask the user to either type the number he/she wants to convert or quit. in the number_input variable.
This program covers several aspects of programming. First, we need to find the problem. The problem is that it takes a lot of time to manually convert all the numbers.
Then we find/learn the math to solve the problem and find what’s common. As it turns out, we can convert anything to anything with the same formula. We only need to handle binary and hexadecimal input and we need to make sure we don’t try to calculate Base-1. This means we can use functions to handle our code.
Everything is wrapped in a menu, a user interaction, and the underlying execution code is lurking in the background.
I hope you learned something by reading this. If you find any issues with the code or have other ideas, please let me know. Feel free to grab the code and continue developing it for your own projects.
|
[
{
"code": null,
"e": 401,
"s": 172,
"text": "In this article, we will build a calculator we can use to convert any number from any base to any other base. In number systems, “Base” tells us how many numbers you have available. Binary has 2, octal has 8, decimal has 10 etc."
},
{
"code": null,
"e": 548,
"s": 401,
"text": "The program we are about to write can handle any number and base we throw at it. When we figure out the math behind it, it is very easy to set up."
},
{
"code": null,
"e": 705,
"s": 548,
"text": "This calculator is based on math (Aren’t they all?). We might need to refresh our memory on the theory of converting between bases (or learn something new.)"
},
{
"code": null,
"e": 970,
"s": 705,
"text": "If you had science-driven math in school or studied computers at any level, chances are you have converted from one number system to another. You might remember the binary table or talks about “the decimal system”, “the octal system”, and “the hexadecimal system”."
},
{
"code": null,
"e": 1278,
"s": 970,
"text": "The decimal system (Base-10) is the one we use daily when we count. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. When we run out of numbers, we add another position to the left → 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21... etc. When we run out of numbers again, we add a new position → 100, 101, 102...118, 119, 120."
},
{
"code": null,
"e": 1323,
"s": 1278,
"text": "Yes, yes... I remember elementary school...."
},
{
"code": null,
"e": 1638,
"s": 1323,
"text": "We don’t think about it, because we learn this when we are 2–3 years old. Tell a kid to count using an octal system (Base-8) and they will most likely look at you for a few seconds before returning to their homework on their iPad. The theory is easy and identical to the decimal system, we are just not used to it."
},
{
"code": null,
"e": 1689,
"s": 1638,
"text": "Counting in the octal system would look like this:"
},
{
"code": null,
"e": 1742,
"s": 1689,
"text": "0,1,2,3,4,5,6,7 → 10,11,12,13,14,15,16,17 → 20,21..."
},
{
"code": null,
"e": 1983,
"s": 1742,
"text": "The first conversion we should look at is going from any base (Base-N) to the decimal system(Base-10). It is very easy to convert from The decimal system to any other base. Therefore, it is valuable to know how to get to the decimal system."
},
{
"code": null,
"e": 2144,
"s": 1983,
"text": "If we keep using decimal and octal as examples, we can convert a number in the octal system to its equivalent in the decimal system. Let’s pick a random number."
},
{
"code": null,
"e": 2171,
"s": 2144,
"text": "256(Base-8) → ???(Base-10)"
},
{
"code": null,
"e": 2208,
"s": 2171,
"text": "(I promise, 256 was actually random)"
},
{
"code": null,
"e": 2347,
"s": 2208,
"text": "We have three positions 2 (hundreds), 5(tens) and 6(ones). These positions can hold between 0–7 (8 numbers)as you remember from the intro."
},
{
"code": null,
"e": 2471,
"s": 2347,
"text": "We need to convert each of the numbers in all positions to the decimal system. The decimal system can hold 0–9 (10 numbers)"
},
{
"code": null,
"e": 2700,
"s": 2471,
"text": "The way we do this is that we take each number and multiply it with the base powered by the position index (num * (base^position)). If we start from the lowest number to the right, we multiply 6 with 80, 5 with 81 and 2 with 82."
},
{
"code": null,
"e": 2772,
"s": 2700,
"text": "Here is an illustration that will make this a lot easier to understand:"
},
{
"code": null,
"e": 2916,
"s": 2772,
"text": "When we have the number in the decimal system (Base-10) it is really easy to go to any system. Let’s go back from 174 (Base-10) to 256 (Base-8)"
},
{
"code": null,
"e": 3279,
"s": 2916,
"text": "We find the number in another base is by dividing it with the base and keep the remainder. The remainders will construct the number in the other base for us. When we have the remainders, we read the number from the least significant number to the most significant number, meaning from bottom to top. There you have your new number represented in your new base! "
},
{
"code": null,
"e": 3536,
"s": 3279,
"text": "174/2 gives us 21.75. Notice how 21 is red and .75 is green. We send 21 to the next line and deal with 0.75. If we multiply 0.75 with the base, we are left with the remainder (which is the number we are after). This number is sent to the far right in blue."
},
{
"code": null,
"e": 3639,
"s": 3536,
"text": "When we reach 0, we are officially done and can pack our bags with a beautiful number in our new base."
},
{
"code": null,
"e": 3763,
"s": 3639,
"text": "Not only does this mean we can go from Base-10 to Base-8 and vice versa. We can go from Base-X to Base-Y. Any Base we want."
},
{
"code": null,
"e": 3793,
"s": 3763,
"text": "It feels something like this:"
},
{
"code": null,
"e": 3936,
"s": 3793,
"text": "If you are still not sure how this works, I suggest checking out “The Organic Chemistry Tutor”. His videos are the best I know on the subject:"
},
{
"code": null,
"e": 3952,
"s": 3936,
"text": "www.youtube.com"
},
{
"code": null,
"e": 3985,
"s": 3952,
"text": "It’s time to dive into the code!"
},
{
"code": null,
"e": 4460,
"s": 3985,
"text": "Note: I do most of my programming manually. This means that I don’t use too many libraries because I want to learn as much as possible. In this code I do use standard python functions like bin() because I want to show you it’s possible, but instead of using hex(), I think it was more fun to manually code the same functions. In a production environment, you probably want to keep it short and use libraries that solve your problems instead of coding everything from scratch"
},
{
"code": null,
"e": 4655,
"s": 4460,
"text": "This program is just one main.py file with all the code in one document. If you wish you can extend this however you like. A Number Class? Sure, why not. GUI? Also something we should look into."
},
{
"code": null,
"e": 4785,
"s": 4655,
"text": "I recommend working with a base converter calculator online while coding to double-check that your code outputs the right values."
},
{
"code": null,
"e": 4803,
"s": 4785,
"text": "Here is the gist:"
},
{
"code": null,
"e": 4902,
"s": 4803,
"text": "The logic behind the code is that we pass three arguments to the function convert_number_system():"
},
{
"code": null,
"e": 4949,
"s": 4902,
"text": "input_number is the number we want to convert."
},
{
"code": null,
"e": 4997,
"s": 4949,
"text": "input_base is the base we wish to convert from."
},
{
"code": null,
"e": 5044,
"s": 4997,
"text": "output_base is the base we wish to convert to."
},
{
"code": null,
"e": 5159,
"s": 5044,
"text": "I haven’t used multiline string to print menus before, but it would make perfect sense to create a menu like this."
},
{
"code": null,
"e": 5282,
"s": 5159,
"text": "The function returns the whole menu string so we can use it anywhere we want. We don’t have to worry about newline either."
},
{
"code": null,
"e": 5637,
"s": 5282,
"text": "return ( '''----------------------------------------------------------Welcome to the Number Base converter!The system will ask you for:- The Number to convert- What base you want to convert FROM- What base you want to convert TO** REMEMBER: All numbers must be integers!(unless HEX) **---------------------------------------------------------- ''')"
},
{
"code": null,
"e": 5791,
"s": 5637,
"text": "Instead of checking the user input in the converter function, I wanted to create validators as functions. By doing that we create code that is re-usable."
},
{
"code": null,
"e": 5857,
"s": 5791,
"text": "This function just checks if the number is a valid binary number."
},
{
"code": null,
"e": 6120,
"s": 5857,
"text": "We don’t want to check a long string with several occurrences of the same number. If we convert it to a set we remove duplicates. Sets can not hold multiple instances of an item. We use list comprehension to convert the input to an int and check it against [0,1]"
},
{
"code": null,
"e": 6168,
"s": 6120,
"text": "[int(item) for item in set(list(check_number))]"
},
{
"code": null,
"e": 6394,
"s": 6168,
"text": "I chose to pass strings from the user interaction and create integers of the input when needed. int(item) makes sure all the numbers are integers (we could check a string against a string as well (‘0’ , ‘1’) if we wanted to)."
},
{
"code": null,
"e": 6438,
"s": 6394,
"text": "This is how it would look behind the scene:"
},
{
"code": null,
"e": 6493,
"s": 6438,
"text": "‘10010011’ → [‘1’,’0',’0',’1',’0',’0',’1',’1'] → [0,1]"
},
{
"code": null,
"e": 6663,
"s": 6493,
"text": "if 0 is in [0,1] it checks out fine, if 1 is in [0,1], that also checks out fine. If you had a number like 23, both digits would fail and the function would return False"
},
{
"code": null,
"e": 6845,
"s": 6663,
"text": "Nothing fancy here... The code checks if the input contains the defined legal characters. We work with numbers 0–9 and because we support HEX, we include a-f as valid input as well."
},
{
"code": null,
"e": 6987,
"s": 6845,
"text": "This function makes use of the other validators and validates all the input so we know if there is a point in proceeding with the conversion."
},
{
"code": null,
"e": 7047,
"s": 6987,
"text": "First it checks if we have entered a number or a hex value."
},
{
"code": null,
"e": 7212,
"s": 7047,
"text": "Then we check the bases. If input_base is 2, we are converting a binary number. Therefore, the input_number must be digits only and if it is, it has to be 0s or 1s."
},
{
"code": null,
"e": 7515,
"s": 7212,
"text": "If the input is both numbers and letters it is a hexadecimal number. If the input_base is NOT 16, then we can’t convert it. HEX is Base-16 and any other base would calculate incorrectly. We could consider making a pre-filled input base during the interaction when someone types in a hexadecimal number."
},
{
"code": null,
"e": 7665,
"s": 7515,
"text": "Last we check if the user tries to convert to- or from a Base-1. That is not possible so instead of crashing the program, we want to return an error."
},
{
"code": null,
"e": 7888,
"s": 7665,
"text": "Now, it is time for the main part of the code. This is where we will make use of our math skills. This function is carrying out the match we looked at earlier, and it has a few safety steps to make sure we output correctly"
},
{
"code": null,
"e": 8019,
"s": 7888,
"text": "remainder_list holds the numbers we want to return. If you remember the math you should instantly recognize the keyword remainder."
},
{
"code": null,
"e": 8177,
"s": 8019,
"text": "sum_base_10. We want to use the Base-10 as an intermediate step. We set the initial value to 0 and then we add whatever values we calculate to this variable."
},
{
"code": null,
"e": 8192,
"s": 8177,
"text": "output binary:"
},
{
"code": null,
"e": 8247,
"s": 8192,
"text": "if output_base == 2: return (bin(input_number)[2:])"
},
{
"code": null,
"e": 8414,
"s": 8247,
"text": "If the user wants a binary output, we can use the built-in function bin(). We don’t have to because the math is the same no matter what we pass, but it is fun to try."
},
{
"code": null,
"e": 8613,
"s": 8414,
"text": "bin() returns 0b and the binary. The 0b tells us it is a binary number. We want to return the actual number. That’s what the [2:] is for. If you run this in your terminal you can see the difference:"
},
{
"code": null,
"e": 8707,
"s": 8613,
"text": ">>> check_number = 23>>> print(bin(check_number))0b10111>>> print(bin(check_number)[2:])10111"
},
{
"code": null,
"e": 8746,
"s": 8707,
"text": "It will print from index 2 and onward."
},
{
"code": null,
"e": 8849,
"s": 8746,
"text": "Note that I have left the hex() version in the code, but commented out. You can use it if you want to."
},
{
"code": null,
"e": 9153,
"s": 8849,
"text": "The Base is NOT 10:If the base is not 10, we go through our intermediate step. First, we reverse the list (you don’t have to do this, but then you need to flip the index in the loop later. I find it easier to flip the list.) Reversing lists in Python can be done with this fantastic built-in code [::-1]"
},
{
"code": null,
"e": 9196,
"s": 9153,
"text": "reversed_input_number = input_number[::-1]"
},
{
"code": null,
"e": 9394,
"s": 9196,
"text": "hex_helper_dict helps us handling numbers above 9 if the user sent a hex input. If you remember our formula, we are multiplying the numbers in each position with the base index powered by position."
},
{
"code": null,
"e": 9435,
"s": 9394,
"text": "Here is 256 again from octal to decimal:"
},
{
"code": null,
"e": 9466,
"s": 9435,
"text": "2*(82) + 5*(81) + 6*(80) = 174"
},
{
"code": null,
"e": 9534,
"s": 9466,
"text": "If the number is hexadecimal, like 23e, it actually reads 2 , 3, 14"
},
{
"code": null,
"e": 9569,
"s": 9534,
"text": "2*(162) + 3*(161) + 14*(160) = 574"
},
{
"code": null,
"e": 9606,
"s": 9569,
"text": "This loop helps us with all of that:"
},
{
"code": null,
"e": 9827,
"s": 9606,
"text": "for index, number in enumerate(reversed_input_number): for key,value in hex_helper_dict.items(): if str(number).lower() == key: number = value sum_base_10 += (int(number)*(int(input_base)**index))"
},
{
"code": null,
"e": 9984,
"s": 9827,
"text": "If you look at the code above, you can see that we use both enumerate and .items() to make sure we can access everything we need to carry out our operation."
},
{
"code": null,
"e": 10291,
"s": 9984,
"text": "By using enumerate, we can access both the value and the index of the variable. When we loop through the variable we check if the number (ex. e) is equal to any of the keys in the dictionary. In the case of 23e, it is and we want to set the number to 14 instead so we can use it for the actual calculation."
},
{
"code": null,
"e": 10345,
"s": 10291,
"text": "sum_base_10 += (int(number)*(int(input_base)**index))"
},
{
"code": null,
"e": 10562,
"s": 10345,
"text": "Now that we are sure no numbers are actually letters, we can iterate through the numbers (let’s stay with 256) and do the operations. For each number we loop through, we do the multiplication we talked about earlier."
},
{
"code": null,
"e": 10609,
"s": 10562,
"text": "(int(number)*(int(input_base)**index))6*(8**0)"
},
{
"code": null,
"e": 10661,
"s": 10609,
"text": "The values we end up with are added to sum_base_10."
},
{
"code": null,
"e": 10741,
"s": 10661,
"text": "The Base IS 10:Great, carry on. We just assign the input number to sum_base_10:"
},
{
"code": null,
"e": 10799,
"s": 10741,
"text": "elif input_base == 10: sum_base_10 = int(input_number)"
},
{
"code": null,
"e": 10917,
"s": 10799,
"text": "Do the mathNow that we have the Base-10 value, we can do the division to find the remainders and find our new number."
},
{
"code": null,
"e": 11070,
"s": 10917,
"text": "while sum_base_10 > 0: divided = sum_base_10// int(output_base) remainder_list.append(str(sum_base_10 % int(output_base)) sum_base_10 = divided"
},
{
"code": null,
"e": 11137,
"s": 11070,
"text": "We need to divide until we hit 0. The while loop makes sure we do."
},
{
"code": null,
"e": 11368,
"s": 11137,
"text": "By using floor division // we divide the number and are left with the integral part of the quotient. this means we only carry the integer (21) over and not what is after the dot (75) based on our example in the intro (174/8=21.75)"
},
{
"code": null,
"e": 11482,
"s": 11368,
"text": "By assigning this number to divided we can also send this value to sum_base_10 for the next iteration in the end."
},
{
"code": null,
"e": 11594,
"s": 11482,
"text": "By using modulo,%, we will get the remainder. This is appended to the remainder_list so we can output it later."
},
{
"code": null,
"e": 11645,
"s": 11594,
"text": "It is a while loop that keeps going until we hit 0"
},
{
"code": null,
"e": 11793,
"s": 11645,
"text": "If output base is 16If output_base is 16, that means the user wants a hexadecimal output. We need to convert any number greater than 9 to a letter."
},
{
"code": null,
"e": 11941,
"s": 11793,
"text": "Just as we did earlier, we create a dictionary to help converting. If we find a match, we convert the number to a letter and append it to the list."
},
{
"code": null,
"e": 11954,
"s": 11941,
"text": "And Finally:"
},
{
"code": null,
"e": 11991,
"s": 11954,
"text": "return ''.join(remainder_list[::-1])"
},
{
"code": null,
"e": 12187,
"s": 11991,
"text": "This reverses and turns our list into a string we can return. If you want to return an int, you can use int(). Make sure you account for Hexadecimal numbers if the user asks for a Base-16 output."
},
{
"code": null,
"e": 12227,
"s": 12187,
"text": "Phew! The majority of our code is done."
},
{
"code": null,
"e": 12475,
"s": 12227,
"text": "The last piece of the puzzle is to interact with the user. It is a straight forward while loop where the user types in numbers, we validate them and run the converter if it validates. The user has the option to do it as many times as he/she wants."
},
{
"code": null,
"e": 12647,
"s": 12475,
"text": "I like to create user interactions with while loops based on the state of a variable; like proceed we have here. This way we can just keep going as long as the user wants."
},
{
"code": null,
"e": 12739,
"s": 12647,
"text": "It has two levels. The first while initiates the main loop based on proceed.lower() == ‘y’."
},
{
"code": null,
"e": 13031,
"s": 12739,
"text": "The second declare valid_input=False , because we want to validate all the input before we pass it to convert_number_system(). As long as the input is False we need new input. After the user gives us his/her input, it runs the validator. If it passes, we can initiate convert_number_system()"
},
{
"code": null,
"e": 13187,
"s": 13031,
"text": "In the end, we ask the user if he/she wants to go again. If the user types ‘y’ , we run the code again. If he/she types anything else, we quit the program."
},
{
"code": null,
"e": 13325,
"s": 13187,
"text": "An alternative way to do this is to ask the user to either type the number he/she wants to convert or quit. in the number_input variable."
},
{
"code": null,
"e": 13493,
"s": 13325,
"text": "This program covers several aspects of programming. First, we need to find the problem. The problem is that it takes a lot of time to manually convert all the numbers."
},
{
"code": null,
"e": 13805,
"s": 13493,
"text": "Then we find/learn the math to solve the problem and find what’s common. As it turns out, we can convert anything to anything with the same formula. We only need to handle binary and hexadecimal input and we need to make sure we don’t try to calculate Base-1. This means we can use functions to handle our code."
},
{
"code": null,
"e": 13922,
"s": 13805,
"text": "Everything is wrapped in a menu, a user interaction, and the underlying execution code is lurking in the background."
}
] |
How to extend a Keras Model. Passing through instance keys and... | by Drew Hodun | Towards Data Science
|
Generally, you only need your Keras model to return prediction values, but there are situations where you want your predictions to retain a portion of the input. A common example is forwarding unique ‘instance keys’ while performing batch predictions. In this blog and corresponding notebook code, I’ll demonstrate how to modify the signature of a trained Keras model to forward features to the output or pass through instance keys.
Sometimes you’ll have a unique instance key that is associated with each row and you want that key to be output along with the prediction so you know which row the prediction belongs to. You’ll need to add keys when executing distributed batch predictions with a service like Cloud AI Platform batch prediction. Also, if you’re performing continuous evaluation on your model and you’d like to log metadata about predictions for later analysis. Lak Lakshmanan shows how to do this with TensorFlow estimators, but what about Keras?
Let’s say you have a previously trained model that has been saved with tf.saved_model.save(). Running the following, you can inspect the serving signature of the model and see the expected inputs and outputs:
tf.saved_model.save(model, MODEL_EXPORT_PATH)!saved_model_cli show — tag_set serve — signature_def serving_default — dir {MODEL_EXPORT_PATH}The given SavedModel SignatureDef contains the following input(s): inputs['image'] tensor_info: dtype: DT_FLOAT shape: (-1, 28, 28) name: serving_default_image:0The given SavedModel SignatureDef contains the following output(s): outputs['preds'] tensor_info: dtype: DT_FLOAT shape: (-1, 10) name: StatefulPartitionedCall:0Method name is: tensorflow/serving/predict
To pass through a unique row key and a previously saved model, load your model, create an alternative serving function, and re-save as follows:
loaded_model = tf.keras.models.load_model(MODEL_EXPORT_PATH)@tf.function(input_signature=[tf.TensorSpec([None], dtype=tf.string),tf.TensorSpec([None, 28, 28], dtype=tf.float32)])def keyed_prediction(key, image): pred = loaded_model(image, training=False) return { 'preds': pred, 'key': key }# Resave model, but specify new serving signatureKEYED_EXPORT_PATH = './keyed_model/'loaded_model.save(KEYED_EXPORT_PATH, signatures={'serving_default': keyed_prediction})
Now when we inspect the serving signature of the model, we will see that it has the key as both input and output:
!saved_model_cli show --tag_set serve --signature_def serving_default --dir {KEYED_EXPORT_PATH}The given SavedModel SignatureDef contains the following input(s): inputs['image'] tensor_info: dtype: DT_FLOAT shape: (-1, 28, 28) name: serving_default_image:0 inputs['key'] tensor_info: dtype: DT_STRING shape: (-1) name: serving_default_key:0The given SavedModel SignatureDef contains the following output(s): outputs['key'] tensor_info: dtype: DT_STRING shape: (-1) name: StatefulPartitionedCall:0 outputs['preds'] tensor_info: dtype: DT_FLOAT shape: (-1, 10) name: StatefulPartitionedCall:1Method name is: tensorflow/serving/predict
Your model service will now expect both an image tensor and a key in any prediction call and will output preds and key in its response. An upside to this method is you don’t need access to the code that generated the model, just the serialized SavedModel.
Sometimes it’s handy to save the model with both serving signatures, either for compatibility reasons (i.e the default signature is unkeyed) or so that a single serving infrastructure can handle both keyed and unkeyed predictions and the user decides which to perform. You’ll need to pull the serving function off of the loaded model and indicate that as one of the serving signatures when saved out again:
inference_function = loaded_model.signatures['serving_default']loaded_model.save(DUAL_SIGNATURE_EXPORT_PATH, signatures={'serving_default': keyed_prediction, 'unkeyed_signature': inference_function})
You may also want to forward certain input features for model debugging purposes, or to compute evaluation metrics on specific slices of data, (e.g. compute RMSE of baby weight based on whether the baby is pre-term or full-term).
This example presumes you’re using multiple named Inputs, something you would do if you wanted to take advantage of TensorFlow feature columns as described here. Your first option would be to train the model as usual and take advantage of the Keras Functional API to create a slightly different model signature while maintaining the same weights:
tax_rate = Input(shape=(1,), dtype=tf.float32, name="tax_rate")rooms = Input(shape=(1,), dtype=tf.float32, name="rooms")x = tf.keras.layers.Concatenate()([tax_rate, rooms])x = tf.keras.layers.Dense(64, activation='relu')(x)price = tf.keras.layers.Dense(1, activation=None, name="price")(x)# Functional API model instead of Sequentialmodel = Model(inputs=[tax_rate, rooms], outputs=[price])# Compile, train, etc...###forward_model = Model(inputs=[tax_rate, rooms], outputs=[price, tax_rate])
The other alternative, particularly useful if you don’t have the code that generated the model, is modify the serving signature as you did with the keyed prediction model:
@tf.function(input_signature=[tf.TensorSpec([None, 1], dtype=tf.float32), tf.TensorSpec([None, 1], dtype=tf.float32)])def feature_forward_prediction(tax_rate, rooms): pred = model([tax_rate, rooms], training=False) return { 'price': pred, 'tax_rate': tax_rate }model.save(FORWARD_EXPORT_PATH, signatures={'serving_default': feature_forward_prediction})
Enjoy!
Thanks to Lak Lakshmanan for helping me update his original Estimator post to Keras.
|
[
{
"code": null,
"e": 605,
"s": 172,
"text": "Generally, you only need your Keras model to return prediction values, but there are situations where you want your predictions to retain a portion of the input. A common example is forwarding unique ‘instance keys’ while performing batch predictions. In this blog and corresponding notebook code, I’ll demonstrate how to modify the signature of a trained Keras model to forward features to the output or pass through instance keys."
},
{
"code": null,
"e": 1135,
"s": 605,
"text": "Sometimes you’ll have a unique instance key that is associated with each row and you want that key to be output along with the prediction so you know which row the prediction belongs to. You’ll need to add keys when executing distributed batch predictions with a service like Cloud AI Platform batch prediction. Also, if you’re performing continuous evaluation on your model and you’d like to log metadata about predictions for later analysis. Lak Lakshmanan shows how to do this with TensorFlow estimators, but what about Keras?"
},
{
"code": null,
"e": 1344,
"s": 1135,
"text": "Let’s say you have a previously trained model that has been saved with tf.saved_model.save(). Running the following, you can inspect the serving signature of the model and see the expected inputs and outputs:"
},
{
"code": null,
"e": 1881,
"s": 1344,
"text": "tf.saved_model.save(model, MODEL_EXPORT_PATH)!saved_model_cli show — tag_set serve — signature_def serving_default — dir {MODEL_EXPORT_PATH}The given SavedModel SignatureDef contains the following input(s): inputs['image'] tensor_info: dtype: DT_FLOAT shape: (-1, 28, 28) name: serving_default_image:0The given SavedModel SignatureDef contains the following output(s): outputs['preds'] tensor_info: dtype: DT_FLOAT shape: (-1, 10) name: StatefulPartitionedCall:0Method name is: tensorflow/serving/predict"
},
{
"code": null,
"e": 2025,
"s": 1881,
"text": "To pass through a unique row key and a previously saved model, load your model, create an alternative serving function, and re-save as follows:"
},
{
"code": null,
"e": 2511,
"s": 2025,
"text": "loaded_model = tf.keras.models.load_model(MODEL_EXPORT_PATH)@tf.function(input_signature=[tf.TensorSpec([None], dtype=tf.string),tf.TensorSpec([None, 28, 28], dtype=tf.float32)])def keyed_prediction(key, image): pred = loaded_model(image, training=False) return { 'preds': pred, 'key': key }# Resave model, but specify new serving signatureKEYED_EXPORT_PATH = './keyed_model/'loaded_model.save(KEYED_EXPORT_PATH, signatures={'serving_default': keyed_prediction})"
},
{
"code": null,
"e": 2625,
"s": 2511,
"text": "Now when we inspect the serving signature of the model, we will see that it has the key as both input and output:"
},
{
"code": null,
"e": 3322,
"s": 2625,
"text": "!saved_model_cli show --tag_set serve --signature_def serving_default --dir {KEYED_EXPORT_PATH}The given SavedModel SignatureDef contains the following input(s): inputs['image'] tensor_info: dtype: DT_FLOAT shape: (-1, 28, 28) name: serving_default_image:0 inputs['key'] tensor_info: dtype: DT_STRING shape: (-1) name: serving_default_key:0The given SavedModel SignatureDef contains the following output(s): outputs['key'] tensor_info: dtype: DT_STRING shape: (-1) name: StatefulPartitionedCall:0 outputs['preds'] tensor_info: dtype: DT_FLOAT shape: (-1, 10) name: StatefulPartitionedCall:1Method name is: tensorflow/serving/predict"
},
{
"code": null,
"e": 3578,
"s": 3322,
"text": "Your model service will now expect both an image tensor and a key in any prediction call and will output preds and key in its response. An upside to this method is you don’t need access to the code that generated the model, just the serialized SavedModel."
},
{
"code": null,
"e": 3985,
"s": 3578,
"text": "Sometimes it’s handy to save the model with both serving signatures, either for compatibility reasons (i.e the default signature is unkeyed) or so that a single serving infrastructure can handle both keyed and unkeyed predictions and the user decides which to perform. You’ll need to pull the serving function off of the loaded model and indicate that as one of the serving signatures when saved out again:"
},
{
"code": null,
"e": 4188,
"s": 3985,
"text": "inference_function = loaded_model.signatures['serving_default']loaded_model.save(DUAL_SIGNATURE_EXPORT_PATH, signatures={'serving_default': keyed_prediction, 'unkeyed_signature': inference_function})"
},
{
"code": null,
"e": 4418,
"s": 4188,
"text": "You may also want to forward certain input features for model debugging purposes, or to compute evaluation metrics on specific slices of data, (e.g. compute RMSE of baby weight based on whether the baby is pre-term or full-term)."
},
{
"code": null,
"e": 4765,
"s": 4418,
"text": "This example presumes you’re using multiple named Inputs, something you would do if you wanted to take advantage of TensorFlow feature columns as described here. Your first option would be to train the model as usual and take advantage of the Keras Functional API to create a slightly different model signature while maintaining the same weights:"
},
{
"code": null,
"e": 5256,
"s": 4765,
"text": "tax_rate = Input(shape=(1,), dtype=tf.float32, name=\"tax_rate\")rooms = Input(shape=(1,), dtype=tf.float32, name=\"rooms\")x = tf.keras.layers.Concatenate()([tax_rate, rooms])x = tf.keras.layers.Dense(64, activation='relu')(x)price = tf.keras.layers.Dense(1, activation=None, name=\"price\")(x)# Functional API model instead of Sequentialmodel = Model(inputs=[tax_rate, rooms], outputs=[price])# Compile, train, etc...###forward_model = Model(inputs=[tax_rate, rooms], outputs=[price, tax_rate])"
},
{
"code": null,
"e": 5428,
"s": 5256,
"text": "The other alternative, particularly useful if you don’t have the code that generated the model, is modify the serving signature as you did with the keyed prediction model:"
},
{
"code": null,
"e": 5804,
"s": 5428,
"text": "@tf.function(input_signature=[tf.TensorSpec([None, 1], dtype=tf.float32), tf.TensorSpec([None, 1], dtype=tf.float32)])def feature_forward_prediction(tax_rate, rooms): pred = model([tax_rate, rooms], training=False) return { 'price': pred, 'tax_rate': tax_rate }model.save(FORWARD_EXPORT_PATH, signatures={'serving_default': feature_forward_prediction})"
},
{
"code": null,
"e": 5811,
"s": 5804,
"text": "Enjoy!"
}
] |
Lucene - Update Document Operation
|
Update document is another important operation as part of indexing process. This operation is used when already indexed contents are updated and indexes become invalid. This operation is also known as re-indexing.
We update Document(s) containing Field(s) to IndexWriter where IndexWriter is used to update indexes.
We will now show you a step-wise approach and help you understand how to update document using a basic example.
Follow this step to update a document to an index −
Step 1 − Create a method to update a Lucene document from an updated text file.
private void updateDocument(File file) throws IOException {
Document document = new Document();
//update indexes for file contents
writer.updateDocument(new Term
(LuceneConstants.CONTENTS,
new FileReader(file)),document);
writer.close();
}
Follow these steps to create an IndexWriter −
Step 1 − IndexWriter class acts as a core component which creates/updates indexes during the indexing process.
Step 2 − Create object of IndexWriter.
Step 3 − Create a Lucene directory which should point to location where indexes are to be stored.
Step 4 − Initialize the IndexWriter object created with the index directory, a standard analyzer having version information and other required/optional parameters.
private IndexWriter writer;
public Indexer(String indexDirectoryPath) throws IOException {
//this directory will contain the indexes
Directory indexDirectory =
FSDirectory.open(new File(indexDirectoryPath));
//create the indexer
writer = new IndexWriter(indexDirectory,
new StandardAnalyzer(Version.LUCENE_36),true,
IndexWriter.MaxFieldLength.UNLIMITED);
}
Following are the two ways to update the document.
updateDocument(Term, Document) − Delete the document containing the term and add the document using the default analyzer (specified when index writer is created).
updateDocument(Term, Document) − Delete the document containing the term and add the document using the default analyzer (specified when index writer is created).
updateDocument(Term, Document,Analyzer) − Delete the document containing the term and add the document using the provided analyzer.
updateDocument(Term, Document,Analyzer) − Delete the document containing the term and add the document using the provided analyzer.
private void indexFile(File file) throws IOException {
System.out.println("Updating index for "+file.getCanonicalPath());
updateDocument(file);
}
To test the indexing process, let us create a Lucene application test.
Create a project with a name LuceneFirstApplication under a packagecom.tutorialspoint.lucene as explained in the Lucene - First Application chapter. You can also use the project created in EJB - First Application chapter as such for this chapter to understand the indexing process.
Create LuceneConstants.java,TextFileFilter.java and Indexer.java as explained in the Lucene - First Application chapter. Keep the rest of the files unchanged.
Create LuceneTester.java as mentioned below.
Clean and Build the application to make sure business logic is working as per the requirements.
This class is used to provide various constants to be used across the sample application.
package com.tutorialspoint.lucene;
public class LuceneConstants {
public static final String CONTENTS = "contents";
public static final String FILE_NAME = "filename";
public static final String FILE_PATH = "filepath";
public static final int MAX_SEARCH = 10;
}
This class is used as a .txt file filter.
package com.tutorialspoint.lucene;
import java.io.File;
import java.io.FileFilter;
public class TextFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().endsWith(".txt");
}
}
This class is used to index the raw data so that we can make it searchable using the Lucene library.
package com.tutorialspoint.lucene;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
public class Indexer {
private IndexWriter writer;
public Indexer(String indexDirectoryPath) throws IOException {
//this directory will contain the indexes
Directory indexDirectory =
FSDirectory.open(new File(indexDirectoryPath));
//create the indexer
writer = new IndexWriter(indexDirectory,
new StandardAnalyzer(Version.LUCENE_36),true,
IndexWriter.MaxFieldLength.UNLIMITED);
}
public void close() throws CorruptIndexException, IOException {
writer.close();
}
private void updateDocument(File file) throws IOException {
Document document = new Document();
//update indexes for file contents
writer.updateDocument(
new Term(LuceneConstants.FILE_NAME,
file.getName()),document);
writer.close();
}
private void indexFile(File file) throws IOException {
System.out.println("Updating index: "+file.getCanonicalPath());
updateDocument(file);
}
public int createIndex(String dataDirPath, FileFilter filter)
throws IOException {
//get all files in the data directory
File[] files = new File(dataDirPath).listFiles();
for (File file : files) {
if(!file.isDirectory()
&& !file.isHidden()
&& file.exists()
&& file.canRead()
&& filter.accept(file)
){
indexFile(file);
}
}
return writer.numDocs();
}
}
This class is used to test the indexing capability of the Lucene library.
package com.tutorialspoint.lucene;
import java.io.IOException;
public class LuceneTester {
String indexDir = "E:\\Lucene\\Index";
String dataDir = "E:\\Lucene\\Data";
Indexer indexer;
public static void main(String[] args) {
LuceneTester tester;
try {
tester = new LuceneTester();
tester.createIndex();
} catch (IOException e) {
e.printStackTrace();
}
}
private void createIndex() throws IOException {
indexer = new Indexer(indexDir);
int numIndexed;
long startTime = System.currentTimeMillis();
numIndexed = indexer.createIndex(dataDir, new TextFileFilter());
long endTime = System.currentTimeMillis();
indexer.close();
}
}
Here, we have used 10 text files from record1.txt to record10.txt containing names and other details of the students and put them in the directory E:\Lucene\Data. Test Data. An index directory path should be created as E:\Lucene\Index. After running this program, you can see the list of index files created in that folder.
Once you are done with the creation of the source, the raw data, the data directory and the index directory, you can proceed with the compiling and running of your program. To do this, keep the LuceneTester.Java file tab active and use either the Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your LuceneTester application. If your application runs successfully, it will print the following message in Eclipse IDE's console −
Updating index for E:\Lucene\Data\record1.txt
Updating index for E:\Lucene\Data\record10.txt
Updating index for E:\Lucene\Data\record2.txt
Updating index for E:\Lucene\Data\record3.txt
Updating index for E:\Lucene\Data\record4.txt
Updating index for E:\Lucene\Data\record5.txt
Updating index for E:\Lucene\Data\record6.txt
Updating index for E:\Lucene\Data\record7.txt
Updating index for E:\Lucene\Data\record8.txt
Updating index for E:\Lucene\Data\record9.txt
10 File indexed, time taken: 109 ms
Once you've run the above program successfully, you will have the following content in your index directory −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2057,
"s": 1843,
"text": "Update document is another important operation as part of indexing process. This operation is used when already indexed contents are updated and indexes become invalid. This operation is also known as re-indexing."
},
{
"code": null,
"e": 2159,
"s": 2057,
"text": "We update Document(s) containing Field(s) to IndexWriter where IndexWriter is used to update indexes."
},
{
"code": null,
"e": 2271,
"s": 2159,
"text": "We will now show you a step-wise approach and help you understand how to update document using a basic example."
},
{
"code": null,
"e": 2323,
"s": 2271,
"text": "Follow this step to update a document to an index −"
},
{
"code": null,
"e": 2403,
"s": 2323,
"text": "Step 1 − Create a method to update a Lucene document from an updated text file."
},
{
"code": null,
"e": 2674,
"s": 2403,
"text": "private void updateDocument(File file) throws IOException {\n Document document = new Document();\n\n //update indexes for file contents\n writer.updateDocument(new Term \n (LuceneConstants.CONTENTS, \n new FileReader(file)),document); \n writer.close();\n} "
},
{
"code": null,
"e": 2720,
"s": 2674,
"text": "Follow these steps to create an IndexWriter −"
},
{
"code": null,
"e": 2831,
"s": 2720,
"text": "Step 1 − IndexWriter class acts as a core component which creates/updates indexes during the indexing process."
},
{
"code": null,
"e": 2870,
"s": 2831,
"text": "Step 2 − Create object of IndexWriter."
},
{
"code": null,
"e": 2968,
"s": 2870,
"text": "Step 3 − Create a Lucene directory which should point to location where indexes are to be stored."
},
{
"code": null,
"e": 3132,
"s": 2968,
"text": "Step 4 − Initialize the IndexWriter object created with the index directory, a standard analyzer having version information and other required/optional parameters."
},
{
"code": null,
"e": 3526,
"s": 3132,
"text": "private IndexWriter writer;\n\npublic Indexer(String indexDirectoryPath) throws IOException {\n //this directory will contain the indexes\n Directory indexDirectory = \n FSDirectory.open(new File(indexDirectoryPath));\n \n //create the indexer\n writer = new IndexWriter(indexDirectory, \n new StandardAnalyzer(Version.LUCENE_36),true,\n IndexWriter.MaxFieldLength.UNLIMITED);\n}"
},
{
"code": null,
"e": 3577,
"s": 3526,
"text": "Following are the two ways to update the document."
},
{
"code": null,
"e": 3740,
"s": 3577,
"text": "updateDocument(Term, Document) − Delete the document containing the term and add the document using the default analyzer (specified when index writer is created)."
},
{
"code": null,
"e": 3903,
"s": 3740,
"text": "updateDocument(Term, Document) − Delete the document containing the term and add the document using the default analyzer (specified when index writer is created)."
},
{
"code": null,
"e": 4035,
"s": 3903,
"text": "updateDocument(Term, Document,Analyzer) − Delete the document containing the term and add the document using the provided analyzer."
},
{
"code": null,
"e": 4167,
"s": 4035,
"text": "updateDocument(Term, Document,Analyzer) − Delete the document containing the term and add the document using the provided analyzer."
},
{
"code": null,
"e": 4322,
"s": 4167,
"text": "private void indexFile(File file) throws IOException {\n System.out.println(\"Updating index for \"+file.getCanonicalPath());\n updateDocument(file); \n}"
},
{
"code": null,
"e": 4393,
"s": 4322,
"text": "To test the indexing process, let us create a Lucene application test."
},
{
"code": null,
"e": 4675,
"s": 4393,
"text": "Create a project with a name LuceneFirstApplication under a packagecom.tutorialspoint.lucene as explained in the Lucene - First Application chapter. You can also use the project created in EJB - First Application chapter as such for this chapter to understand the indexing process."
},
{
"code": null,
"e": 4834,
"s": 4675,
"text": "Create LuceneConstants.java,TextFileFilter.java and Indexer.java as explained in the Lucene - First Application chapter. Keep the rest of the files unchanged."
},
{
"code": null,
"e": 4879,
"s": 4834,
"text": "Create LuceneTester.java as mentioned below."
},
{
"code": null,
"e": 4975,
"s": 4879,
"text": "Clean and Build the application to make sure business logic is working as per the requirements."
},
{
"code": null,
"e": 5065,
"s": 4975,
"text": "This class is used to provide various constants to be used across the sample application."
},
{
"code": null,
"e": 5339,
"s": 5065,
"text": "package com.tutorialspoint.lucene;\n\npublic class LuceneConstants {\n public static final String CONTENTS = \"contents\";\n public static final String FILE_NAME = \"filename\";\n public static final String FILE_PATH = \"filepath\";\n public static final int MAX_SEARCH = 10;\n}"
},
{
"code": null,
"e": 5381,
"s": 5339,
"text": "This class is used as a .txt file filter."
},
{
"code": null,
"e": 5645,
"s": 5381,
"text": "package com.tutorialspoint.lucene;\n\nimport java.io.File;\nimport java.io.FileFilter;\n\npublic class TextFileFilter implements FileFilter {\n\n @Override\n public boolean accept(File pathname) {\n return pathname.getName().toLowerCase().endsWith(\".txt\");\n }\n}"
},
{
"code": null,
"e": 5746,
"s": 5645,
"text": "This class is used to index the raw data so that we can make it searchable using the Lucene library."
},
{
"code": null,
"e": 7735,
"s": 5746,
"text": "package com.tutorialspoint.lucene;\n\nimport java.io.File;\nimport java.io.FileFilter;\nimport java.io.FileReader;\nimport java.io.IOException;\n\nimport org.apache.lucene.analysis.standard.StandardAnalyzer;\nimport org.apache.lucene.document.Document;\nimport org.apache.lucene.document.Field;\nimport org.apache.lucene.index.CorruptIndexException;\nimport org.apache.lucene.index.IndexWriter;\nimport org.apache.lucene.store.Directory;\nimport org.apache.lucene.store.FSDirectory;\nimport org.apache.lucene.util.Version;\n\npublic class Indexer {\n\n private IndexWriter writer;\n\n public Indexer(String indexDirectoryPath) throws IOException {\n //this directory will contain the indexes\n Directory indexDirectory = \n FSDirectory.open(new File(indexDirectoryPath));\n\n //create the indexer\n writer = new IndexWriter(indexDirectory, \n new StandardAnalyzer(Version.LUCENE_36),true,\n IndexWriter.MaxFieldLength.UNLIMITED);\n }\n\n public void close() throws CorruptIndexException, IOException {\n writer.close();\n }\n\n private void updateDocument(File file) throws IOException {\n Document document = new Document();\n\n //update indexes for file contents\n writer.updateDocument(\n new Term(LuceneConstants.FILE_NAME,\n file.getName()),document); \n writer.close();\n } \n\n private void indexFile(File file) throws IOException {\n System.out.println(\"Updating index: \"+file.getCanonicalPath());\n updateDocument(file); \n }\n\n public int createIndex(String dataDirPath, FileFilter filter) \n throws IOException {\n //get all files in the data directory\n File[] files = new File(dataDirPath).listFiles();\n\n for (File file : files) {\n if(!file.isDirectory()\n && !file.isHidden()\n && file.exists()\n && file.canRead()\n && filter.accept(file)\n ){\n indexFile(file);\n }\n }\n return writer.numDocs();\n }\n}"
},
{
"code": null,
"e": 7809,
"s": 7735,
"text": "This class is used to test the indexing capability of the Lucene library."
},
{
"code": null,
"e": 8553,
"s": 7809,
"text": "package com.tutorialspoint.lucene;\n\nimport java.io.IOException;\n\npublic class LuceneTester {\n\t\n String indexDir = \"E:\\\\Lucene\\\\Index\";\n String dataDir = \"E:\\\\Lucene\\\\Data\";\n Indexer indexer;\n \n public static void main(String[] args) {\n LuceneTester tester;\n try {\n tester = new LuceneTester();\n tester.createIndex();\n } catch (IOException e) {\n e.printStackTrace();\n } \n }\n\n private void createIndex() throws IOException {\n indexer = new Indexer(indexDir);\n int numIndexed;\n long startTime = System.currentTimeMillis();\t\n numIndexed = indexer.createIndex(dataDir, new TextFileFilter());\n long endTime = System.currentTimeMillis();\n indexer.close();\n }\n}"
},
{
"code": null,
"e": 8877,
"s": 8553,
"text": "Here, we have used 10 text files from record1.txt to record10.txt containing names and other details of the students and put them in the directory E:\\Lucene\\Data. Test Data. An index directory path should be created as E:\\Lucene\\Index. After running this program, you can see the list of index files created in that folder."
},
{
"code": null,
"e": 9334,
"s": 8877,
"text": "Once you are done with the creation of the source, the raw data, the data directory and the index directory, you can proceed with the compiling and running of your program. To do this, keep the LuceneTester.Java file tab active and use either the Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your LuceneTester application. If your application runs successfully, it will print the following message in Eclipse IDE's console −"
},
{
"code": null,
"e": 9832,
"s": 9334,
"text": "Updating index for E:\\Lucene\\Data\\record1.txt\nUpdating index for E:\\Lucene\\Data\\record10.txt\nUpdating index for E:\\Lucene\\Data\\record2.txt\nUpdating index for E:\\Lucene\\Data\\record3.txt\nUpdating index for E:\\Lucene\\Data\\record4.txt\nUpdating index for E:\\Lucene\\Data\\record5.txt\nUpdating index for E:\\Lucene\\Data\\record6.txt\nUpdating index for E:\\Lucene\\Data\\record7.txt\nUpdating index for E:\\Lucene\\Data\\record8.txt\nUpdating index for E:\\Lucene\\Data\\record9.txt\n10 File indexed, time taken: 109 ms\n"
},
{
"code": null,
"e": 9942,
"s": 9832,
"text": "Once you've run the above program successfully, you will have the following content in your index directory −"
},
{
"code": null,
"e": 9949,
"s": 9942,
"text": " Print"
},
{
"code": null,
"e": 9960,
"s": 9949,
"text": " Add Notes"
}
] |
Client-side Validation
|
In this chapter, we will learn how validation helps in Python Pentesting.
The main goal of validation is to test and ensure that the user has provided necessary and properly formatted information needed to successfully complete an operation.
There are two different types of validation −
client-side validation (web browser)
server-side validation
The user input validation that takes place on the server side during a post back session is called server-side validation. The languages such as PHP and ASP.Net use server-side validation. Once the validation process on server side is over, the feedback is sent back to client by generating a new and dynamic web page. With the help of server-side validation, we can get protection against malicious users.
On the other hand, the user input validation that takes place on the client side is called client-side validation. Scripting languages such as JavaScript and VBScript are used for client-side validation. In this kind of validation, all the user input validation is done in user’s browser only. It is not so secure like server-side validation because the hacker can easily bypass our client side scripting language and submit dangerous input to the server.
Parameter passing in HTTP protocol can be done with the help of POST and GET methods. GET is used to request data from a specified resource and POST is used to send data to a server to create or update a resource. One major difference between both these methods is that if a website is using GET method then the passing parameters are shown in the URL and we can change this parameter and pass it to web server. For example, the query string (name/value pairs) is sent in the URL of a GET request: /test/hello_form.php?name1 = value1&name2 = value2. On the other hand, parameters are not shown while using the POST method. The data sent to the server with POST is stored in the request body of the HTTP request. For example, POST /test/hello_form.php HTTP/1.1 Host: ‘URL’ name1 = value1&name2 = value2.
The Python module that we are going to use is mechanize. It is a Python web browser, which is providing the facility of obtaining web forms in a web page and facilitates the submission of input values too. With the help of mechanize, we can bypass the validation and temper client-side parameters. However, before importing it in our Python script, we need to install it by executing the following command −
pip install mechanize
Following is a Python script, which uses mechanize to bypass the validation of a web form using POST method to pass the parameter. The web form can be taken from the link https://www.tutorialspoint.com/php/php_validation_example.htm and can be used in any dummy website of your choice.
To begin with, let us import the mechanize browser −
import mechanize
Now, we will create an object named brwsr of the mechanize browser −
brwsr = mechanize.Browser()
The next line of code shows that the user agent is not a robot.
brwsr.set_handle_robots( False )
Now, we need to provide the url of our dummy website containing the web form on which we need to bypass validation.
url = input("Enter URL ")
Now, following lines will set some parenters to true.
brwsr.set_handle_equiv(True)
brwsr.set_handle_gzip(True)
brwsr.set_handle_redirect(True)
brwsr.set_handle_referer(True)
Next it will open the web page and print the web form on that page.
brwsr.open(url)
for form in brwsr.forms():
print form
Next line of codes will bypass the validations on the given fields.
brwsr.select_form(nr = 0)
brwsr.form['name'] = ''
brwsr.form['gender'] = ''
brwsr.submit()
The last part of the script can be changed according to the fields of web form on which we want to bypass validation. Here in the above script, we have taken two fields — ‘name’ and ‘gender’ which cannot be left blank (you can see in the coding of web form) but this script will bypass that validation.
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1931,
"s": 1857,
"text": "In this chapter, we will learn how validation helps in Python Pentesting."
},
{
"code": null,
"e": 2099,
"s": 1931,
"text": "The main goal of validation is to test and ensure that the user has provided necessary and properly formatted information needed to successfully complete an operation."
},
{
"code": null,
"e": 2145,
"s": 2099,
"text": "There are two different types of validation −"
},
{
"code": null,
"e": 2182,
"s": 2145,
"text": "client-side validation (web browser)"
},
{
"code": null,
"e": 2205,
"s": 2182,
"text": "server-side validation"
},
{
"code": null,
"e": 2612,
"s": 2205,
"text": "The user input validation that takes place on the server side during a post back session is called server-side validation. The languages such as PHP and ASP.Net use server-side validation. Once the validation process on server side is over, the feedback is sent back to client by generating a new and dynamic web page. With the help of server-side validation, we can get protection against malicious users."
},
{
"code": null,
"e": 3068,
"s": 2612,
"text": "On the other hand, the user input validation that takes place on the client side is called client-side validation. Scripting languages such as JavaScript and VBScript are used for client-side validation. In this kind of validation, all the user input validation is done in user’s browser only. It is not so secure like server-side validation because the hacker can easily bypass our client side scripting language and submit dangerous input to the server."
},
{
"code": null,
"e": 3871,
"s": 3068,
"text": "Parameter passing in HTTP protocol can be done with the help of POST and GET methods. GET is used to request data from a specified resource and POST is used to send data to a server to create or update a resource. One major difference between both these methods is that if a website is using GET method then the passing parameters are shown in the URL and we can change this parameter and pass it to web server. For example, the query string (name/value pairs) is sent in the URL of a GET request: /test/hello_form.php?name1 = value1&name2 = value2. On the other hand, parameters are not shown while using the POST method. The data sent to the server with POST is stored in the request body of the HTTP request. For example, POST /test/hello_form.php HTTP/1.1 Host: ‘URL’ name1 = value1&name2 = value2."
},
{
"code": null,
"e": 4279,
"s": 3871,
"text": "The Python module that we are going to use is mechanize. It is a Python web browser, which is providing the facility of obtaining web forms in a web page and facilitates the submission of input values too. With the help of mechanize, we can bypass the validation and temper client-side parameters. However, before importing it in our Python script, we need to install it by executing the following command −"
},
{
"code": null,
"e": 4302,
"s": 4279,
"text": "pip install mechanize\n"
},
{
"code": null,
"e": 4588,
"s": 4302,
"text": "Following is a Python script, which uses mechanize to bypass the validation of a web form using POST method to pass the parameter. The web form can be taken from the link https://www.tutorialspoint.com/php/php_validation_example.htm and can be used in any dummy website of your choice."
},
{
"code": null,
"e": 4641,
"s": 4588,
"text": "To begin with, let us import the mechanize browser −"
},
{
"code": null,
"e": 4659,
"s": 4641,
"text": "import mechanize\n"
},
{
"code": null,
"e": 4728,
"s": 4659,
"text": "Now, we will create an object named brwsr of the mechanize browser −"
},
{
"code": null,
"e": 4757,
"s": 4728,
"text": "brwsr = mechanize.Browser()\n"
},
{
"code": null,
"e": 4821,
"s": 4757,
"text": "The next line of code shows that the user agent is not a robot."
},
{
"code": null,
"e": 4854,
"s": 4821,
"text": "brwsr.set_handle_robots( False )"
},
{
"code": null,
"e": 4970,
"s": 4854,
"text": "Now, we need to provide the url of our dummy website containing the web form on which we need to bypass validation."
},
{
"code": null,
"e": 4997,
"s": 4970,
"text": "url = input(\"Enter URL \")\n"
},
{
"code": null,
"e": 5051,
"s": 4997,
"text": "Now, following lines will set some parenters to true."
},
{
"code": null,
"e": 5171,
"s": 5051,
"text": "brwsr.set_handle_equiv(True)\nbrwsr.set_handle_gzip(True)\nbrwsr.set_handle_redirect(True)\nbrwsr.set_handle_referer(True)"
},
{
"code": null,
"e": 5239,
"s": 5171,
"text": "Next it will open the web page and print the web form on that page."
},
{
"code": null,
"e": 5296,
"s": 5239,
"text": "brwsr.open(url)\nfor form in brwsr.forms():\n print form"
},
{
"code": null,
"e": 5364,
"s": 5296,
"text": "Next line of codes will bypass the validations on the given fields."
},
{
"code": null,
"e": 5455,
"s": 5364,
"text": "brwsr.select_form(nr = 0)\nbrwsr.form['name'] = ''\nbrwsr.form['gender'] = ''\nbrwsr.submit()"
},
{
"code": null,
"e": 5758,
"s": 5455,
"text": "The last part of the script can be changed according to the fields of web form on which we want to bypass validation. Here in the above script, we have taken two fields — ‘name’ and ‘gender’ which cannot be left blank (you can see in the coding of web form) but this script will bypass that validation."
},
{
"code": null,
"e": 5795,
"s": 5758,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5811,
"s": 5795,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5844,
"s": 5811,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5863,
"s": 5844,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5898,
"s": 5863,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 5920,
"s": 5898,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 5954,
"s": 5920,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5982,
"s": 5954,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6017,
"s": 5982,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 6031,
"s": 6017,
"text": " Lets Kode It"
},
{
"code": null,
"e": 6064,
"s": 6031,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6081,
"s": 6064,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6088,
"s": 6081,
"text": " Print"
},
{
"code": null,
"e": 6099,
"s": 6088,
"text": " Add Notes"
}
] |
Jupyter Notebook or Lab or VS Code? | by Daniel Deutsch | Towards Data Science
|
I have been working with various IDEs for my Python development over the last few years. Recently I asked myself if it would make sense to check if it is useful to update my current practice and see if alternatives offer better productivity. There is often the question if one IDE is better than the other. In this article, I want to show that the best way is to use the best tool for a specific task.
Jupyter Notebook or Lab or VS Code? Why not all?
Table of Contents
Why you don’t need to decide which is better
Why Jupyter Notebook
Why Jupyter Lab
Why VS Code
Disclaimer
About
Currently, I use a mix of
Jupyter Notebook
Jupyter Lab
VS Code
I am always asking myself if Jupyter Lab is already so far developed that it can replace my Jupyter Notebook (NB) workflow. The short answer is no. There are still many advantages of NB over Lab, which I will elaborate on in the following. However, and this is important to understand, it doesn’t need to be replaced. You can easily use both of them for the tasks they are good at.
Therefore I use:
NB for developing a Data Science Proof-of-concept (POC)
Jupyter Lab for managing and re-arranging my POCs
VS Code for everything that is not notebook-related.
In essence, I use all three tools to various degrees in a data science project.
I still use the NB for most of my POC work. Here are some reasons why:
With jupyterthemes you can easily adapt the theme to your needs. I used a lot the “chesterish” theme (jt -t chesterish -T -N) which looks like
You can specify a with various jupyterthemes flags. Currently, I use it with !jt -t chesterish -f fira -fs 10 -nf ptsans -nfs 11 -N -kl -cursw 2 -cursc r -cellw 95% -T ( you will find similar setups on other articles). Check the official website to see a full list of the flags and their meanings. This setup looks like this:
I prefer the dark theme because I work quite a lot in front of the monitor and whatever helps to reduce strain on my eyes is very welcome.
I use some specific NB configurations which might be helpful for you as well.
%load_ext autoreload%autoreload 2%matplotlib inline%config IPCompleter.greedy = Truepd.options.display.max_columns = Nonepd.options.display.max_rows = 200sns.set_palette("bright")sns.set(style="darkgrid")sns.set(rc={'figure.figsize':(30,30)})InteractiveShell.ast_node_interactivity = "all"ip = get_ipython()ip.register_magics(jupyternotify.JupyterNotifyMagics)%autonotify -a 120
The autoreload allows me to reload imported .py files when I evaluate a cell. Due to interaction between Jupyter NB and VS Code files I need to develop in both environments and want everything up to date in my notebook
The greedy IP completer allows me to list all options in python dictionaries and tab through them instead of looking up every option. Be careful though, as having too many big objects in a NB might slow down everything.
The pandas (pd) and seaborn (sns) options are simply a preference setup of mine. I do not want to have truncated rows within pandas dataframes often and also prefer a bigger figuresize within seaborn
The node interactivity “all” simply outputs all statements instead of the last one. This allows me to not always have to type “print” for my statements and can simply type variable names. Be aware that this also leads to different behavior for plotting figures.
The last one is jupyternotify. It is very helpful as some calculations need time (for example training a model, or optimizing hyperparameters). With this option, you can set a timer and notifies you when the calculation is done. Extremely helpful when you want to work on other parts during calculation.
There are various notebook extensions for jupyter NB. Here are the ones I use:
autopep8 for formatting code and making it more readable
hide input and collapsible headings for showing the results of the cells and not the code. And also focusing on certain parts in the notebook. Helpful for presentations
highlight selected word for showing me where I used the same variable I want to edit
code folding for more complex and longer functions in cells
table of contents for showing the headings of the notebook. Absolutely essential for navigating through the notebook and making it more readable.
execution time for knowing how long an execution took. Very useful in training and comparing ML models and parameter optimization.
finally, comment hotkey this is a must if you are using a different keyboard layout than the English one. I use a german keyboard within macOS and therefore the code comment key shortcut does not work. with jupyter NB you have the option to set a different hotkey. this is one big reason why I still do not use jupyter lab. Because there you still do not have this option and there is no way for commenting/uncommenting code parts apart from manually typing “#”. This is unbearable if you want proper efficient coding.
I do not use the “Hinterland” extension for code completion. I have used it in the past, but the performance is not good and it also slows down the whole notebook.
The same goes for “Variable Inspector”. As soon as you have a few more dataframes or models stored, it will slow down the notebook and make it unusable. It took me a while to figure out that those extensions are causing problems. Therefore I do not use it anymore and can recommend not using it if your notebooks are larger.
Currently, I only use Jupyter Lab for notebook organization. My repository is managed with VS Code but sometimes I need to rearrange notebooks. This can not be done within VS Code and is cumbersome with Jupyter NB. Either I want to check what steps I have done in similar notebooks or I want to copy certain cells. Also splitting notebooks is much easier within Juypter Lab, where you have
a nice overview of your notebooks,
open multiple notebooks within one tab
copy and drag multiple cells within a notebook
For everything that is not done in Jupyter NB I use VS Code. I am aware that VS Code supports .ipynb files with a “notebook style” approach. However, until now, it comes not close to the benefits of real Jupyter NB (see my list above) and is also extremely slow. The loading always takes so long that I am already annoyed by it.
But as soon as I leave the notebook environment I do everything in VS Code. I have been using it for many years and it is still the best option in my opinion.
Reasons for this are:
Syntax highlighting
Code completion and suggestions
Navigation through functions and files
Extensions and Integrations (eg Docker, linting, formatting, testing, snippets)
Git
Basically, everything that is needed when developing an app after the notebook proof of concept is great in VS Code.
If you are using another IDE (eg PyCharm) instead of VS Code it will also be sufficient I would say. If you have developed a certain workflow with an IDE and it works it doesn’t make too much sense to switch in my opinion. The reason I prefer VS Code is the lightweight and customizability. It is extremely intuitive and easy to get started with. You don’t need to create projects or whatever. Just add the extensions you need and start programming. You can add as much as you like or you can keep it super slim. It can also support many other languages which makes it great to use if you have bigger projects.
I am not associated with any of the services I use in this article.
I do not consider myself an expert. I am not a blogger or something. I merely document things besides doing other things. Therefore the content does not represent the quality of any of my work, nor does it fully reflect my view on things. If you have the feeling that I am missing important steps or neglected something, consider pointing it out in the comment section or get in touch with me.
I am always happy for constructive input and how to improve.
This was written on 16.03.2021. I cannot monitor all of my articles. There is a high probability that when you read this article the tips are outdated and the processes have changed.
If you need more information on certain parts, feel free to point it out in the comments.
Daniel is an artist, entrepreneur, software developer, and business law graduate. He has worked at various IT companies, tax advisory, management consulting, and at the Austrian court.
His knowledge and interests currently revolve around programming machine learning applications and all their related aspects. To the core, he considers himself a problem solver of complex environments, which is reflected in his various projects.
Don’t hesitate to get in touch if you have ideas, projects, or problems.
|
[
{
"code": null,
"e": 574,
"s": 172,
"text": "I have been working with various IDEs for my Python development over the last few years. Recently I asked myself if it would make sense to check if it is useful to update my current practice and see if alternatives offer better productivity. There is often the question if one IDE is better than the other. In this article, I want to show that the best way is to use the best tool for a specific task."
},
{
"code": null,
"e": 623,
"s": 574,
"text": "Jupyter Notebook or Lab or VS Code? Why not all?"
},
{
"code": null,
"e": 641,
"s": 623,
"text": "Table of Contents"
},
{
"code": null,
"e": 686,
"s": 641,
"text": "Why you don’t need to decide which is better"
},
{
"code": null,
"e": 707,
"s": 686,
"text": "Why Jupyter Notebook"
},
{
"code": null,
"e": 723,
"s": 707,
"text": "Why Jupyter Lab"
},
{
"code": null,
"e": 735,
"s": 723,
"text": "Why VS Code"
},
{
"code": null,
"e": 746,
"s": 735,
"text": "Disclaimer"
},
{
"code": null,
"e": 752,
"s": 746,
"text": "About"
},
{
"code": null,
"e": 778,
"s": 752,
"text": "Currently, I use a mix of"
},
{
"code": null,
"e": 795,
"s": 778,
"text": "Jupyter Notebook"
},
{
"code": null,
"e": 807,
"s": 795,
"text": "Jupyter Lab"
},
{
"code": null,
"e": 815,
"s": 807,
"text": "VS Code"
},
{
"code": null,
"e": 1197,
"s": 815,
"text": "I am always asking myself if Jupyter Lab is already so far developed that it can replace my Jupyter Notebook (NB) workflow. The short answer is no. There are still many advantages of NB over Lab, which I will elaborate on in the following. However, and this is important to understand, it doesn’t need to be replaced. You can easily use both of them for the tasks they are good at."
},
{
"code": null,
"e": 1214,
"s": 1197,
"text": "Therefore I use:"
},
{
"code": null,
"e": 1270,
"s": 1214,
"text": "NB for developing a Data Science Proof-of-concept (POC)"
},
{
"code": null,
"e": 1320,
"s": 1270,
"text": "Jupyter Lab for managing and re-arranging my POCs"
},
{
"code": null,
"e": 1373,
"s": 1320,
"text": "VS Code for everything that is not notebook-related."
},
{
"code": null,
"e": 1453,
"s": 1373,
"text": "In essence, I use all three tools to various degrees in a data science project."
},
{
"code": null,
"e": 1524,
"s": 1453,
"text": "I still use the NB for most of my POC work. Here are some reasons why:"
},
{
"code": null,
"e": 1667,
"s": 1524,
"text": "With jupyterthemes you can easily adapt the theme to your needs. I used a lot the “chesterish” theme (jt -t chesterish -T -N) which looks like"
},
{
"code": null,
"e": 1993,
"s": 1667,
"text": "You can specify a with various jupyterthemes flags. Currently, I use it with !jt -t chesterish -f fira -fs 10 -nf ptsans -nfs 11 -N -kl -cursw 2 -cursc r -cellw 95% -T ( you will find similar setups on other articles). Check the official website to see a full list of the flags and their meanings. This setup looks like this:"
},
{
"code": null,
"e": 2132,
"s": 1993,
"text": "I prefer the dark theme because I work quite a lot in front of the monitor and whatever helps to reduce strain on my eyes is very welcome."
},
{
"code": null,
"e": 2210,
"s": 2132,
"text": "I use some specific NB configurations which might be helpful for you as well."
},
{
"code": null,
"e": 2589,
"s": 2210,
"text": "%load_ext autoreload%autoreload 2%matplotlib inline%config IPCompleter.greedy = Truepd.options.display.max_columns = Nonepd.options.display.max_rows = 200sns.set_palette(\"bright\")sns.set(style=\"darkgrid\")sns.set(rc={'figure.figsize':(30,30)})InteractiveShell.ast_node_interactivity = \"all\"ip = get_ipython()ip.register_magics(jupyternotify.JupyterNotifyMagics)%autonotify -a 120"
},
{
"code": null,
"e": 2808,
"s": 2589,
"text": "The autoreload allows me to reload imported .py files when I evaluate a cell. Due to interaction between Jupyter NB and VS Code files I need to develop in both environments and want everything up to date in my notebook"
},
{
"code": null,
"e": 3028,
"s": 2808,
"text": "The greedy IP completer allows me to list all options in python dictionaries and tab through them instead of looking up every option. Be careful though, as having too many big objects in a NB might slow down everything."
},
{
"code": null,
"e": 3228,
"s": 3028,
"text": "The pandas (pd) and seaborn (sns) options are simply a preference setup of mine. I do not want to have truncated rows within pandas dataframes often and also prefer a bigger figuresize within seaborn"
},
{
"code": null,
"e": 3490,
"s": 3228,
"text": "The node interactivity “all” simply outputs all statements instead of the last one. This allows me to not always have to type “print” for my statements and can simply type variable names. Be aware that this also leads to different behavior for plotting figures."
},
{
"code": null,
"e": 3794,
"s": 3490,
"text": "The last one is jupyternotify. It is very helpful as some calculations need time (for example training a model, or optimizing hyperparameters). With this option, you can set a timer and notifies you when the calculation is done. Extremely helpful when you want to work on other parts during calculation."
},
{
"code": null,
"e": 3873,
"s": 3794,
"text": "There are various notebook extensions for jupyter NB. Here are the ones I use:"
},
{
"code": null,
"e": 3930,
"s": 3873,
"text": "autopep8 for formatting code and making it more readable"
},
{
"code": null,
"e": 4099,
"s": 3930,
"text": "hide input and collapsible headings for showing the results of the cells and not the code. And also focusing on certain parts in the notebook. Helpful for presentations"
},
{
"code": null,
"e": 4184,
"s": 4099,
"text": "highlight selected word for showing me where I used the same variable I want to edit"
},
{
"code": null,
"e": 4244,
"s": 4184,
"text": "code folding for more complex and longer functions in cells"
},
{
"code": null,
"e": 4390,
"s": 4244,
"text": "table of contents for showing the headings of the notebook. Absolutely essential for navigating through the notebook and making it more readable."
},
{
"code": null,
"e": 4521,
"s": 4390,
"text": "execution time for knowing how long an execution took. Very useful in training and comparing ML models and parameter optimization."
},
{
"code": null,
"e": 5040,
"s": 4521,
"text": "finally, comment hotkey this is a must if you are using a different keyboard layout than the English one. I use a german keyboard within macOS and therefore the code comment key shortcut does not work. with jupyter NB you have the option to set a different hotkey. this is one big reason why I still do not use jupyter lab. Because there you still do not have this option and there is no way for commenting/uncommenting code parts apart from manually typing “#”. This is unbearable if you want proper efficient coding."
},
{
"code": null,
"e": 5204,
"s": 5040,
"text": "I do not use the “Hinterland” extension for code completion. I have used it in the past, but the performance is not good and it also slows down the whole notebook."
},
{
"code": null,
"e": 5529,
"s": 5204,
"text": "The same goes for “Variable Inspector”. As soon as you have a few more dataframes or models stored, it will slow down the notebook and make it unusable. It took me a while to figure out that those extensions are causing problems. Therefore I do not use it anymore and can recommend not using it if your notebooks are larger."
},
{
"code": null,
"e": 5919,
"s": 5529,
"text": "Currently, I only use Jupyter Lab for notebook organization. My repository is managed with VS Code but sometimes I need to rearrange notebooks. This can not be done within VS Code and is cumbersome with Jupyter NB. Either I want to check what steps I have done in similar notebooks or I want to copy certain cells. Also splitting notebooks is much easier within Juypter Lab, where you have"
},
{
"code": null,
"e": 5954,
"s": 5919,
"text": "a nice overview of your notebooks,"
},
{
"code": null,
"e": 5993,
"s": 5954,
"text": "open multiple notebooks within one tab"
},
{
"code": null,
"e": 6040,
"s": 5993,
"text": "copy and drag multiple cells within a notebook"
},
{
"code": null,
"e": 6369,
"s": 6040,
"text": "For everything that is not done in Jupyter NB I use VS Code. I am aware that VS Code supports .ipynb files with a “notebook style” approach. However, until now, it comes not close to the benefits of real Jupyter NB (see my list above) and is also extremely slow. The loading always takes so long that I am already annoyed by it."
},
{
"code": null,
"e": 6528,
"s": 6369,
"text": "But as soon as I leave the notebook environment I do everything in VS Code. I have been using it for many years and it is still the best option in my opinion."
},
{
"code": null,
"e": 6550,
"s": 6528,
"text": "Reasons for this are:"
},
{
"code": null,
"e": 6570,
"s": 6550,
"text": "Syntax highlighting"
},
{
"code": null,
"e": 6602,
"s": 6570,
"text": "Code completion and suggestions"
},
{
"code": null,
"e": 6641,
"s": 6602,
"text": "Navigation through functions and files"
},
{
"code": null,
"e": 6721,
"s": 6641,
"text": "Extensions and Integrations (eg Docker, linting, formatting, testing, snippets)"
},
{
"code": null,
"e": 6725,
"s": 6721,
"text": "Git"
},
{
"code": null,
"e": 6842,
"s": 6725,
"text": "Basically, everything that is needed when developing an app after the notebook proof of concept is great in VS Code."
},
{
"code": null,
"e": 7453,
"s": 6842,
"text": "If you are using another IDE (eg PyCharm) instead of VS Code it will also be sufficient I would say. If you have developed a certain workflow with an IDE and it works it doesn’t make too much sense to switch in my opinion. The reason I prefer VS Code is the lightweight and customizability. It is extremely intuitive and easy to get started with. You don’t need to create projects or whatever. Just add the extensions you need and start programming. You can add as much as you like or you can keep it super slim. It can also support many other languages which makes it great to use if you have bigger projects."
},
{
"code": null,
"e": 7521,
"s": 7453,
"text": "I am not associated with any of the services I use in this article."
},
{
"code": null,
"e": 7915,
"s": 7521,
"text": "I do not consider myself an expert. I am not a blogger or something. I merely document things besides doing other things. Therefore the content does not represent the quality of any of my work, nor does it fully reflect my view on things. If you have the feeling that I am missing important steps or neglected something, consider pointing it out in the comment section or get in touch with me."
},
{
"code": null,
"e": 7976,
"s": 7915,
"text": "I am always happy for constructive input and how to improve."
},
{
"code": null,
"e": 8159,
"s": 7976,
"text": "This was written on 16.03.2021. I cannot monitor all of my articles. There is a high probability that when you read this article the tips are outdated and the processes have changed."
},
{
"code": null,
"e": 8249,
"s": 8159,
"text": "If you need more information on certain parts, feel free to point it out in the comments."
},
{
"code": null,
"e": 8434,
"s": 8249,
"text": "Daniel is an artist, entrepreneur, software developer, and business law graduate. He has worked at various IT companies, tax advisory, management consulting, and at the Austrian court."
},
{
"code": null,
"e": 8680,
"s": 8434,
"text": "His knowledge and interests currently revolve around programming machine learning applications and all their related aspects. To the core, he considers himself a problem solver of complex environments, which is reflected in his various projects."
}
] |
Check whether String is an interface or class in Java
|
The method java.lang.Class.isInterface() is used to find if String is an interface or class in Java. This method returns true if String is an interface, otherwise it returns false.
A program that demonstrates this is given as follows −
Live Demo
package Test;
import java.lang.*;
public class Demo {
public static void main(String[] args) {
Class c = String.class;
boolean interfaceFlag = c.isInterface();
System.out.println("This is an Interface? " + interfaceFlag);
}
}
This is an Interface? false
Now let us understand the above program.
The isInterface() method is used to find if String is an interface or not. The result is stored in interfaceFlag and then displayed. A code snippet which demonstrates this is as follows −
Class c = String.class;
boolean interfaceFlag = c.isInterface();
System.out.println("This is an Interface? " + interfaceFlag);
|
[
{
"code": null,
"e": 1243,
"s": 1062,
"text": "The method java.lang.Class.isInterface() is used to find if String is an interface or class in Java. This method returns true if String is an interface, otherwise it returns false."
},
{
"code": null,
"e": 1298,
"s": 1243,
"text": "A program that demonstrates this is given as follows −"
},
{
"code": null,
"e": 1309,
"s": 1298,
"text": " Live Demo"
},
{
"code": null,
"e": 1559,
"s": 1309,
"text": "package Test;\nimport java.lang.*;\npublic class Demo {\n public static void main(String[] args) {\n Class c = String.class;\n boolean interfaceFlag = c.isInterface();\n System.out.println(\"This is an Interface? \" + interfaceFlag);\n }\n}"
},
{
"code": null,
"e": 1587,
"s": 1559,
"text": "This is an Interface? false"
},
{
"code": null,
"e": 1628,
"s": 1587,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 1816,
"s": 1628,
"text": "The isInterface() method is used to find if String is an interface or not. The result is stored in interfaceFlag and then displayed. A code snippet which demonstrates this is as follows −"
},
{
"code": null,
"e": 1945,
"s": 1816,
"text": "Class c = String.class;\nboolean interfaceFlag = c.isInterface();\nSystem.out.println(\"This is an Interface? \" + interfaceFlag); "
}
] |
What permission do I need to access Internet from an Android application?
|
<uses-permission android:name="android.permission.INTERNET"/>
This example demonstrates how do I open google from android app using Internet permission.
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:orientation="vertical"
android:padding="2dp"
tools:context=".MainActivity">
<WebView
android:id="@+id/webView"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</WebView>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity {
WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
webView.loadUrl("http://www.google.com");
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
|
[
{
"code": null,
"e": 1124,
"s": 1062,
"text": "<uses-permission android:name=\"android.permission.INTERNET\"/>"
},
{
"code": null,
"e": 1215,
"s": 1124,
"text": "This example demonstrates how do I open google from android app using Internet permission."
},
{
"code": null,
"e": 1344,
"s": 1215,
"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": 1409,
"s": 1344,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1907,
"s": 1409,
"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:orientation=\"vertical\"\n android:padding=\"2dp\"\n tools:context=\".MainActivity\">\n <WebView\n android:id=\"@+id/webView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\">\n </WebView>\n</RelativeLayout>"
},
{
"code": null,
"e": 1964,
"s": 1907,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2400,
"s": 1964,
"text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.webkit.WebView;\npublic class MainActivity extends AppCompatActivity {\n WebView webView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n webView = findViewById(R.id.webView);\n webView.loadUrl(\"http://www.google.com\");\n }\n}"
},
{
"code": null,
"e": 2455,
"s": 2400,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3190,
"s": 2455,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.INTERNET\"/>\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": 3537,
"s": 3190,
"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": 3578,
"s": 3537,
"text": "Click here to download the project code."
}
] |
ML | Fowlkes-Mallows Score - GeeksforGeeks
|
28 Nov, 2019
The Fowlkes-Mallows Score is an evaluation metric to evaluate the similarity among clusterings obtained after applying different clustering algorithms. Although technically it is used to quantify the similarity between two clusterings, it is typically used to evaluate the clustering performance of a clustering algorithm by assuming the second clustering to be the ground-truth ie the observed data and assuming it to be the perfect clustering.
Let there be N number of data points in the data and k number of clusters in clusterings A1 and A2. Then the matrix M is built such that
where determines the number of data points that lie in the ith cluster in clustering A1 and the jth cluster in clustering A2.
The Fowlkes-Mallows index for the parameter k is given by
where
The following terms are defined in the context of the above-defined symbolic conventions:-
True Positive(TP): The number of pair of data points which are in the same cluster in A1 and in A2.False Positive(FP): The number of pair of data points which are in the same cluster in A1 but not in A2.False Negative(FN): The number of pair of data points which are not in the same cluster in A1 but are in the same cluster in A2.True Negative(TN): The number of pair of data points which are not in the same cluster in neither A1 nor A2.
True Positive(TP): The number of pair of data points which are in the same cluster in A1 and in A2.
False Positive(FP): The number of pair of data points which are in the same cluster in A1 but not in A2.
False Negative(FN): The number of pair of data points which are not in the same cluster in A1 but are in the same cluster in A2.
True Negative(TN): The number of pair of data points which are not in the same cluster in neither A1 nor A2.
Obviously
Thus the Fowlkes-Mallows Index can also be expressed as:-
Rewritting the above expression
Thus the Fowlkes-Mallows Index is the geometric mean of the precision and the recall.
Properties:
Assumption-Less: This evaluation metric does not assume any property about the cluster structure thus proving to be significantly advantageous than traditional evaluation methods.
Ground-Truth Rules: One disadvantage to this evaluation metric is that it requires the knowledge of the ground-truth rules(Class Labels) to evaluate a clustering algorithm.
The below steps will demonstrate how to evaluate the Fowlkes-Mallows Index for a clustering algorithm by using Sklearn. The dataset for the below steps is the Credit Card Fraud Detection dataset which can be downloaded from Kaggle.
Step 1: Importing the required libraries
import pandas as pdimport matplotlib.pyplot as pltfrom sklearn.cluster import KMeansfrom sklearn.metrics import fowlkes_mallows
Step 2: Loading and Cleaning the data
#Changing the working location to the location of the filecd C:\Users\Dev\Desktop\Kaggle\Credit Card Fraud #Loading the datadf = pd.read_csv('creditcard.csv') #Separating the dependent and independent variablesy = df['Class']X = df.drop('Class',axis=1) X.head()
Step 3: Building different Clustering and evaluating individual performances
The following step lines of code involve Building different K-Means Clustering models each having different values for the parameter n_clusters and then evaluating each individual performance using the Fowlkes-Mallows Score.
#List of Fowlkes-Mallows Scores for different modelsfms_scores = [] #List of different number of clustersN_Clusters = [2,3,4,5,6]
a) n_clusters = 2
#Building the clustering modelkmeans2 = KMeans(n_clusters=2) #Training the clustering modelkmeans2.fit(X) #Storing the predicted Clustering labelslabels2 = kmeans2.predict(X) #Evaluating the performancefms_scores.append(fms(y,labels2))
b) n_clusters = 3
#Building the clustering modelkmeans3 = KMeans(n_clusters=3) #Training the clustering modelkmeans3.fit(X) #Storing the predicted Clustering labelslabels3 = kmeans3.predict(X) #Evaluating the performancefms_scores.append(fms(y,labels3))
c) n_clusters = 4
#Building the clustering modelkmeans4 = KMeans(n_clusters=4) #Training the clustering modelkmeans4.fit(X) #Storing the predicted Clustering labelslabels4 = kmeans4.predict(X) #Evaluating the performancefms_scores.append(fms(y,labels4))
d) n_clusters = 5
#Building the clustering modelkmeans5 = KMeans(n_clusters=5) #Training the clustering modelkmeans5.fit(X) #Storing the predicted Clustering labelslabels5 = kmeans5.predict(X) #Evaluating the performancefms_scores.append(fms(y,labels5))
e) n_clusters = 6
#Building the clustering modelkmeans6 = KMeans(n_clusters=6) #Training the clustering modelkmeans6.fit(X) #Storing the predicted Clustering labelslabels6 = kmeans6.predict(X) #Evaluating the performancefms_scores.append(fms(y,labels6))
print(fms_scores)
Step 4: Visualizing and Comparing the results
#Plotting a Bar Graph to compare the modelsplt.bar(N_Clusters,fms_scores)plt.xlabel('Number of Clusters')plt.ylabel('Fowlkes Mallows Score')plt.title('Comparison of different Clustering Models')plt.show()
Thus, quite obviously, the clustering with the number of clusters = 2 is the most similar to the observed data because the data has only two class labels.
shubham_singh
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ML | Linear Regression
Python | Decision tree implementation
Difference between Informed and Uninformed Search in AI
Search Algorithms in AI
Decision Tree Introduction with example
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 24005,
"s": 23977,
"text": "\n28 Nov, 2019"
},
{
"code": null,
"e": 24451,
"s": 24005,
"text": "The Fowlkes-Mallows Score is an evaluation metric to evaluate the similarity among clusterings obtained after applying different clustering algorithms. Although technically it is used to quantify the similarity between two clusterings, it is typically used to evaluate the clustering performance of a clustering algorithm by assuming the second clustering to be the ground-truth ie the observed data and assuming it to be the perfect clustering."
},
{
"code": null,
"e": 24588,
"s": 24451,
"text": "Let there be N number of data points in the data and k number of clusters in clusterings A1 and A2. Then the matrix M is built such that"
},
{
"code": null,
"e": 24715,
"s": 24588,
"text": "where determines the number of data points that lie in the ith cluster in clustering A1 and the jth cluster in clustering A2."
},
{
"code": null,
"e": 24773,
"s": 24715,
"text": "The Fowlkes-Mallows index for the parameter k is given by"
},
{
"code": null,
"e": 24779,
"s": 24773,
"text": "where"
},
{
"code": null,
"e": 24870,
"s": 24779,
"text": "The following terms are defined in the context of the above-defined symbolic conventions:-"
},
{
"code": null,
"e": 25310,
"s": 24870,
"text": "True Positive(TP): The number of pair of data points which are in the same cluster in A1 and in A2.False Positive(FP): The number of pair of data points which are in the same cluster in A1 but not in A2.False Negative(FN): The number of pair of data points which are not in the same cluster in A1 but are in the same cluster in A2.True Negative(TN): The number of pair of data points which are not in the same cluster in neither A1 nor A2."
},
{
"code": null,
"e": 25410,
"s": 25310,
"text": "True Positive(TP): The number of pair of data points which are in the same cluster in A1 and in A2."
},
{
"code": null,
"e": 25515,
"s": 25410,
"text": "False Positive(FP): The number of pair of data points which are in the same cluster in A1 but not in A2."
},
{
"code": null,
"e": 25644,
"s": 25515,
"text": "False Negative(FN): The number of pair of data points which are not in the same cluster in A1 but are in the same cluster in A2."
},
{
"code": null,
"e": 25753,
"s": 25644,
"text": "True Negative(TN): The number of pair of data points which are not in the same cluster in neither A1 nor A2."
},
{
"code": null,
"e": 25763,
"s": 25753,
"text": "Obviously"
},
{
"code": null,
"e": 25821,
"s": 25763,
"text": "Thus the Fowlkes-Mallows Index can also be expressed as:-"
},
{
"code": null,
"e": 25853,
"s": 25821,
"text": "Rewritting the above expression"
},
{
"code": null,
"e": 25939,
"s": 25853,
"text": "Thus the Fowlkes-Mallows Index is the geometric mean of the precision and the recall."
},
{
"code": null,
"e": 25951,
"s": 25939,
"text": "Properties:"
},
{
"code": null,
"e": 26131,
"s": 25951,
"text": "Assumption-Less: This evaluation metric does not assume any property about the cluster structure thus proving to be significantly advantageous than traditional evaluation methods."
},
{
"code": null,
"e": 26304,
"s": 26131,
"text": "Ground-Truth Rules: One disadvantage to this evaluation metric is that it requires the knowledge of the ground-truth rules(Class Labels) to evaluate a clustering algorithm."
},
{
"code": null,
"e": 26536,
"s": 26304,
"text": "The below steps will demonstrate how to evaluate the Fowlkes-Mallows Index for a clustering algorithm by using Sklearn. The dataset for the below steps is the Credit Card Fraud Detection dataset which can be downloaded from Kaggle."
},
{
"code": null,
"e": 26577,
"s": 26536,
"text": "Step 1: Importing the required libraries"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as pltfrom sklearn.cluster import KMeansfrom sklearn.metrics import fowlkes_mallows",
"e": 26705,
"s": 26577,
"text": null
},
{
"code": null,
"e": 26743,
"s": 26705,
"text": "Step 2: Loading and Cleaning the data"
},
{
"code": "#Changing the working location to the location of the filecd C:\\Users\\Dev\\Desktop\\Kaggle\\Credit Card Fraud #Loading the datadf = pd.read_csv('creditcard.csv') #Separating the dependent and independent variablesy = df['Class']X = df.drop('Class',axis=1) X.head()",
"e": 27008,
"s": 26743,
"text": null
},
{
"code": null,
"e": 27085,
"s": 27008,
"text": "Step 3: Building different Clustering and evaluating individual performances"
},
{
"code": null,
"e": 27310,
"s": 27085,
"text": "The following step lines of code involve Building different K-Means Clustering models each having different values for the parameter n_clusters and then evaluating each individual performance using the Fowlkes-Mallows Score."
},
{
"code": "#List of Fowlkes-Mallows Scores for different modelsfms_scores = [] #List of different number of clustersN_Clusters = [2,3,4,5,6]",
"e": 27441,
"s": 27310,
"text": null
},
{
"code": null,
"e": 27459,
"s": 27441,
"text": "a) n_clusters = 2"
},
{
"code": "#Building the clustering modelkmeans2 = KMeans(n_clusters=2) #Training the clustering modelkmeans2.fit(X) #Storing the predicted Clustering labelslabels2 = kmeans2.predict(X) #Evaluating the performancefms_scores.append(fms(y,labels2))",
"e": 27698,
"s": 27459,
"text": null
},
{
"code": null,
"e": 27716,
"s": 27698,
"text": "b) n_clusters = 3"
},
{
"code": "#Building the clustering modelkmeans3 = KMeans(n_clusters=3) #Training the clustering modelkmeans3.fit(X) #Storing the predicted Clustering labelslabels3 = kmeans3.predict(X) #Evaluating the performancefms_scores.append(fms(y,labels3))",
"e": 27955,
"s": 27716,
"text": null
},
{
"code": null,
"e": 27973,
"s": 27955,
"text": "c) n_clusters = 4"
},
{
"code": "#Building the clustering modelkmeans4 = KMeans(n_clusters=4) #Training the clustering modelkmeans4.fit(X) #Storing the predicted Clustering labelslabels4 = kmeans4.predict(X) #Evaluating the performancefms_scores.append(fms(y,labels4))",
"e": 28212,
"s": 27973,
"text": null
},
{
"code": null,
"e": 28230,
"s": 28212,
"text": "d) n_clusters = 5"
},
{
"code": "#Building the clustering modelkmeans5 = KMeans(n_clusters=5) #Training the clustering modelkmeans5.fit(X) #Storing the predicted Clustering labelslabels5 = kmeans5.predict(X) #Evaluating the performancefms_scores.append(fms(y,labels5))",
"e": 28469,
"s": 28230,
"text": null
},
{
"code": null,
"e": 28487,
"s": 28469,
"text": "e) n_clusters = 6"
},
{
"code": "#Building the clustering modelkmeans6 = KMeans(n_clusters=6) #Training the clustering modelkmeans6.fit(X) #Storing the predicted Clustering labelslabels6 = kmeans6.predict(X) #Evaluating the performancefms_scores.append(fms(y,labels6))",
"e": 28726,
"s": 28487,
"text": null
},
{
"code": "print(fms_scores)",
"e": 28744,
"s": 28726,
"text": null
},
{
"code": null,
"e": 28790,
"s": 28744,
"text": "Step 4: Visualizing and Comparing the results"
},
{
"code": "#Plotting a Bar Graph to compare the modelsplt.bar(N_Clusters,fms_scores)plt.xlabel('Number of Clusters')plt.ylabel('Fowlkes Mallows Score')plt.title('Comparison of different Clustering Models')plt.show()",
"e": 28995,
"s": 28790,
"text": null
},
{
"code": null,
"e": 29150,
"s": 28995,
"text": "Thus, quite obviously, the clustering with the number of clusters = 2 is the most similar to the observed data because the data has only two class labels."
},
{
"code": null,
"e": 29164,
"s": 29150,
"text": "shubham_singh"
},
{
"code": null,
"e": 29181,
"s": 29164,
"text": "Machine Learning"
},
{
"code": null,
"e": 29188,
"s": 29181,
"text": "Python"
},
{
"code": null,
"e": 29205,
"s": 29188,
"text": "Machine Learning"
},
{
"code": null,
"e": 29303,
"s": 29205,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29312,
"s": 29303,
"text": "Comments"
},
{
"code": null,
"e": 29325,
"s": 29312,
"text": "Old Comments"
},
{
"code": null,
"e": 29348,
"s": 29325,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 29386,
"s": 29348,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 29442,
"s": 29386,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 29466,
"s": 29442,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 29506,
"s": 29466,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 29534,
"s": 29506,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 29584,
"s": 29534,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 29606,
"s": 29584,
"text": "Python map() function"
}
] |
Pattern Printing | Practice | GeeksforGeeks
|
Given a number N. The task is to print a series of asterisk(*) from 1 till N terms with increasing order and difference being 1.
Example 1:
Input:
N = 3
Output:
* ** ***
Explanation:
First, print 1 asterisk then space after
that print 2 asterisk and space after that
print 3 asterisk now stop as N is 3.
Example 2:
Input:
N = 5
Output:
* ** *** **** *****
Explanation:
First, print 1 asterisk then space after
that print 2 asterisk and space and do this
3 more times.
Your Task:
You don't need to read input. Your task is to complete the function printPattern() which takes an integer N as an input parameter and print the above pattern.
Expected Time Complexity: O(N^2)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 1000
0
dalalrinku88901 month ago
class Solution{public: void printPattern(int N) { for(int i=1;i<=N;i++) { for(int j=1;j<=i;j++) { cout<<"*"; }cout<<" "; } }};
0
amiransarimy3 months ago
Python One Line Solutions
class Solution:
def printPattern(self, N):
for i in range(1,N+1):
print("*"*i,end =' ')
0
sonalipatro3 months ago
class Solution{ static void printPattern(int N){ // code here int i=1; while(i<=N){ for(int j=0;j<i;j++){ System.out.print("*"); } System.out.print(" ");i++; } }}
0
ankit2030singh3 months ago
**************Python Code*******************
write this in Solution class
def printPattern(self, N): for i in range(1, N+1): for j in range(i): print('*', end = '') if(i<N): print(' ', end = '')
0
pankajkumarravi6 months ago
******************* java Logic **************
static void printPattern(int N){ // code here for (int i=0;i<N;i++) { for (int j = 0; j <= i; j++) { System.out.print("*" ); } System.out.print(" "); } }
0
cshubham4397 months ago
for(int i = 0; i<N; i++){ for(int j = 0; j<=i; j++){ System.out.print("*"); } System.out.print(" "); }
0
Yash Kadulkar1 year ago
Yash Kadulkar
Using for loop:for i in range(1,N+1): print('*'*i,end=' ')
Using while loop: L = 1 while L<=N: print('*'*L,end=' ') L += 1
0
Shreyansh Kumar Singh1 year ago
Shreyansh Kumar Singh
For Java it's only working when we add a new line at the end of function.Please fix this..!!
0
jay agrawal1 year ago
jay agrawal
class Solution{ static void printPattern(int N){ // code here for (int i=1;i<=N;i++){ for (int j=1;j<=i;j++){ System.out.print("*"); } System.out.print(" "); } }}My code is not working at N=84,don't know why
0
Vishal Sharma1 year ago
Vishal Sharma
int i,j; for(i=0; i<n; i++){="" for(j="0;" j<i+1;="" j++){="" cout<<"*";="" }="" cout<<"="" ";="" }="" cout<<"\n";="" }="">
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": 355,
"s": 226,
"text": "Given a number N. The task is to print a series of asterisk(*) from 1 till N terms with increasing order and difference being 1."
},
{
"code": null,
"e": 366,
"s": 355,
"text": "Example 1:"
},
{
"code": null,
"e": 532,
"s": 366,
"text": "Input:\nN = 3\nOutput:\n* ** ***\nExplanation:\nFirst, print 1 asterisk then space after\nthat print 2 asterisk and space after that \nprint 3 asterisk now stop as N is 3.\n"
},
{
"code": null,
"e": 543,
"s": 532,
"text": "Example 2:"
},
{
"code": null,
"e": 697,
"s": 543,
"text": "Input:\nN = 5\nOutput:\n* ** *** **** ***** \nExplanation:\nFirst, print 1 asterisk then space after\nthat print 2 asterisk and space and do this\n3 more times."
},
{
"code": null,
"e": 869,
"s": 697,
"text": "Your Task: \nYou don't need to read input. Your task is to complete the function printPattern() which takes an integer N as an input parameter and print the above pattern."
},
{
"code": null,
"e": 933,
"s": 869,
"text": "Expected Time Complexity: O(N^2)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 961,
"s": 933,
"text": "Constraints:\n1 <= N <= 1000"
},
{
"code": null,
"e": 963,
"s": 961,
"text": "0"
},
{
"code": null,
"e": 989,
"s": 963,
"text": "dalalrinku88901 month ago"
},
{
"code": null,
"e": 1167,
"s": 989,
"text": "class Solution{public: void printPattern(int N) { for(int i=1;i<=N;i++) { for(int j=1;j<=i;j++) { cout<<\"*\"; }cout<<\" \"; } }}; "
},
{
"code": null,
"e": 1169,
"s": 1167,
"text": "0"
},
{
"code": null,
"e": 1194,
"s": 1169,
"text": "amiransarimy3 months ago"
},
{
"code": null,
"e": 1220,
"s": 1194,
"text": "Python One Line Solutions"
},
{
"code": null,
"e": 1331,
"s": 1222,
"text": "class Solution:\n def printPattern(self, N):\n for i in range(1,N+1):\n print(\"*\"*i,end =' ')"
},
{
"code": null,
"e": 1333,
"s": 1331,
"text": "0"
},
{
"code": null,
"e": 1357,
"s": 1333,
"text": "sonalipatro3 months ago"
},
{
"code": null,
"e": 1592,
"s": 1357,
"text": "class Solution{ static void printPattern(int N){ // code here int i=1; while(i<=N){ for(int j=0;j<i;j++){ System.out.print(\"*\"); } System.out.print(\" \");i++; } }}"
},
{
"code": null,
"e": 1594,
"s": 1592,
"text": "0"
},
{
"code": null,
"e": 1621,
"s": 1594,
"text": "ankit2030singh3 months ago"
},
{
"code": null,
"e": 1666,
"s": 1621,
"text": "**************Python Code*******************"
},
{
"code": null,
"e": 1695,
"s": 1666,
"text": "write this in Solution class"
},
{
"code": null,
"e": 1855,
"s": 1695,
"text": "def printPattern(self, N): for i in range(1, N+1): for j in range(i): print('*', end = '') if(i<N): print(' ', end = '')"
},
{
"code": null,
"e": 1857,
"s": 1855,
"text": "0"
},
{
"code": null,
"e": 1885,
"s": 1857,
"text": "pankajkumarravi6 months ago"
},
{
"code": null,
"e": 1931,
"s": 1885,
"text": "******************* java Logic **************"
},
{
"code": null,
"e": 2153,
"s": 1931,
"text": " static void printPattern(int N){ // code here for (int i=0;i<N;i++) { for (int j = 0; j <= i; j++) { System.out.print(\"*\" ); } System.out.print(\" \"); } }"
},
{
"code": null,
"e": 2155,
"s": 2153,
"text": "0"
},
{
"code": null,
"e": 2179,
"s": 2155,
"text": "cshubham4397 months ago"
},
{
"code": null,
"e": 2333,
"s": 2179,
"text": " for(int i = 0; i<N; i++){ for(int j = 0; j<=i; j++){ System.out.print(\"*\"); } System.out.print(\" \"); }"
},
{
"code": null,
"e": 2335,
"s": 2333,
"text": "0"
},
{
"code": null,
"e": 2359,
"s": 2335,
"text": "Yash Kadulkar1 year ago"
},
{
"code": null,
"e": 2373,
"s": 2359,
"text": "Yash Kadulkar"
},
{
"code": null,
"e": 2439,
"s": 2373,
"text": "Using for loop:for i in range(1,N+1): print('*'*i,end=' ')"
},
{
"code": null,
"e": 2535,
"s": 2439,
"text": "Using while loop: L = 1 while L<=N: print('*'*L,end=' ') L += 1"
},
{
"code": null,
"e": 2537,
"s": 2535,
"text": "0"
},
{
"code": null,
"e": 2569,
"s": 2537,
"text": "Shreyansh Kumar Singh1 year ago"
},
{
"code": null,
"e": 2591,
"s": 2569,
"text": "Shreyansh Kumar Singh"
},
{
"code": null,
"e": 2684,
"s": 2591,
"text": "For Java it's only working when we add a new line at the end of function.Please fix this..!!"
},
{
"code": null,
"e": 2686,
"s": 2684,
"text": "0"
},
{
"code": null,
"e": 2708,
"s": 2686,
"text": "jay agrawal1 year ago"
},
{
"code": null,
"e": 2720,
"s": 2708,
"text": "jay agrawal"
},
{
"code": null,
"e": 3003,
"s": 2720,
"text": "class Solution{ static void printPattern(int N){ // code here for (int i=1;i<=N;i++){ for (int j=1;j<=i;j++){ System.out.print(\"*\"); } System.out.print(\" \"); } }}My code is not working at N=84,don't know why"
},
{
"code": null,
"e": 3005,
"s": 3003,
"text": "0"
},
{
"code": null,
"e": 3029,
"s": 3005,
"text": "Vishal Sharma1 year ago"
},
{
"code": null,
"e": 3043,
"s": 3029,
"text": "Vishal Sharma"
},
{
"code": null,
"e": 3174,
"s": 3043,
"text": "int i,j; for(i=0; i<n; i++){=\"\" for(j=\"0;\" j<i+1;=\"\" j++){=\"\" cout<<\"*\";=\"\" }=\"\" cout<<\"=\"\" \";=\"\" }=\"\" cout<<\"\\n\";=\"\" }=\"\">"
},
{
"code": null,
"e": 3320,
"s": 3174,
"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": 3356,
"s": 3320,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3366,
"s": 3356,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3376,
"s": 3366,
"text": "\nContest\n"
},
{
"code": null,
"e": 3439,
"s": 3376,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3587,
"s": 3439,
"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": 3795,
"s": 3587,
"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": 3901,
"s": 3795,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
LESS - Mixins
|
Mixins are similar to functions in programming languages. Mixins are a group of CSS properties that allow you to use properties of one class for another class and includes class name as its properties. In LESS, you can declare a mixin in the same way as CSS style using class or id selector. It can store multiple values and can be reused in the code whenever necessary.
The following table demonstrates the use of LESS mixins in detail.
Mixins can be made to disappear in the output by simply placing the parentheses after it.
The mixins can contain not just properties, but they can contain selectors too.
Namespaces are used to group the mixins under a common name.
When guard is applied to namespace, mixins defined by it are used only when the guard condition returns true.
The !important keyword is used to override the particular property.
The following example demonstrates the use of mixins in the LESS file −
<html>
<head>
<link rel = "stylesheet" href = "style.css" type = "text/css" />
<title>LESS Mixins</title>
</head>
<body>
<h1>Welcome to Tutorialspoint</h1>
<p class = "p1">LESS is a CSS pre-processor that enables customizable,
manageable and reusable style sheet for web site.</p>
<p class = "p2">LESS is a dynamic style sheet language that extends the capability of CSS.</p>
<p class = "p3">LESS is cross browser friendly.</p>
</body>
</html>
Next, create the style.less file.
.p1 {
color:red;
}
.p2 {
background : #64d9c0;
.p1();
}
.p3 {
background : #LESS520;
.p1;
}
You can compile the style.less to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
.p1 {
color: red;
}
.p2 {
background: #64d9c0;
color: red;
}
.p3 {
background: #LESS520;
color: red;
}
Follow these steps to see how the above code works −
Save the above html code in the less_mixins.html file.
Save the above html code in the less_mixins.html file.
Open this HTML file in a browser, the following output will get displayed.
Open this HTML file in a browser, the following output will get displayed.
The parentheses are optional when calling mixins. In the above example, both statements .p1(); and .p1; do the same thing.
20 Lectures
1 hours
Anadi Sharma
44 Lectures
7.5 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Zach Miller
23 Lectures
1.5 hours
Zach Miller
34 Lectures
4 hours
Syed Raza
31 Lectures
3 hours
Harshit Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2921,
"s": 2550,
"text": "Mixins are similar to functions in programming languages. Mixins are a group of CSS properties that allow you to use properties of one class for another class and includes class name as its properties. In LESS, you can declare a mixin in the same way as CSS style using class or id selector. It can store multiple values and can be reused in the code whenever necessary."
},
{
"code": null,
"e": 2988,
"s": 2921,
"text": "The following table demonstrates the use of LESS mixins in detail."
},
{
"code": null,
"e": 3078,
"s": 2988,
"text": "Mixins can be made to disappear in the output by simply placing the parentheses after it."
},
{
"code": null,
"e": 3158,
"s": 3078,
"text": "The mixins can contain not just properties, but they can contain selectors too."
},
{
"code": null,
"e": 3219,
"s": 3158,
"text": "Namespaces are used to group the mixins under a common name."
},
{
"code": null,
"e": 3329,
"s": 3219,
"text": "When guard is applied to namespace, mixins defined by it are used only when the guard condition returns true."
},
{
"code": null,
"e": 3397,
"s": 3329,
"text": "The !important keyword is used to override the particular property."
},
{
"code": null,
"e": 3469,
"s": 3397,
"text": "The following example demonstrates the use of mixins in the LESS file −"
},
{
"code": null,
"e": 3969,
"s": 3469,
"text": "<html>\n <head>\n <link rel = \"stylesheet\" href = \"style.css\" type = \"text/css\" />\n <title>LESS Mixins</title>\n </head>\n\n <body>\n <h1>Welcome to Tutorialspoint</h1>\n <p class = \"p1\">LESS is a CSS pre-processor that enables customizable, \n manageable and reusable style sheet for web site.</p>\n <p class = \"p2\">LESS is a dynamic style sheet language that extends the capability of CSS.</p>\n <p class = \"p3\">LESS is cross browser friendly.</p>\n </body>\n</html>"
},
{
"code": null,
"e": 4003,
"s": 3969,
"text": "Next, create the style.less file."
},
{
"code": null,
"e": 4111,
"s": 4003,
"text": ".p1 {\n color:red;\n}\n\n.p2 {\n background : #64d9c0;\n .p1();\n}\n\n.p3 {\n background : #LESS520;\n .p1;\n}"
},
{
"code": null,
"e": 4188,
"s": 4111,
"text": "You can compile the style.less to style.css by using the following command −"
},
{
"code": null,
"e": 4216,
"s": 4188,
"text": "lessc style.less style.css\n"
},
{
"code": null,
"e": 4317,
"s": 4216,
"text": "Execute the above command; it will create the style.css file automatically with the following code −"
},
{
"code": null,
"e": 4437,
"s": 4317,
"text": ".p1 {\n color: red;\n}\n\n.p2 {\n background: #64d9c0;\n color: red;\n}\n\n.p3 {\n background: #LESS520;\n color: red;\n}"
},
{
"code": null,
"e": 4490,
"s": 4437,
"text": "Follow these steps to see how the above code works −"
},
{
"code": null,
"e": 4545,
"s": 4490,
"text": "Save the above html code in the less_mixins.html file."
},
{
"code": null,
"e": 4600,
"s": 4545,
"text": "Save the above html code in the less_mixins.html file."
},
{
"code": null,
"e": 4675,
"s": 4600,
"text": "Open this HTML file in a browser, the following output will get displayed."
},
{
"code": null,
"e": 4750,
"s": 4675,
"text": "Open this HTML file in a browser, the following output will get displayed."
},
{
"code": null,
"e": 4873,
"s": 4750,
"text": "The parentheses are optional when calling mixins. In the above example, both statements .p1(); and .p1; do the same thing."
},
{
"code": null,
"e": 4906,
"s": 4873,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4920,
"s": 4906,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4955,
"s": 4920,
"text": "\n 44 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4983,
"s": 4955,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5016,
"s": 4983,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5029,
"s": 5016,
"text": " Zach Miller"
},
{
"code": null,
"e": 5064,
"s": 5029,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5077,
"s": 5064,
"text": " Zach Miller"
},
{
"code": null,
"e": 5110,
"s": 5077,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5121,
"s": 5110,
"text": " Syed Raza"
},
{
"code": null,
"e": 5154,
"s": 5121,
"text": "\n 31 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5174,
"s": 5154,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 5181,
"s": 5174,
"text": " Print"
},
{
"code": null,
"e": 5192,
"s": 5181,
"text": " Add Notes"
}
] |
How to use if clause in MySQL to display Students result as Pass or Fail in a new column?
|
Let us first create a table −
mysql> create table DemoTable
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Name varchar(100),
-> Subject varchar(100),
-> Score int
-> );
Query OK, 0 rows affected (0.94 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name,Subject,Score) values('Chris','MySQL',80);
Query OK, 1 row affected (0.32 sec)
mysql> insert into DemoTable(Name,Subject,Score) values('Robert','MongoDB',45);
Query OK, 1 row affected (0.62 sec)
mysql> insert into DemoTable(Name,Subject,Score) values('Adam','Java',78);
Query OK, 1 row affected (0.52 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+---------+-------+
| Id | Name | Subject | Score |
+----+--------+---------+-------+
| 1 | Chris | MySQL | 80 |
| 2 | Robert | MongoDB | 45 |
| 3 | Adam | Java | 78 |
+----+--------+---------+-------+
3 rows in set (0.00 sec)
Here is the query to work with if clause in MySQL to display result in the form of Pass or Fail.
mysql> select Name,Subject,Score,if(Score > 75,"PASS","FAIL") AS Status from DemoTable;
This will produce the following output −
+--------+---------+-------+--------+
| Name | Subject | Score | Status |
+--------+---------+-------+--------+
| Chris | MySQL | 80 | PASS |
| Robert | MongoDB | 45 | FAIL |
| Adam | Java | 78 | PASS |
+--------+---------+-------+--------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1295,
"s": 1092,
"text": "mysql> create table DemoTable\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> Name varchar(100),\n -> Subject varchar(100),\n -> Score int\n -> );\nQuery OK, 0 rows affected (0.94 sec)"
},
{
"code": null,
"e": 1351,
"s": 1295,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1693,
"s": 1351,
"text": "mysql> insert into DemoTable(Name,Subject,Score) values('Chris','MySQL',80);\nQuery OK, 1 row affected (0.32 sec)\n\nmysql> insert into DemoTable(Name,Subject,Score) values('Robert','MongoDB',45);\nQuery OK, 1 row affected (0.62 sec)\n\nmysql> insert into DemoTable(Name,Subject,Score) values('Adam','Java',78);\nQuery OK, 1 row affected (0.52 sec)"
},
{
"code": null,
"e": 1753,
"s": 1693,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1784,
"s": 1753,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1825,
"s": 1784,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2088,
"s": 1825,
"text": "+----+--------+---------+-------+\n| Id | Name | Subject | Score |\n+----+--------+---------+-------+\n| 1 | Chris | MySQL | 80 |\n| 2 | Robert | MongoDB | 45 |\n| 3 | Adam | Java | 78 |\n+----+--------+---------+-------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2185,
"s": 2088,
"text": "Here is the query to work with if clause in MySQL to display result in the form of Pass or Fail."
},
{
"code": null,
"e": 2274,
"s": 2185,
"text": "mysql> select Name,Subject,Score,if(Score > 75,\"PASS\",\"FAIL\") AS Status from DemoTable;"
},
{
"code": null,
"e": 2315,
"s": 2274,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2606,
"s": 2315,
"text": "+--------+---------+-------+--------+\n| Name | Subject | Score | Status |\n+--------+---------+-------+--------+\n| Chris | MySQL | 80 | PASS |\n| Robert | MongoDB | 45 | FAIL |\n| Adam | Java | 78 | PASS |\n+--------+---------+-------+--------+\n3 rows in set (0.00 sec)"
}
] |
Python VLC MediaPlayer - Checking if it is playing or not - GeeksforGeeks
|
10 Feb, 2022
In this article we will see how we can check if the video is playing in MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. We can create a MediaPlayer object with the help of MediaPlayer method. We uses play method to play the video.
In order to do this we will use is_playing method with the MediaPlayer object
Syntax : media_player.is_playing()
Argument : It takes no argument
Return : It returns 0 if not playing and 1 if playing
Below is the implementation
# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media("death_note.mkv") # setting media to the media playermedia_player.set_media(media) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective of length of videotime.sleep(5) # checking if it is playingvalue = media_player.is_playing() # printing valueprint("Is playing : ")print(value)
Output :
Is playing :
1
Another exampleBelow is the implementation
# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media("1mp4.mkv") # setting media to the media playermedia_player.set_media(media) # start playing video + commenting it # media_player.play() # wait so the video can be played for 5 seconds# irrespective of length of videotime.sleep(5) # checking if it is playingvalue = media_player.is_playing() # printing valueprint("Is playing : ")print(value)
Output :
Is playing :
0
kumaripunam984122
Python vlc-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n10 Feb, 2022"
},
{
"code": null,
"e": 24745,
"s": 24292,
"text": "In this article we will see how we can check if the video is playing in MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. We can create a MediaPlayer object with the help of MediaPlayer method. We uses play method to play the video."
},
{
"code": null,
"e": 24823,
"s": 24745,
"text": "In order to do this we will use is_playing method with the MediaPlayer object"
},
{
"code": null,
"e": 24858,
"s": 24823,
"text": "Syntax : media_player.is_playing()"
},
{
"code": null,
"e": 24890,
"s": 24858,
"text": "Argument : It takes no argument"
},
{
"code": null,
"e": 24944,
"s": 24890,
"text": "Return : It returns 0 if not playing and 1 if playing"
},
{
"code": null,
"e": 24972,
"s": 24944,
"text": "Below is the implementation"
},
{
"code": "# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media(\"death_note.mkv\") # setting media to the media playermedia_player.set_media(media) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective of length of videotime.sleep(5) # checking if it is playingvalue = media_player.is_playing() # printing valueprint(\"Is playing : \")print(value)",
"e": 25481,
"s": 24972,
"text": null
},
{
"code": null,
"e": 25490,
"s": 25481,
"text": "Output :"
},
{
"code": null,
"e": 25507,
"s": 25490,
"text": "Is playing : \n1\n"
},
{
"code": null,
"e": 25550,
"s": 25507,
"text": "Another exampleBelow is the implementation"
},
{
"code": "# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media(\"1mp4.mkv\") # setting media to the media playermedia_player.set_media(media) # start playing video + commenting it # media_player.play() # wait so the video can be played for 5 seconds# irrespective of length of videotime.sleep(5) # checking if it is playingvalue = media_player.is_playing() # printing valueprint(\"Is playing : \")print(value)",
"e": 26072,
"s": 25550,
"text": null
},
{
"code": null,
"e": 26081,
"s": 26072,
"text": "Output :"
},
{
"code": null,
"e": 26098,
"s": 26081,
"text": "Is playing : \n0\n"
},
{
"code": null,
"e": 26116,
"s": 26098,
"text": "kumaripunam984122"
},
{
"code": null,
"e": 26135,
"s": 26116,
"text": "Python vlc-library"
},
{
"code": null,
"e": 26142,
"s": 26135,
"text": "Python"
},
{
"code": null,
"e": 26240,
"s": 26142,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26249,
"s": 26240,
"text": "Comments"
},
{
"code": null,
"e": 26262,
"s": 26249,
"text": "Old Comments"
},
{
"code": null,
"e": 26294,
"s": 26262,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26350,
"s": 26294,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26405,
"s": 26350,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26447,
"s": 26405,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26489,
"s": 26447,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26520,
"s": 26489,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26559,
"s": 26520,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26581,
"s": 26559,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26610,
"s": 26581,
"text": "Create a directory in Python"
}
] |
PHP 7 - Closure::call()
|
Closure::call() method is added as a shorthand way to temporarily bind an object scope to a closure and invoke it. It is much faster in performance as compared to bindTo of PHP 5.6.
<?php
class A {
private $x = 1;
}
// Define a closure Pre PHP 7 code
$getValue = function() {
return $this->x;
};
// Bind a clousure
$value = $getValue->bindTo(new A, 'A');
print($value());
?>
It produces the following browser output −
1
<?php
class A {
private $x = 1;
}
// PHP 7+ code, Define
$value = function() {
return $this->x;
};
print($value->call(new A));
?>
It produces the following browser output −
1
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2259,
"s": 2077,
"text": "Closure::call() method is added as a shorthand way to temporarily bind an object scope to a closure and invoke it. It is much faster in performance as compared to bindTo of PHP 5.6."
},
{
"code": null,
"e": 2492,
"s": 2259,
"text": "<?php\n class A {\n private $x = 1;\n }\n\n // Define a closure Pre PHP 7 code\n $getValue = function() {\n return $this->x;\n };\n\n // Bind a clousure\n $value = $getValue->bindTo(new A, 'A'); \n\n print($value());\n?>"
},
{
"code": null,
"e": 2535,
"s": 2492,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 2538,
"s": 2535,
"text": "1\n"
},
{
"code": null,
"e": 2700,
"s": 2538,
"text": "<?php\n class A {\n private $x = 1;\n }\n\n // PHP 7+ code, Define\n $value = function() {\n return $this->x;\n };\n\n print($value->call(new A));\n?>"
},
{
"code": null,
"e": 2743,
"s": 2700,
"text": "It produces the following browser output −"
},
{
"code": null,
"e": 2746,
"s": 2743,
"text": "1\n"
},
{
"code": null,
"e": 2779,
"s": 2746,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 2795,
"s": 2779,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 2828,
"s": 2795,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2839,
"s": 2828,
"text": " Syed Raza"
},
{
"code": null,
"e": 2874,
"s": 2839,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 2891,
"s": 2874,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 2924,
"s": 2891,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2939,
"s": 2924,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 2974,
"s": 2939,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 2986,
"s": 2974,
"text": " Azaz Patel"
},
{
"code": null,
"e": 3021,
"s": 2986,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3049,
"s": 3021,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 3056,
"s": 3049,
"text": " Print"
},
{
"code": null,
"e": 3067,
"s": 3056,
"text": " Add Notes"
}
] |
Sentiment Analysis — A how-to guide with movie reviews | by Shiao-li Green | Towards Data Science
|
So, what exactly is sentiment? Sentiment relates to the meaning of a word or sequence of words and is usually associated with an opinion or emotion. And analysis? Well, this is the process of looking at data and making inferences; in this case, using machine learning to learn and predict whether a movie review is positive or negative.
Maybe you’re interested in knowing whether movie reviews are positive or negative, companies use sentiment analysis in a variety of settings, particularly for marketing purposes. Uses include social media monitoring, brand monitoring, customer feedback, customer service and market research (“Sentiment Analysis”).
This post will cover:
The competitionPre-processing dataFeaturesModellingEvaluationNext steps
The competition
Pre-processing data
Features
Modelling
Evaluation
Next steps
We’ll be using the IMDB movie dataset which has 25,000 labelled reviews for training and 25,000 reviews for testing. The Kaggle challenge asks for binary classification (“Bag of Words Meets Bags of Popcorn”).
Let’s have a look at some summary statistics of the dataset (Li, 2019). We are told that there is an even split of positive and negative movie reviews. Here are some of the positive and negative reviews:
It’s also interesting to see the distribution of the length of movie reviews (word count) split according to sentiment. The spread is similar in shape for both types of reviews however negative reviews are on average a tad shorter.
Text is messy, people love to throw in attempts at expressing themselves more clearly by adding extravagant punctuation and spelling words incorrectly. However, machine learning models can’t cope with text as input, so we need to map the characters and words to numerical representations.
Basic pre-processing for text consists of removing non-alphabetic characters, stop words (a set of very common words like the, a, and, etc.) and changing all words to lowercase. In this instance, we also need to remove HTML tags from the movie reviews. These steps can be packaged into the following function.
The table below shows how the most frequent words change once stop words are removed from the reviews.
How should we approach transforming word representations to numerical versions that a model can interpret? There are many ways, but for now, let’s try a few of the simple approaches.
We obtain the vocabulary list from the corpus (whole text dataset). The length of the vocabulary list is equal to the length of the vector that will be output when we apply Bag of Words (BOW). For each item (could be an entry, sentence, line of text), we transform the text into a frequency count in the form of a vector. In this case, we limit it to the top 5000 words to restrict the dimensionality of the data. We code this by setting up a count vectorizer from sklearn’s library, fit it on the training data and then transform both the training and test data.
An example of how this works is in the grey box below. We look at all the unique words in the corpus and then count how many times these appear in each of the pieces of texts, resulting in a vector representation of each piece of text.
Text:It was the best of times,it was the worst of times,it was the age of wisdom,it was the age of foolishness.Unique words:"it", "was", "the", "best", "of", "times", "worst", "age", "wisdom" "foolishness""it was the worst of times" = [1, 1, 1, 0, 1, 1, 1, 0, 0, 0]"it was the age of wisdom" = [1, 1, 1, 0, 1, 0, 0, 1, 1, 0]"it was the age of foolishness" = [1, 1, 1, 0, 1, 0, 0, 1, 0, 1]
Word2vec (Word to Vector) is a two-layer neural net that processes text. Its input is a text corpus and its output is a set of vectors: feature vectors for words in that corpus. The algorithm was created by Google in 2013. The 50-D space can be visualised by using classical projection methods (e.g. PCA) to reduce the vectors to two-dimensional data that can be plotted on a graph.
Why would we use Word2vec instead of BOW? It is better at learning words in their surrounding context. The process is a bit more convoluted than implementing BOW so I won’t outline it here, but it can be found in the GitHub folder (Dar, Green, Kurban & Mitchell, 2019). In short, it requires tokenising reviews as sentences rather than words, determining the vector representations and then averaging them appropriately.
This is short for Term-frequency-Inverse-Document-Frequency and gives us a measure of how important a word is in the document.
Term frequency (the same as for bag of words):
Inverse document frequency measures how rare a term is across all documents (the higher the value, the rarer the word)[1]:
We combine these two to get Tf-Idf as follows:
To implement this representation, we use the TfidfTransformer function from sklearn’s library. Fitting occurs on the training set and the values for the same words are determined for the test set.
[1] Where ln is the natural logarithm.
We attempted two different models for this dataset: Naïve Bayes and Random Forest. Naïve Bayes builds on Bayes’ Theorem while a Random Forest is a group of decision trees. Consolidated code for these two implementations can be found in the NLP_IMDb Jupyter notebook in the GitHub Repository (Dar et al., 2019).
This is a probabilistic machine learning model used for classification, based on Bayes Theorem:
B is the evidence while A is the hypothesis (Gandhi, 2018). We must assume that the features are independent (one does not affect the other).
Framing it in terms of this problem we have y representing a positive or negative review, X represents a vector of the features from the reviews. The equation we end up with for finding the class is:
This is implemented using sklearn’s Naïve Bayes package!
A random forest is a series of decision trees in which the leaf nodes indicate the predicted class. We can use the RandomForestClassifier function from sklearn’s ensemble package.
Each decision tree incorporates a selection of features and outputs a decision at the end. These results are then combined from all the decision trees to give the final class prediction. The diagram below from DataCamp visualises the process quite nicely.
Kaggle specifies using the area under the ROC curve as the metric for this competition. ROC is short for Receiving Operator Characteristic and is a probability curve. It plots the true positive rate against the false positive rate.[2] The higher the area under this curve, the better the model is at predicting the output. The graph for Bag of words and a Random Forest is below. The dotted line represents the baseline, which would be expected if the predictions were random.
We can inspect a few different permutations in the table below.
It’s interesting to see that Tf-Idf does marginally better and Naïve Bayes performs slightly better than the Random Forest. However, there is a significant drop in the performance of Naïve Bayes with Word2Vec features. This is likely because some information is lost when the representation is transformed to be positive (since Naïve Bayes only allows for positive values) and Gaussian Naïve Bayes is used instead.
[2] True positive represents when an item that is positive is predicted as positive. False positive represents when an item that is negative is predicted as positive.
This is just the start of sentiment analysis. Further approaches could use bigrams (sequences of two words) to attempt to retain more contextual meaning, using neural networks like LSTMs (Long Short-Term Memory) to extend the distance of relationships among words in the reviews and more.
Bag of Words Meets Bags of Popcorn. (n.d.). Retrieved from https://www.kaggle.com/c/word2vec-nlp-tutorial/
Dar, O., Green, S., Kurban, R., & Mitchell, C. (2019). Sprint 3, Team 1. Retrieved from https://github.com/shiaoligreen/practical-data-science
Gandhi, R. (2018, May 5). Naïve Bayes Classifier. Retrieved from https://towardsdatascience.com/naive-bayes-classifier-81d512f50a7c
Li, S. (2019, March 18). A Complete Exploratory Data Analysis and Visualization for Text Data. Retrieved from https://towardsdatascience.com/a-complete-exploratory-data-analysis-and-visualization-for-text-data-29fb1b96fb6a
Sentiment Analysis. (n.d.). Retrieved from https://monkeylearn.com/sentiment-analysis/
|
[
{
"code": null,
"e": 509,
"s": 172,
"text": "So, what exactly is sentiment? Sentiment relates to the meaning of a word or sequence of words and is usually associated with an opinion or emotion. And analysis? Well, this is the process of looking at data and making inferences; in this case, using machine learning to learn and predict whether a movie review is positive or negative."
},
{
"code": null,
"e": 824,
"s": 509,
"text": "Maybe you’re interested in knowing whether movie reviews are positive or negative, companies use sentiment analysis in a variety of settings, particularly for marketing purposes. Uses include social media monitoring, brand monitoring, customer feedback, customer service and market research (“Sentiment Analysis”)."
},
{
"code": null,
"e": 846,
"s": 824,
"text": "This post will cover:"
},
{
"code": null,
"e": 918,
"s": 846,
"text": "The competitionPre-processing dataFeaturesModellingEvaluationNext steps"
},
{
"code": null,
"e": 934,
"s": 918,
"text": "The competition"
},
{
"code": null,
"e": 954,
"s": 934,
"text": "Pre-processing data"
},
{
"code": null,
"e": 963,
"s": 954,
"text": "Features"
},
{
"code": null,
"e": 973,
"s": 963,
"text": "Modelling"
},
{
"code": null,
"e": 984,
"s": 973,
"text": "Evaluation"
},
{
"code": null,
"e": 995,
"s": 984,
"text": "Next steps"
},
{
"code": null,
"e": 1204,
"s": 995,
"text": "We’ll be using the IMDB movie dataset which has 25,000 labelled reviews for training and 25,000 reviews for testing. The Kaggle challenge asks for binary classification (“Bag of Words Meets Bags of Popcorn”)."
},
{
"code": null,
"e": 1408,
"s": 1204,
"text": "Let’s have a look at some summary statistics of the dataset (Li, 2019). We are told that there is an even split of positive and negative movie reviews. Here are some of the positive and negative reviews:"
},
{
"code": null,
"e": 1640,
"s": 1408,
"text": "It’s also interesting to see the distribution of the length of movie reviews (word count) split according to sentiment. The spread is similar in shape for both types of reviews however negative reviews are on average a tad shorter."
},
{
"code": null,
"e": 1929,
"s": 1640,
"text": "Text is messy, people love to throw in attempts at expressing themselves more clearly by adding extravagant punctuation and spelling words incorrectly. However, machine learning models can’t cope with text as input, so we need to map the characters and words to numerical representations."
},
{
"code": null,
"e": 2239,
"s": 1929,
"text": "Basic pre-processing for text consists of removing non-alphabetic characters, stop words (a set of very common words like the, a, and, etc.) and changing all words to lowercase. In this instance, we also need to remove HTML tags from the movie reviews. These steps can be packaged into the following function."
},
{
"code": null,
"e": 2342,
"s": 2239,
"text": "The table below shows how the most frequent words change once stop words are removed from the reviews."
},
{
"code": null,
"e": 2525,
"s": 2342,
"text": "How should we approach transforming word representations to numerical versions that a model can interpret? There are many ways, but for now, let’s try a few of the simple approaches."
},
{
"code": null,
"e": 3089,
"s": 2525,
"text": "We obtain the vocabulary list from the corpus (whole text dataset). The length of the vocabulary list is equal to the length of the vector that will be output when we apply Bag of Words (BOW). For each item (could be an entry, sentence, line of text), we transform the text into a frequency count in the form of a vector. In this case, we limit it to the top 5000 words to restrict the dimensionality of the data. We code this by setting up a count vectorizer from sklearn’s library, fit it on the training data and then transform both the training and test data."
},
{
"code": null,
"e": 3325,
"s": 3089,
"text": "An example of how this works is in the grey box below. We look at all the unique words in the corpus and then count how many times these appear in each of the pieces of texts, resulting in a vector representation of each piece of text."
},
{
"code": null,
"e": 3714,
"s": 3325,
"text": "Text:It was the best of times,it was the worst of times,it was the age of wisdom,it was the age of foolishness.Unique words:\"it\", \"was\", \"the\", \"best\", \"of\", \"times\", \"worst\", \"age\", \"wisdom\" \"foolishness\"\"it was the worst of times\" = [1, 1, 1, 0, 1, 1, 1, 0, 0, 0]\"it was the age of wisdom\" = [1, 1, 1, 0, 1, 0, 0, 1, 1, 0]\"it was the age of foolishness\" = [1, 1, 1, 0, 1, 0, 0, 1, 0, 1]"
},
{
"code": null,
"e": 4097,
"s": 3714,
"text": "Word2vec (Word to Vector) is a two-layer neural net that processes text. Its input is a text corpus and its output is a set of vectors: feature vectors for words in that corpus. The algorithm was created by Google in 2013. The 50-D space can be visualised by using classical projection methods (e.g. PCA) to reduce the vectors to two-dimensional data that can be plotted on a graph."
},
{
"code": null,
"e": 4518,
"s": 4097,
"text": "Why would we use Word2vec instead of BOW? It is better at learning words in their surrounding context. The process is a bit more convoluted than implementing BOW so I won’t outline it here, but it can be found in the GitHub folder (Dar, Green, Kurban & Mitchell, 2019). In short, it requires tokenising reviews as sentences rather than words, determining the vector representations and then averaging them appropriately."
},
{
"code": null,
"e": 4645,
"s": 4518,
"text": "This is short for Term-frequency-Inverse-Document-Frequency and gives us a measure of how important a word is in the document."
},
{
"code": null,
"e": 4692,
"s": 4645,
"text": "Term frequency (the same as for bag of words):"
},
{
"code": null,
"e": 4815,
"s": 4692,
"text": "Inverse document frequency measures how rare a term is across all documents (the higher the value, the rarer the word)[1]:"
},
{
"code": null,
"e": 4862,
"s": 4815,
"text": "We combine these two to get Tf-Idf as follows:"
},
{
"code": null,
"e": 5059,
"s": 4862,
"text": "To implement this representation, we use the TfidfTransformer function from sklearn’s library. Fitting occurs on the training set and the values for the same words are determined for the test set."
},
{
"code": null,
"e": 5098,
"s": 5059,
"text": "[1] Where ln is the natural logarithm."
},
{
"code": null,
"e": 5411,
"s": 5098,
"text": "We attempted two different models for this dataset: Naïve Bayes and Random Forest. Naïve Bayes builds on Bayes’ Theorem while a Random Forest is a group of decision trees. Consolidated code for these two implementations can be found in the NLP_IMDb Jupyter notebook in the GitHub Repository (Dar et al., 2019)."
},
{
"code": null,
"e": 5507,
"s": 5411,
"text": "This is a probabilistic machine learning model used for classification, based on Bayes Theorem:"
},
{
"code": null,
"e": 5649,
"s": 5507,
"text": "B is the evidence while A is the hypothesis (Gandhi, 2018). We must assume that the features are independent (one does not affect the other)."
},
{
"code": null,
"e": 5849,
"s": 5649,
"text": "Framing it in terms of this problem we have y representing a positive or negative review, X represents a vector of the features from the reviews. The equation we end up with for finding the class is:"
},
{
"code": null,
"e": 5907,
"s": 5849,
"text": "This is implemented using sklearn’s Naïve Bayes package!"
},
{
"code": null,
"e": 6087,
"s": 5907,
"text": "A random forest is a series of decision trees in which the leaf nodes indicate the predicted class. We can use the RandomForestClassifier function from sklearn’s ensemble package."
},
{
"code": null,
"e": 6343,
"s": 6087,
"text": "Each decision tree incorporates a selection of features and outputs a decision at the end. These results are then combined from all the decision trees to give the final class prediction. The diagram below from DataCamp visualises the process quite nicely."
},
{
"code": null,
"e": 6820,
"s": 6343,
"text": "Kaggle specifies using the area under the ROC curve as the metric for this competition. ROC is short for Receiving Operator Characteristic and is a probability curve. It plots the true positive rate against the false positive rate.[2] The higher the area under this curve, the better the model is at predicting the output. The graph for Bag of words and a Random Forest is below. The dotted line represents the baseline, which would be expected if the predictions were random."
},
{
"code": null,
"e": 6884,
"s": 6820,
"text": "We can inspect a few different permutations in the table below."
},
{
"code": null,
"e": 7303,
"s": 6884,
"text": "It’s interesting to see that Tf-Idf does marginally better and Naïve Bayes performs slightly better than the Random Forest. However, there is a significant drop in the performance of Naïve Bayes with Word2Vec features. This is likely because some information is lost when the representation is transformed to be positive (since Naïve Bayes only allows for positive values) and Gaussian Naïve Bayes is used instead."
},
{
"code": null,
"e": 7470,
"s": 7303,
"text": "[2] True positive represents when an item that is positive is predicted as positive. False positive represents when an item that is negative is predicted as positive."
},
{
"code": null,
"e": 7759,
"s": 7470,
"text": "This is just the start of sentiment analysis. Further approaches could use bigrams (sequences of two words) to attempt to retain more contextual meaning, using neural networks like LSTMs (Long Short-Term Memory) to extend the distance of relationships among words in the reviews and more."
},
{
"code": null,
"e": 7866,
"s": 7759,
"text": "Bag of Words Meets Bags of Popcorn. (n.d.). Retrieved from https://www.kaggle.com/c/word2vec-nlp-tutorial/"
},
{
"code": null,
"e": 8009,
"s": 7866,
"text": "Dar, O., Green, S., Kurban, R., & Mitchell, C. (2019). Sprint 3, Team 1. Retrieved from https://github.com/shiaoligreen/practical-data-science"
},
{
"code": null,
"e": 8142,
"s": 8009,
"text": "Gandhi, R. (2018, May 5). Naïve Bayes Classifier. Retrieved from https://towardsdatascience.com/naive-bayes-classifier-81d512f50a7c"
},
{
"code": null,
"e": 8365,
"s": 8142,
"text": "Li, S. (2019, March 18). A Complete Exploratory Data Analysis and Visualization for Text Data. Retrieved from https://towardsdatascience.com/a-complete-exploratory-data-analysis-and-visualization-for-text-data-29fb1b96fb6a"
}
] |
Write a Python program to export dataframe into an Excel file with multiple sheets
|
Assume, you have a dataframe and the result for export dataframe to multiple sheets as,
To solve this, we will follow the steps given below −
import xlsxwriter module to use excel conversion
import xlsxwriter module to use excel conversion
Define a dataframe and assign to df
Define a dataframe and assign to df
Apply pd.ExcelWriter function inside name excel name you want to create and set engine as xlsxwriter
Apply pd.ExcelWriter function inside name excel name you want to create and set engine as xlsxwriter
excel_writer = pd.ExcelWriter('pandas_df.xlsx', engine='xlsxwriter')
Convert the dataframe to multiple excel sheets using the below method,
Convert the dataframe to multiple excel sheets using the below method,
df.to_excel(excel_writer, sheet_name='first_sheet')
df.to_excel(excel_writer, sheet_name='second_sheet')
df.to_excel(excel_writer, sheet_name='third_sheet')
Finally save the excel_writer
Finally save the excel_writer
excel_writer.save()
Let’s understand the below code to get a better understanding −
import pandas as pd
import xlsxwriter
df = pd.DataFrame({'Fruits': ["Apple","Orange","Mango","Kiwi"],
'City' : ["Shimla","Sydney","Lucknow","Wellington"]
})
print(df)
excel_writer = pd.ExcelWriter('pandas_df.xlsx', engine='xlsxwriter')
df.to_excel(excel_writer, sheet_name='first_sheet')
df.to_excel(excel_writer, sheet_name='second_sheet')
df.to_excel(excel_writer, sheet_name='third_sheet')
excel_writer.save()
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "Assume, you have a dataframe and the result for export dataframe to multiple sheets as,"
},
{
"code": null,
"e": 1204,
"s": 1150,
"text": "To solve this, we will follow the steps given below −"
},
{
"code": null,
"e": 1253,
"s": 1204,
"text": "import xlsxwriter module to use excel conversion"
},
{
"code": null,
"e": 1302,
"s": 1253,
"text": "import xlsxwriter module to use excel conversion"
},
{
"code": null,
"e": 1338,
"s": 1302,
"text": "Define a dataframe and assign to df"
},
{
"code": null,
"e": 1374,
"s": 1338,
"text": "Define a dataframe and assign to df"
},
{
"code": null,
"e": 1475,
"s": 1374,
"text": "Apply pd.ExcelWriter function inside name excel name you want to create and set engine as xlsxwriter"
},
{
"code": null,
"e": 1576,
"s": 1475,
"text": "Apply pd.ExcelWriter function inside name excel name you want to create and set engine as xlsxwriter"
},
{
"code": null,
"e": 1645,
"s": 1576,
"text": "excel_writer = pd.ExcelWriter('pandas_df.xlsx', engine='xlsxwriter')"
},
{
"code": null,
"e": 1716,
"s": 1645,
"text": "Convert the dataframe to multiple excel sheets using the below method,"
},
{
"code": null,
"e": 1787,
"s": 1716,
"text": "Convert the dataframe to multiple excel sheets using the below method,"
},
{
"code": null,
"e": 1944,
"s": 1787,
"text": "df.to_excel(excel_writer, sheet_name='first_sheet')\ndf.to_excel(excel_writer, sheet_name='second_sheet')\ndf.to_excel(excel_writer, sheet_name='third_sheet')"
},
{
"code": null,
"e": 1974,
"s": 1944,
"text": "Finally save the excel_writer"
},
{
"code": null,
"e": 2004,
"s": 1974,
"text": "Finally save the excel_writer"
},
{
"code": null,
"e": 2024,
"s": 2004,
"text": "excel_writer.save()"
},
{
"code": null,
"e": 2088,
"s": 2024,
"text": "Let’s understand the below code to get a better understanding −"
},
{
"code": null,
"e": 2540,
"s": 2088,
"text": "import pandas as pd\nimport xlsxwriter\ndf = pd.DataFrame({'Fruits': [\"Apple\",\"Orange\",\"Mango\",\"Kiwi\"],\n 'City' : [\"Shimla\",\"Sydney\",\"Lucknow\",\"Wellington\"]\n })\nprint(df)\nexcel_writer = pd.ExcelWriter('pandas_df.xlsx', engine='xlsxwriter')\ndf.to_excel(excel_writer, sheet_name='first_sheet')\ndf.to_excel(excel_writer, sheet_name='second_sheet')\ndf.to_excel(excel_writer, sheet_name='third_sheet')\nexcel_writer.save()"
}
] |
Apache Pig - TOP()
|
The TOP() function of Pig Latin is used to get the top N tuples of a bag. To this function, as inputs, we have to pass a relation, the number of tuples we want, and the column name whose values are being compared. This function will return a bag containing the required columns.
Given below is the syntax of the function TOP().
grunt> TOP(topN,column,relation)
Assume we have a file named employee_details.txt in the HDFS directory /pig_data/, with the following content.
employee_details.txt
001,Robin,22,newyork
002,BOB,23,Kolkata
003,Maya,23,Tokyo
004,Sara,25,London
005,David,23,Bhuwaneshwar
006,Maggy,22,Chennai
007,Robert,22,newyork
008,Syam,23,Kolkata
009,Mary,25,Tokyo
010,Saran,25,London
011,Stacy,25,Bhuwaneshwar
012,Kelly,22,Chennai
We have loaded this file into Pig with the relation name emp_data as shown below.
grunt> emp_data = LOAD 'hdfs://localhost:9000/pig_data/ employee_details.txt' USING PigStorage(',')
as (id:int, name:chararray, age:int, city:chararray);
Group the relation emp_data by age, and store it in the relation emp_group.
grunt> emp_group = Group emp_data BY age;
Verify the relation emp_group using the Dump operator as shown below.
grunt> Dump emp_group;
(22,{(12,Kelly,22,Chennai),(7,Robert,22,newyork),(6,Maggy,22,Chennai),(1,Robin, 22,newyork)})
(23,{(8,Syam,23,Kolkata),(5,David,23,Bhuwaneshwar),(3,Maya,23,Tokyo),(2,BOB,23, Kolkata)})
(25,{(11,Stacy,25,Bhuwaneshwar),(10,Saran,25,London),(9,Mary,25,Tokyo),(4,Sara, 25,London)})
Now, you can get the top two records of each group arranged in ascending order (based on id) as shown below.
grunt> data_top = FOREACH emp_group {
top = TOP(2, 0, emp_data);
GENERATE top;
}
In this example we are retriving the top 2 tuples of a group having greater id. Since we are retriving top 2 tuples basing on the id, we are passing the index of the column name id as second parameter of TOP() function.
You can verify the contents of the data_top relation using the Dump operator as shown below.
grunt> Dump data_top;
({(7,Robert,22,newyork),(12,Kelly,22,Chennai)})
({(5,David,23,Bhuwaneshwar),(8,Syam,23,Kolkata)})
({(10,Saran,25,London),(11,Stacy,25,Bhuwaneshwar)})
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2963,
"s": 2684,
"text": "The TOP() function of Pig Latin is used to get the top N tuples of a bag. To this function, as inputs, we have to pass a relation, the number of tuples we want, and the column name whose values are being compared. This function will return a bag containing the required columns."
},
{
"code": null,
"e": 3012,
"s": 2963,
"text": "Given below is the syntax of the function TOP()."
},
{
"code": null,
"e": 3046,
"s": 3012,
"text": "grunt> TOP(topN,column,relation)\n"
},
{
"code": null,
"e": 3157,
"s": 3046,
"text": "Assume we have a file named employee_details.txt in the HDFS directory /pig_data/, with the following content."
},
{
"code": null,
"e": 3178,
"s": 3157,
"text": "employee_details.txt"
},
{
"code": null,
"e": 3441,
"s": 3178,
"text": "001,Robin,22,newyork \n002,BOB,23,Kolkata \n003,Maya,23,Tokyo \n004,Sara,25,London \n005,David,23,Bhuwaneshwar \n006,Maggy,22,Chennai \n007,Robert,22,newyork \n008,Syam,23,Kolkata \n009,Mary,25,Tokyo \n010,Saran,25,London \n011,Stacy,25,Bhuwaneshwar \n012,Kelly,22,Chennai\n"
},
{
"code": null,
"e": 3523,
"s": 3441,
"text": "We have loaded this file into Pig with the relation name emp_data as shown below."
},
{
"code": null,
"e": 3680,
"s": 3523,
"text": "grunt> emp_data = LOAD 'hdfs://localhost:9000/pig_data/ employee_details.txt' USING PigStorage(',')\n as (id:int, name:chararray, age:int, city:chararray);"
},
{
"code": null,
"e": 3756,
"s": 3680,
"text": "Group the relation emp_data by age, and store it in the relation emp_group."
},
{
"code": null,
"e": 3798,
"s": 3756,
"text": "grunt> emp_group = Group emp_data BY age;"
},
{
"code": null,
"e": 3868,
"s": 3798,
"text": "Verify the relation emp_group using the Dump operator as shown below."
},
{
"code": null,
"e": 4175,
"s": 3868,
"text": "grunt> Dump emp_group;\n \n(22,{(12,Kelly,22,Chennai),(7,Robert,22,newyork),(6,Maggy,22,Chennai),(1,Robin, 22,newyork)}) \n(23,{(8,Syam,23,Kolkata),(5,David,23,Bhuwaneshwar),(3,Maya,23,Tokyo),(2,BOB,23, Kolkata)}) \n(25,{(11,Stacy,25,Bhuwaneshwar),(10,Saran,25,London),(9,Mary,25,Tokyo),(4,Sara, 25,London)})\n"
},
{
"code": null,
"e": 4284,
"s": 4175,
"text": "Now, you can get the top two records of each group arranged in ascending order (based on id) as shown below."
},
{
"code": null,
"e": 4374,
"s": 4284,
"text": "grunt> data_top = FOREACH emp_group { \n top = TOP(2, 0, emp_data); \n GENERATE top; \n}"
},
{
"code": null,
"e": 4594,
"s": 4374,
"text": "In this example we are retriving the top 2 tuples of a group having greater id. Since we are retriving top 2 tuples basing on the id, we are passing the index of the column name id as second parameter of TOP() function."
},
{
"code": null,
"e": 4687,
"s": 4594,
"text": "You can verify the contents of the data_top relation using the Dump operator as shown below."
},
{
"code": null,
"e": 4865,
"s": 4687,
"text": "grunt> Dump data_top;\n \n({(7,Robert,22,newyork),(12,Kelly,22,Chennai)}) \n({(5,David,23,Bhuwaneshwar),(8,Syam,23,Kolkata)}) \n({(10,Saran,25,London),(11,Stacy,25,Bhuwaneshwar)})\n"
},
{
"code": null,
"e": 4900,
"s": 4865,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4919,
"s": 4900,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4954,
"s": 4919,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4975,
"s": 4954,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 5008,
"s": 4975,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5021,
"s": 5008,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5056,
"s": 5021,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5074,
"s": 5056,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5107,
"s": 5074,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5125,
"s": 5107,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5158,
"s": 5125,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5176,
"s": 5158,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5183,
"s": 5176,
"text": " Print"
},
{
"code": null,
"e": 5194,
"s": 5183,
"text": " Add Notes"
}
] |
Install Visual Studio Code in Kali Linux - GeeksforGeeks
|
17 Jun, 2021
Visual Studio Code is an open-source, cross-platform source-code editor developed by Microsoft. It is used by developers for developing software and writing code using programming languages such as C, C++, Python, Go, Java, etc. Visual Studio Code employs the same editor used in Azure, DevOps
Debugging
Syntax highlighting
Intelligent code completion
Code refactoring
In this article, we will show you the installation process of the Visual Studio Code on Kali Linux (or other Ubuntu/Debian-based Linux).
To install Visual Code Studio on Debian-based systems, you have to enable the VS Code repository and install the Visual Studio Code package using the apt package manager.
The steps for installing Visual Code Studio is as follows:
Step 1: First, you have to update your system using the following command:
$ sudo apt update
Step 2: Now, after your system is updated, install the required dependencies for Visual Code Studio by using the following command:-
$ sudo apt install software-properties-common apt-transport-https
Step 3: Next, download the repository using the wget command, import Microsoft’s GPG key, and add it to your kali source list by using the following commands:-
$ wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg –dearmor > packages.microsoft.gpg
$ sudo install -o root -g root -m 644 packages.microsoft.gpg /etc/apt/trusted.gpg.d/
$ sudo sh -c ‘echo “deb [arch=amd64 signed-by=/etc/apt/trusted.gpg.d/packages.microsoft.gpg] https://packages.microsoft.com/repos/vscode stable main” > /etc/apt/sources.list.d/vscode.list’
Step 4: Once you’ve done with the above steps, next you have to update the system and install Visual Studio Code by running the following commands:-
$ sudo apt update
$ sudo apt install code
Step 5: Once the installation of Visual Studio Code is completed, go search for Visual Code Studio from the application manager and you can see it over the screen like this:-
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
chown command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples
|
[
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 24701,
"s": 24406,
"text": "Visual Studio Code is an open-source, cross-platform source-code editor developed by Microsoft. It is used by developers for developing software and writing code using programming languages such as C, C++, Python, Go, Java, etc. Visual Studio Code employs the same editor used in Azure, DevOps "
},
{
"code": null,
"e": 24711,
"s": 24701,
"text": "Debugging"
},
{
"code": null,
"e": 24731,
"s": 24711,
"text": "Syntax highlighting"
},
{
"code": null,
"e": 24759,
"s": 24731,
"text": "Intelligent code completion"
},
{
"code": null,
"e": 24776,
"s": 24759,
"text": "Code refactoring"
},
{
"code": null,
"e": 24914,
"s": 24776,
"text": "In this article, we will show you the installation process of the Visual Studio Code on Kali Linux (or other Ubuntu/Debian-based Linux). "
},
{
"code": null,
"e": 25085,
"s": 24914,
"text": "To install Visual Code Studio on Debian-based systems, you have to enable the VS Code repository and install the Visual Studio Code package using the apt package manager."
},
{
"code": null,
"e": 25144,
"s": 25085,
"text": "The steps for installing Visual Code Studio is as follows:"
},
{
"code": null,
"e": 25219,
"s": 25144,
"text": "Step 1: First, you have to update your system using the following command:"
},
{
"code": null,
"e": 25237,
"s": 25219,
"text": "$ sudo apt update"
},
{
"code": null,
"e": 25371,
"s": 25237,
"text": "Step 2: Now, after your system is updated, install the required dependencies for Visual Code Studio by using the following command:-"
},
{
"code": null,
"e": 25437,
"s": 25371,
"text": "$ sudo apt install software-properties-common apt-transport-https"
},
{
"code": null,
"e": 25597,
"s": 25437,
"text": "Step 3: Next, download the repository using the wget command, import Microsoft’s GPG key, and add it to your kali source list by using the following commands:-"
},
{
"code": null,
"e": 25699,
"s": 25597,
"text": "$ wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg –dearmor > packages.microsoft.gpg"
},
{
"code": null,
"e": 25784,
"s": 25699,
"text": "$ sudo install -o root -g root -m 644 packages.microsoft.gpg /etc/apt/trusted.gpg.d/"
},
{
"code": null,
"e": 25973,
"s": 25784,
"text": "$ sudo sh -c ‘echo “deb [arch=amd64 signed-by=/etc/apt/trusted.gpg.d/packages.microsoft.gpg] https://packages.microsoft.com/repos/vscode stable main” > /etc/apt/sources.list.d/vscode.list’"
},
{
"code": null,
"e": 26122,
"s": 25973,
"text": "Step 4: Once you’ve done with the above steps, next you have to update the system and install Visual Studio Code by running the following commands:-"
},
{
"code": null,
"e": 26164,
"s": 26122,
"text": "$ sudo apt update\n$ sudo apt install code"
},
{
"code": null,
"e": 26342,
"s": 26164,
"text": "Step 5: Once the installation of Visual Studio Code is completed, go search for Visual Code Studio from the application manager and you can see it over the screen like this:-"
},
{
"code": null,
"e": 26353,
"s": 26342,
"text": "Kali-Linux"
},
{
"code": null,
"e": 26365,
"s": 26353,
"text": "Linux-Tools"
},
{
"code": null,
"e": 26376,
"s": 26365,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26474,
"s": 26376,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26511,
"s": 26474,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26546,
"s": 26511,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 26572,
"s": 26546,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 26606,
"s": 26572,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 26643,
"s": 26606,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26672,
"s": 26643,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 26698,
"s": 26672,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 26738,
"s": 26698,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 26773,
"s": 26738,
"text": "Basic Operators in Shell Scripting"
}
] |
What is Scanner class in Java? when was it introduced?
|
Until Java 1.5 to read data from the user programmers used to depend on the character stream classes and byte stream classes.
From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions.
By default, whitespace is considered as the delimiter (to break the data into tokens).
To read various datatypes from the source using the nextXXX() methods provided by this class namely, nextInt(), nextShort(), nextFloat(), nextLong(), nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(), nextByte(), nextFloat(), next().
Example − Reading data from keyboard
Following Java program reads name, date of birth, roll number and, percent from the user and prints back his age and grade. Here, we are using the methods of Scanner class to read the data.
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.Date;
import java.util.Scanner;
public class ScannerExample {
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = sc.next();
System.out.println("Enter your date of birth (dd-MM-yyyy): ");
String dob = sc.next();
System.out.println("Enter your roll number: ");
int rollNumber = sc.nextInt();
System.out.println("Enter your percentage: ");
float percent = sc.nextFloat();
//Getting Date object from given String
Date date = new SimpleDateFormat("dd-MM-yyyy").parse(dob);
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
//Calculating age
Period period = Period.between(localDate, LocalDate.now());
System.out.print("Hello "+name+" your current age is: ");
System.out.print(period.getYears()+" years "+period.getMonths()+" and "+period.getDays()+" days");
System.out.println();
if(percent>=80){
System.out.println("Your grade is: A");
} else if(percent>=60 && percent<80) {
System.out.println("Your grade is: B");
}
else if(percent>=40 && percent<60){
System.out.println("Your grade is: C");
} else {
System.out.println("Your grade is: D");
}
}
}
Enter your name:
Krishna
Enter your date of birth (dd-MM-yyyy):
26-09-1989
Enter your roll number:
1254
Enter your percentage:
83
Hello Krishna your current age is: 29 years 9 and 5 days
Your grade is: A
|
[
{
"code": null,
"e": 1188,
"s": 1062,
"text": "Until Java 1.5 to read data from the user programmers used to depend on the character stream classes and byte stream classes."
},
{
"code": null,
"e": 1411,
"s": 1188,
"text": "From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions."
},
{
"code": null,
"e": 1498,
"s": 1411,
"text": "By default, whitespace is considered as the delimiter (to break the data into tokens)."
},
{
"code": null,
"e": 1756,
"s": 1498,
"text": "To read various datatypes from the source using the nextXXX() methods provided by this class namely, nextInt(), nextShort(), nextFloat(), nextLong(), nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(), nextByte(), nextFloat(), next()."
},
{
"code": null,
"e": 1793,
"s": 1756,
"text": "Example − Reading data from keyboard"
},
{
"code": null,
"e": 1983,
"s": 1793,
"text": "Following Java program reads name, date of birth, roll number and, percent from the user and prints back his age and grade. Here, we are using the methods of Scanner class to read the data."
},
{
"code": null,
"e": 3471,
"s": 1983,
"text": "import java.text.SimpleDateFormat;\nimport java.time.LocalDate;\nimport java.time.Period;\nimport java.time.ZoneId;\nimport java.util.Date;\nimport java.util.Scanner;\npublic class ScannerExample {\n public static void main(String args[]) throws Exception {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter your name: \");\n String name = sc.next();\n System.out.println(\"Enter your date of birth (dd-MM-yyyy): \");\n String dob = sc.next();\n System.out.println(\"Enter your roll number: \");\n int rollNumber = sc.nextInt();\n System.out.println(\"Enter your percentage: \");\n float percent = sc.nextFloat();\n //Getting Date object from given String\n Date date = new SimpleDateFormat(\"dd-MM-yyyy\").parse(dob);\n LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();\n //Calculating age\n Period period = Period.between(localDate, LocalDate.now());\n System.out.print(\"Hello \"+name+\" your current age is: \");\n System.out.print(period.getYears()+\" years \"+period.getMonths()+\" and \"+period.getDays()+\" days\");\n System.out.println();\n if(percent>=80){\n System.out.println(\"Your grade is: A\");\n } else if(percent>=60 && percent<80) {\n System.out.println(\"Your grade is: B\");\n }\n else if(percent>=40 && percent<60){\n System.out.println(\"Your grade is: C\");\n } else {\n System.out.println(\"Your grade is: D\");\n }\n }\n}"
},
{
"code": null,
"e": 3675,
"s": 3471,
"text": "Enter your name:\nKrishna\nEnter your date of birth (dd-MM-yyyy):\n26-09-1989\nEnter your roll number:\n1254\nEnter your percentage:\n83\nHello Krishna your current age is: 29 years 9 and 5 days\nYour grade is: A"
}
] |
Program to equal two strings of same length by swapping characters in Python
|
Suppose we have two strings s and t of length n. We can take one character from s and another
from t and swap them. We can make unlimited number of swaps; we have to check whether it's
possible to make the two strings equal or not.
So, if the input is like s = "xy", t = "yx", then the output will be True
To solve this, we will follow these steps −
st:= sort the string after concatenating s and t
for i in range 0 to size of st - 1, increase by 2, doif st[i] is not same as st[i+1], thenreturn False
if st[i] is not same as st[i+1], thenreturn False
return False
return True
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, s, t):
st=sorted(s+t)
for i in range(0,len(st),2):
if st[i]!=st[i+1]:
return False
return True
ob = Solution()
print(ob.solve("xy", "yx"))
"xy", "yx"
True
|
[
{
"code": null,
"e": 1294,
"s": 1062,
"text": "Suppose we have two strings s and t of length n. We can take one character from s and another\nfrom t and swap them. We can make unlimited number of swaps; we have to check whether it's\npossible to make the two strings equal or not."
},
{
"code": null,
"e": 1368,
"s": 1294,
"text": "So, if the input is like s = \"xy\", t = \"yx\", then the output will be True"
},
{
"code": null,
"e": 1412,
"s": 1368,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1461,
"s": 1412,
"text": "st:= sort the string after concatenating s and t"
},
{
"code": null,
"e": 1564,
"s": 1461,
"text": "for i in range 0 to size of st - 1, increase by 2, doif st[i] is not same as st[i+1], thenreturn False"
},
{
"code": null,
"e": 1614,
"s": 1564,
"text": "if st[i] is not same as st[i+1], thenreturn False"
},
{
"code": null,
"e": 1627,
"s": 1614,
"text": "return False"
},
{
"code": null,
"e": 1639,
"s": 1627,
"text": "return True"
},
{
"code": null,
"e": 1709,
"s": 1639,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1720,
"s": 1709,
"text": " Live Demo"
},
{
"code": null,
"e": 1933,
"s": 1720,
"text": "class Solution:\n def solve(self, s, t):\n st=sorted(s+t)\n for i in range(0,len(st),2):\n if st[i]!=st[i+1]:\n return False\n return True\nob = Solution()\nprint(ob.solve(\"xy\", \"yx\"))"
},
{
"code": null,
"e": 1944,
"s": 1933,
"text": "\"xy\", \"yx\""
},
{
"code": null,
"e": 1949,
"s": 1944,
"text": "True"
}
] |
EmailField – Django Forms
|
13 Feb, 2020
EmailField in Django Forms is a string field, for input of Emails. It is used for taking text inputs from the user. The default widget for this input is EmailInput. It uses MaxLengthValidator and MinLengthValidator if max_length and min_length are provided. Otherwise, all inputs are valid.
EmailField has following optional arguments:
max_length and min_length :- If provided, these arguments ensure that the string is at most or at least the given length.
empty_value :- The value to use to represent “ ”. Defaults to an empty string.
Syntax
field_name = forms.EmailField(**options)
Illustration of EmailField using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into forms.py file of geeks app.
from django import forms # creating a form class GeeksForm(forms.Form): geeks_field = forms.EmailField(max_length = 200)
Add the geeks app to INSTALLED_APPS
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]
Now to render this form into a view we need a view and a URL mapped to that URL. Let’s create a view first in views.py of geeks app,
from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} context['form'] = GeeksForm() return render( request, "home.html", context)
Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html.
<form method = "GET"> {{ form }} <input type = "submit" value = "Submit"></form>
Finally, a URL to map to this view in urls.py
from django.urls import path # importing views from views..pyfrom .views import home_view urlpatterns = [ path('', home_view ),]
Let’s run the server and check what has actually happened, Run
Python manage.py runserver
Thus, an geeks_field EmailField is created by replacing “_” with ” “. It is a field to input email strings.
EmailField is used for input of email address in the database. One can input Email Id, etc. Till now we have discussed how to implement EmailField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into field into a python string instance.In views.py,
from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context ={} form = GeeksForm() context['form']= form if request.GET: temp = request.GET['geeks_field'] print(type(temp)) return render(request, "home.html", context)
Let’s try something other than a email in a EmailField.
So it accepts a email input only otherwise validation errors will be seen. Now let’s try entering a valid Email into the field.Date data can be fetched using corresponding request dictionary. If method is GET, data would be available in request.GET and if post, request.POST correspondingly. In above example we have the value in temp which we can use for any purpose.
Core Field arguments are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument required = False to EmailField will enable it to be left blank by the user. Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:
NaveenArora
Django-forms
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Feb, 2020"
},
{
"code": null,
"e": 319,
"s": 28,
"text": "EmailField in Django Forms is a string field, for input of Emails. It is used for taking text inputs from the user. The default widget for this input is EmailInput. It uses MaxLengthValidator and MinLengthValidator if max_length and min_length are provided. Otherwise, all inputs are valid."
},
{
"code": null,
"e": 364,
"s": 319,
"text": "EmailField has following optional arguments:"
},
{
"code": null,
"e": 486,
"s": 364,
"text": "max_length and min_length :- If provided, these arguments ensure that the string is at most or at least the given length."
},
{
"code": null,
"e": 565,
"s": 486,
"text": "empty_value :- The value to use to represent “ ”. Defaults to an empty string."
},
{
"code": null,
"e": 572,
"s": 565,
"text": "Syntax"
},
{
"code": null,
"e": 613,
"s": 572,
"text": "field_name = forms.EmailField(**options)"
},
{
"code": null,
"e": 724,
"s": 613,
"text": "Illustration of EmailField using an Example. Consider a project named geeksforgeeks having an app named geeks."
},
{
"code": null,
"e": 811,
"s": 724,
"text": "Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 862,
"s": 811,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 895,
"s": 862,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 953,
"s": 895,
"text": "Enter the following code into forms.py file of geeks app."
},
{
"code": "from django import forms # creating a form class GeeksForm(forms.Form): geeks_field = forms.EmailField(max_length = 200)",
"e": 1078,
"s": 953,
"text": null
},
{
"code": null,
"e": 1114,
"s": 1078,
"text": "Add the geeks app to INSTALLED_APPS"
},
{
"code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]",
"e": 1352,
"s": 1114,
"text": null
},
{
"code": null,
"e": 1485,
"s": 1352,
"text": "Now to render this form into a view we need a view and a URL mapped to that URL. Let’s create a view first in views.py of geeks app,"
},
{
"code": "from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} context['form'] = GeeksForm() return render( request, \"home.html\", context)",
"e": 1697,
"s": 1485,
"text": null
},
{
"code": null,
"e": 1983,
"s": 1697,
"text": "Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html."
},
{
"code": "<form method = \"GET\"> {{ form }} <input type = \"submit\" value = \"Submit\"></form>",
"e": 2070,
"s": 1983,
"text": null
},
{
"code": null,
"e": 2116,
"s": 2070,
"text": "Finally, a URL to map to this view in urls.py"
},
{
"code": "from django.urls import path # importing views from views..pyfrom .views import home_view urlpatterns = [ path('', home_view ),]",
"e": 2250,
"s": 2116,
"text": null
},
{
"code": null,
"e": 2313,
"s": 2250,
"text": "Let’s run the server and check what has actually happened, Run"
},
{
"code": null,
"e": 2340,
"s": 2313,
"text": "Python manage.py runserver"
},
{
"code": null,
"e": 2448,
"s": 2340,
"text": "Thus, an geeks_field EmailField is created by replacing “_” with ” “. It is a field to input email strings."
},
{
"code": null,
"e": 2773,
"s": 2448,
"text": "EmailField is used for input of email address in the database. One can input Email Id, etc. Till now we have discussed how to implement EmailField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into field into a python string instance.In views.py,"
},
{
"code": "from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context ={} form = GeeksForm() context['form']= form if request.GET: temp = request.GET['geeks_field'] print(type(temp)) return render(request, \"home.html\", context)",
"e": 3082,
"s": 2773,
"text": null
},
{
"code": null,
"e": 3138,
"s": 3082,
"text": "Let’s try something other than a email in a EmailField."
},
{
"code": null,
"e": 3507,
"s": 3138,
"text": "So it accepts a email input only otherwise validation errors will be seen. Now let’s try entering a valid Email into the field.Date data can be fetched using corresponding request dictionary. If method is GET, data would be available in request.GET and if post, request.POST correspondingly. In above example we have the value in temp which we can use for any purpose."
},
{
"code": null,
"e": 3935,
"s": 3507,
"text": "Core Field arguments are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument required = False to EmailField will enable it to be left blank by the user. Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:"
},
{
"code": null,
"e": 3947,
"s": 3935,
"text": "NaveenArora"
},
{
"code": null,
"e": 3960,
"s": 3947,
"text": "Django-forms"
},
{
"code": null,
"e": 3974,
"s": 3960,
"text": "Python Django"
},
{
"code": null,
"e": 3981,
"s": 3974,
"text": "Python"
}
] |
Dart – Unit Testing
|
09 May, 2021
Unit Testing is a process of testing individual components of a software/application separately, to ensure that each component is functioning as intended.
It provides multiple advantages such as –
Ability to test out individual components without running the whole software/application.
Pinpoint errors easily inside a specific component.
Dart provides a package called test which lets the developer carry out unit testing very easily. In this article, we’ll write a few unit tests using this package, demonstrating various use cases and results.
Since we’re using test, which is an external dart package, a separate project has to be created to run the project.
We’ve to create a pubspec.yaml file, and add the following lines to the project.
name: DartTesting
dev_dependencies:
test:
Then we’ve to run the following command
dart pub get
This will initialize a project with the name DartTesting and also install the test package as a dev dependency
Next, we can create a main.dart file which will contain all our code and import the test package there.
import 'package:test/test.dart';
First, we’ve to write a simple function on which we can run our tests. Provided below is the code for calculating the sum of all the elements of an array.
Dart
// Get sum of all elements of an arrayint getSumOfArray(List<int> arr) { int res = 0; for (var i=0; i<arr.length; i++) { res += arr[i]; } return res;}
A unit test can be written for the above function by using the test() function. It takes in 2 Arguments
A string value containing a description of the unit testA test assertion by using the expect() function. The expect() function has to be provided with 2 values:Expected Value, which is provided manually by the developer.Actual Value, which is obtained by running the concerned functionIf these values match, then the Unit Test is successful, or else it is considered to be failing.
A string value containing a description of the unit test
A test assertion by using the expect() function. The expect() function has to be provided with 2 values:Expected Value, which is provided manually by the developer.Actual Value, which is obtained by running the concerned functionIf these values match, then the Unit Test is successful, or else it is considered to be failing.
Expected Value, which is provided manually by the developer.
Actual Value, which is obtained by running the concerned function
If these values match, then the Unit Test is successful, or else it is considered to be failing.
Provided below is the code for a unit test for getSumOfArray() function. Since the expected and actual values match, it’ll be a successful test.
Dart
main() { // Successful test for sum of array test('Get sum of array - success', () { int expectedValue = 15; int actualValue = getSumOfArray([1, 2, 3, 4, 5]); expect(expectedValue, actualValue); });}
Output
00:00 +0: Get sum of array - success
00:00 +1: All tests passed!
Exited
In this case, the expected value is different from the actual value, due to which the test will fail.
Dart
main() { // Unsuccessful test for sum of array test('Get sum of array - failure', () { int expectedValue = 40; int actualValue = getSumOfArray([1, 2, 3, 4, 5]); expect(expectedValue, actualValue); });}
Output
00:00 +0: Get sum of array - failure
00:00 +0 -1: Get sum of array - failure [E]
Expected: <15>
Actual: <40>
Dart-Collection
Picked
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 May, 2021"
},
{
"code": null,
"e": 208,
"s": 52,
"text": "Unit Testing is a process of testing individual components of a software/application separately, to ensure that each component is functioning as intended. "
},
{
"code": null,
"e": 250,
"s": 208,
"text": "It provides multiple advantages such as –"
},
{
"code": null,
"e": 340,
"s": 250,
"text": "Ability to test out individual components without running the whole software/application."
},
{
"code": null,
"e": 392,
"s": 340,
"text": "Pinpoint errors easily inside a specific component."
},
{
"code": null,
"e": 600,
"s": 392,
"text": "Dart provides a package called test which lets the developer carry out unit testing very easily. In this article, we’ll write a few unit tests using this package, demonstrating various use cases and results."
},
{
"code": null,
"e": 716,
"s": 600,
"text": "Since we’re using test, which is an external dart package, a separate project has to be created to run the project."
},
{
"code": null,
"e": 797,
"s": 716,
"text": "We’ve to create a pubspec.yaml file, and add the following lines to the project."
},
{
"code": null,
"e": 842,
"s": 797,
"text": "name: DartTesting\n\ndev_dependencies:\n test:"
},
{
"code": null,
"e": 882,
"s": 842,
"text": "Then we’ve to run the following command"
},
{
"code": null,
"e": 895,
"s": 882,
"text": "dart pub get"
},
{
"code": null,
"e": 1006,
"s": 895,
"text": "This will initialize a project with the name DartTesting and also install the test package as a dev dependency"
},
{
"code": null,
"e": 1110,
"s": 1006,
"text": "Next, we can create a main.dart file which will contain all our code and import the test package there."
},
{
"code": null,
"e": 1143,
"s": 1110,
"text": "import 'package:test/test.dart';"
},
{
"code": null,
"e": 1298,
"s": 1143,
"text": "First, we’ve to write a simple function on which we can run our tests. Provided below is the code for calculating the sum of all the elements of an array."
},
{
"code": null,
"e": 1303,
"s": 1298,
"text": "Dart"
},
{
"code": "// Get sum of all elements of an arrayint getSumOfArray(List<int> arr) { int res = 0; for (var i=0; i<arr.length; i++) { res += arr[i]; } return res;}",
"e": 1461,
"s": 1303,
"text": null
},
{
"code": null,
"e": 1565,
"s": 1461,
"text": "A unit test can be written for the above function by using the test() function. It takes in 2 Arguments"
},
{
"code": null,
"e": 1947,
"s": 1565,
"text": "A string value containing a description of the unit testA test assertion by using the expect() function. The expect() function has to be provided with 2 values:Expected Value, which is provided manually by the developer.Actual Value, which is obtained by running the concerned functionIf these values match, then the Unit Test is successful, or else it is considered to be failing."
},
{
"code": null,
"e": 2004,
"s": 1947,
"text": "A string value containing a description of the unit test"
},
{
"code": null,
"e": 2330,
"s": 2004,
"text": "A test assertion by using the expect() function. The expect() function has to be provided with 2 values:Expected Value, which is provided manually by the developer.Actual Value, which is obtained by running the concerned functionIf these values match, then the Unit Test is successful, or else it is considered to be failing."
},
{
"code": null,
"e": 2391,
"s": 2330,
"text": "Expected Value, which is provided manually by the developer."
},
{
"code": null,
"e": 2457,
"s": 2391,
"text": "Actual Value, which is obtained by running the concerned function"
},
{
"code": null,
"e": 2554,
"s": 2457,
"text": "If these values match, then the Unit Test is successful, or else it is considered to be failing."
},
{
"code": null,
"e": 2699,
"s": 2554,
"text": "Provided below is the code for a unit test for getSumOfArray() function. Since the expected and actual values match, it’ll be a successful test."
},
{
"code": null,
"e": 2704,
"s": 2699,
"text": "Dart"
},
{
"code": "main() { // Successful test for sum of array test('Get sum of array - success', () { int expectedValue = 15; int actualValue = getSumOfArray([1, 2, 3, 4, 5]); expect(expectedValue, actualValue); });}",
"e": 2920,
"s": 2704,
"text": null
},
{
"code": null,
"e": 2927,
"s": 2920,
"text": "Output"
},
{
"code": null,
"e": 3001,
"s": 2927,
"text": "00:00 +0: Get sum of array - success\n\n00:00 +1: All tests passed!\n\nExited"
},
{
"code": null,
"e": 3103,
"s": 3001,
"text": "In this case, the expected value is different from the actual value, due to which the test will fail."
},
{
"code": null,
"e": 3108,
"s": 3103,
"text": "Dart"
},
{
"code": "main() { // Unsuccessful test for sum of array test('Get sum of array - failure', () { int expectedValue = 40; int actualValue = getSumOfArray([1, 2, 3, 4, 5]); expect(expectedValue, actualValue); });}",
"e": 3325,
"s": 3108,
"text": null
},
{
"code": null,
"e": 3332,
"s": 3325,
"text": "Output"
},
{
"code": null,
"e": 3449,
"s": 3332,
"text": "00:00 +0: Get sum of array - failure\n\n00:00 +0 -1: Get sum of array - failure [E]\n\n Expected: <15>\n Actual: <40>"
},
{
"code": null,
"e": 3465,
"s": 3449,
"text": "Dart-Collection"
},
{
"code": null,
"e": 3472,
"s": 3465,
"text": "Picked"
},
{
"code": null,
"e": 3477,
"s": 3472,
"text": "Dart"
}
] |
PHP | current() Function
|
14 Feb, 2022
The current() function is an inbuilt function in PHP.
It is used to return the value of the element in an array which the internal pointer is currently pointing to.
The current() function does not increment or decrement the internal pointer after returning the value.
In PHP, all arrays have an internal pointer. This internal pointer points to some element in that array which is called as the current element of the array.
Usually, the current element is the first inserted element in the array.
Syntax:
current($array)
Parameters: The current() function accepts a single parameter $array. It is the array of which we want to find the current element.
Return Values: It returns the value of the element in the array which the internal pointer is currently pointing to. If the array is empty then the current() function returns FALSE.
Examples:
Input : current(array("John", "b", "c", "d"))
Output : John
Explanation : Here as we see that input array contains
many elements and the output is "John" because first
element is John and current() function returns
the element to which internal pointer is currently
pointing.
Input: current(array("abc", "123", "7"))
Output: abc
Below programs illustrate the current() function in PHP:
Program 1:
PHP
<?php // input array$arr = array("Ram", "Shita", "Geeta"); // Here current function returns the// first element of the array.echo current($a); ?>
Output:
Ram
Program 2:
PHP
<?php $arr = array('Sham', 'Mac', 'Jhon', 'Adwin'); // Here current element is Sham.echo current($arr)."\n"; // increment internal pointer to point// to next element i.e, Macecho next($arr)."\n"; // printing the current element as// for now current element is Mac.echo current($arr)."\n"; // increment internal pointer to point// to next element i.e, Jhon.echo next($arr)."\n"; // increment internal pointer to point// to next element i.e, Adwin.echo next($arr)."\n"; // printing the current element as for// now current element is Adwin.echo current($arr)."\n"; ?>
Output:
Sham
Mac
Mac
Jhon
Adwin
Adwin
Note: The current() function returns False when array is empty i.e, do not contain any elements, and also it returns false when internal pointer go out of the bound i.e beyond the end of the last element.
Reference: http://php.net/manual/en/function.current.php
Akanksha_Rai
arorakashish0911
varshagumber28
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Feb, 2022"
},
{
"code": null,
"e": 82,
"s": 28,
"text": "The current() function is an inbuilt function in PHP."
},
{
"code": null,
"e": 193,
"s": 82,
"text": "It is used to return the value of the element in an array which the internal pointer is currently pointing to."
},
{
"code": null,
"e": 296,
"s": 193,
"text": "The current() function does not increment or decrement the internal pointer after returning the value."
},
{
"code": null,
"e": 453,
"s": 296,
"text": "In PHP, all arrays have an internal pointer. This internal pointer points to some element in that array which is called as the current element of the array."
},
{
"code": null,
"e": 526,
"s": 453,
"text": "Usually, the current element is the first inserted element in the array."
},
{
"code": null,
"e": 535,
"s": 526,
"text": "Syntax: "
},
{
"code": null,
"e": 551,
"s": 535,
"text": "current($array)"
},
{
"code": null,
"e": 683,
"s": 551,
"text": "Parameters: The current() function accepts a single parameter $array. It is the array of which we want to find the current element."
},
{
"code": null,
"e": 865,
"s": 683,
"text": "Return Values: It returns the value of the element in the array which the internal pointer is currently pointing to. If the array is empty then the current() function returns FALSE."
},
{
"code": null,
"e": 877,
"s": 865,
"text": "Examples: "
},
{
"code": null,
"e": 1210,
"s": 877,
"text": "Input : current(array(\"John\", \"b\", \"c\", \"d\"))\nOutput : John\nExplanation : Here as we see that input array contains \nmany elements and the output is \"John\" because first \nelement is John and current() function returns \nthe element to which internal pointer is currently\npointing.\n\nInput: current(array(\"abc\", \"123\", \"7\"))\nOutput: abc"
},
{
"code": null,
"e": 1267,
"s": 1210,
"text": "Below programs illustrate the current() function in PHP:"
},
{
"code": null,
"e": 1279,
"s": 1267,
"text": "Program 1: "
},
{
"code": null,
"e": 1283,
"s": 1279,
"text": "PHP"
},
{
"code": "<?php // input array$arr = array(\"Ram\", \"Shita\", \"Geeta\"); // Here current function returns the// first element of the array.echo current($a); ?>",
"e": 1430,
"s": 1283,
"text": null
},
{
"code": null,
"e": 1439,
"s": 1430,
"text": "Output: "
},
{
"code": null,
"e": 1443,
"s": 1439,
"text": "Ram"
},
{
"code": null,
"e": 1455,
"s": 1443,
"text": "Program 2: "
},
{
"code": null,
"e": 1459,
"s": 1455,
"text": "PHP"
},
{
"code": "<?php $arr = array('Sham', 'Mac', 'Jhon', 'Adwin'); // Here current element is Sham.echo current($arr).\"\\n\"; // increment internal pointer to point// to next element i.e, Macecho next($arr).\"\\n\"; // printing the current element as// for now current element is Mac.echo current($arr).\"\\n\"; // increment internal pointer to point// to next element i.e, Jhon.echo next($arr).\"\\n\"; // increment internal pointer to point// to next element i.e, Adwin.echo next($arr).\"\\n\"; // printing the current element as for// now current element is Adwin.echo current($arr).\"\\n\"; ?>",
"e": 2025,
"s": 1459,
"text": null
},
{
"code": null,
"e": 2034,
"s": 2025,
"text": "Output: "
},
{
"code": null,
"e": 2064,
"s": 2034,
"text": "Sham\nMac\nMac\nJhon\nAdwin\nAdwin"
},
{
"code": null,
"e": 2269,
"s": 2064,
"text": "Note: The current() function returns False when array is empty i.e, do not contain any elements, and also it returns false when internal pointer go out of the bound i.e beyond the end of the last element."
},
{
"code": null,
"e": 2327,
"s": 2269,
"text": "Reference: http://php.net/manual/en/function.current.php "
},
{
"code": null,
"e": 2340,
"s": 2327,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2357,
"s": 2340,
"text": "arorakashish0911"
},
{
"code": null,
"e": 2372,
"s": 2357,
"text": "varshagumber28"
},
{
"code": null,
"e": 2382,
"s": 2372,
"text": "PHP-array"
},
{
"code": null,
"e": 2395,
"s": 2382,
"text": "PHP-function"
},
{
"code": null,
"e": 2399,
"s": 2395,
"text": "PHP"
},
{
"code": null,
"e": 2416,
"s": 2399,
"text": "Web Technologies"
},
{
"code": null,
"e": 2420,
"s": 2416,
"text": "PHP"
}
] |
killall Command in Linux with Examples
|
02 Nov, 2020
Have you ever confronted the circumstance where you executed a program or an application, and abruptly while you are utilizing the application, it gets halted and starts to crash? You attempt to begin the application again, yet nothing happens on the grounds that the first application measure never genuinely closes down totally. The arrangement is to end the application cycle. Fortunately, there are a few utilities in Linux that permits you to execute the kill process.
It is recommended to read kill Command before proceeding further.
The primary contrast between the kill and killall command is that the “kill” ends process cycles dependent on Process ID number (PID), while the killall orders end running cycles dependent on their names and different attributes. Normal users can end/kill their own cycles(processes), however not those that have a place with different users, while the root client can end all cycles.
The ionice device acknowledges the accompanying alternatives:
Tag
Description
To know the contrast among kill and killall orders we first need to ensure that we comprehend the nuts and bolts behind cycles on the Linux OS. The process is an occurrence of a running system. Each process cycle is allotted PID ( Process ID ) which is remarkable for each cycle and in this way, no two cycles can be allocated the same PID. When the cycle is ended the PID is accessible for reuse.
General Syntax:
killall [ -Z CONTEXT ] [ -u USER ] [ -y TIME ] [ -o TIME ] [ -eIgiqrvw ] [ -s SIGNAL | -SIGNAL ] NAME...
1. The command below will begin the process yes and yield its standard output to/dev/null. What we are keen on here, is the second line which contains the accompanying data “[1]” ( work ID ) and “16017” the real PID. On your Linux OS, you can run numerous cycles at some random time and each cycle, contingent upon the client benefits can be ended utilizing either kill or killall orders.
$ yes > /dev/null &
$ jobs
3. The contrast between kill versus killall commands is that with kill order we can end just a solitary cycle at that point, though with killall order we can end numerous cycles dependent on given models, for example, process group, process age, or client privilege. Now, we will use “kill” command to terminate the process with PID “16022”:
$ sudo kill 16022
Now, from the above command, we have terminated the process with PID 16022, and it was processed no. [4]. We can also verify the command execution by giving the “jobs” command:
4. Ending each cycle individually can end up being hard and repetitive work. We should see whether we can get some assistance by utilizing killall order and process cycle name:
$ sudo killall yes
Now, we can easily observe that all processes running under the name “yes” have been terminated successfully.
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Nov, 2020"
},
{
"code": null,
"e": 528,
"s": 54,
"text": "Have you ever confronted the circumstance where you executed a program or an application, and abruptly while you are utilizing the application, it gets halted and starts to crash? You attempt to begin the application again, yet nothing happens on the grounds that the first application measure never genuinely closes down totally. The arrangement is to end the application cycle. Fortunately, there are a few utilities in Linux that permits you to execute the kill process."
},
{
"code": null,
"e": 594,
"s": 528,
"text": "It is recommended to read kill Command before proceeding further."
},
{
"code": null,
"e": 979,
"s": 594,
"text": "The primary contrast between the kill and killall command is that the “kill” ends process cycles dependent on Process ID number (PID), while the killall orders end running cycles dependent on their names and different attributes. Normal users can end/kill their own cycles(processes), however not those that have a place with different users, while the root client can end all cycles."
},
{
"code": null,
"e": 1041,
"s": 979,
"text": "The ionice device acknowledges the accompanying alternatives:"
},
{
"code": null,
"e": 1045,
"s": 1041,
"text": "Tag"
},
{
"code": null,
"e": 1057,
"s": 1045,
"text": "Description"
},
{
"code": null,
"e": 1456,
"s": 1057,
"text": "To know the contrast among kill and killall orders we first need to ensure that we comprehend the nuts and bolts behind cycles on the Linux OS. The process is an occurrence of a running system. Each process cycle is allotted PID ( Process ID ) which is remarkable for each cycle and in this way, no two cycles can be allocated the same PID. When the cycle is ended the PID is accessible for reuse. "
},
{
"code": null,
"e": 1472,
"s": 1456,
"text": "General Syntax:"
},
{
"code": null,
"e": 1578,
"s": 1472,
"text": "killall [ -Z CONTEXT ] [ -u USER ] [ -y TIME ] [ -o TIME ] [ -eIgiqrvw ] [ -s SIGNAL | -SIGNAL ] NAME...\n"
},
{
"code": null,
"e": 1967,
"s": 1578,
"text": "1. The command below will begin the process yes and yield its standard output to/dev/null. What we are keen on here, is the second line which contains the accompanying data “[1]” ( work ID ) and “16017” the real PID. On your Linux OS, you can run numerous cycles at some random time and each cycle, contingent upon the client benefits can be ended utilizing either kill or killall orders."
},
{
"code": null,
"e": 1988,
"s": 1967,
"text": "$ yes > /dev/null &\n"
},
{
"code": null,
"e": 1996,
"s": 1988,
"text": "$ jobs\n"
},
{
"code": null,
"e": 2338,
"s": 1996,
"text": "3. The contrast between kill versus killall commands is that with kill order we can end just a solitary cycle at that point, though with killall order we can end numerous cycles dependent on given models, for example, process group, process age, or client privilege. Now, we will use “kill” command to terminate the process with PID “16022”:"
},
{
"code": null,
"e": 2357,
"s": 2338,
"text": "$ sudo kill 16022\n"
},
{
"code": null,
"e": 2534,
"s": 2357,
"text": "Now, from the above command, we have terminated the process with PID 16022, and it was processed no. [4]. We can also verify the command execution by giving the “jobs” command:"
},
{
"code": null,
"e": 2711,
"s": 2534,
"text": "4. Ending each cycle individually can end up being hard and repetitive work. We should see whether we can get some assistance by utilizing killall order and process cycle name:"
},
{
"code": null,
"e": 2731,
"s": 2711,
"text": "$ sudo killall yes\n"
},
{
"code": null,
"e": 2841,
"s": 2731,
"text": "Now, we can easily observe that all processes running under the name “yes” have been terminated successfully."
},
{
"code": null,
"e": 2855,
"s": 2841,
"text": "linux-command"
},
{
"code": null,
"e": 2877,
"s": 2855,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 2888,
"s": 2877,
"text": "Linux-Unix"
}
] |
Delete array element in given index range [L – R]
|
03 Jun, 2021
Given an array A[] and size of an array is N. The task is to delete elements of array A[] are in given range L to R both are exclusive.Examples:
Input : N = 12
A[] = { 3, 5, 3, 4, 9, 3, 1, 6, 3, 11, 12, 3}
L = 2
R = 7
Output : 3 5 3 6 3 11 12 3
since A[2] = 3 but this is exclude
A[7] = 6 this also exclude
Input : N = 10
A[] ={ 5, 8, 11, 15, 26, 14, 19, 17, 10, 14 }
L = 4
R = 6
Output :5 8 11 15 26 19 17 10 14
A naive approach is to delete elements in range L to R with extra space.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ code to delete element// in given range#include <bits/stdc++.h>using namespace std; // Delete L to R elementvector<int> deleteElement(int A[], int L, int R, int N){ vector<int> B; for (int i = 0; i < N; i++) if (i <= L || i >= R) B.push_back(A[i]); return B;} // main Driverint main(){ int A[] = { 3, 5, 3, 4, 9, 3, 1, 6, 3, 11, 12, 3 }; int L = 2, R = 7; int n = sizeof(A) / sizeof(A[0]); vector<int> res = deleteElement(A, L, R, n); for (auto x : res) cout << x << " "; return 0;}
import java.util.Vector; // Java code to delete element// in given rangeclass GFG {// Delete L to R element static Vector<Integer> deleteElement(int A[], int L, int R, int N) { Vector<Integer> B = new Vector<>(); for (int i = 0; i < N; i++) { if (i <= L || i >= R) { B.add(A[i]); } } return B; } // main Driver public static void main(String[] args) { int A[] = {3, 5, 3, 4, 9, 3, 1, 6, 3, 11, 12, 3}; int L = 2, R = 7; int n = A.length; Vector<Integer> res = deleteElement(A, L, R, n); for (Integer x : res) { System.out.print(x + " "); } }}// This code is contributed by PrinciRaj1992
# Python 3 code to delete element# in given range # Delete L to R elementdef deleteElement(A, L, R, N): B = [] for i in range(0, N, 1): if (i <= L or i >= R): B.append(A[i]) return B # Driver Codeif __name__ == '__main__': A = [3, 5, 3, 4, 9, 3, 1, 6, 3, 11, 12, 3] L = 2 R = 7 n = len(A) res = deleteElement(A, L, R, n) for i in range(len(res)): print(res[i], end = " ") # THis code is implemented by# Surendra_Gangwar
// C# code to delete element// in given rangeusing System;using System.Collections.Generic; class GFG{ // Delete L to R element static List<int> deleteElement(int []A, int L, int R, int N) { List<int> B = new List<int>(); for (int i = 0; i < N; i++) { if (i <= L || i >= R) { B.Add(A[i]); } } return B; } // Driver code public static void Main() { int []A = {3, 5, 3, 4, 9, 3, 1, 6, 3, 11, 12, 3}; int L = 2, R = 7; int n = A.Length; List<int> res = deleteElement(A, L, R, n); foreach (int x in res) { Console.Write(x + " "); } }} // This code is contributed by Rajput-Ji
<?php// PHP code to delete element// in given range // Delete L to R elementfunction deleteElement($A, $L, $R, $N){ $B = array(); for ($i = 0; $i < $N; $i++) { if ($i <= $L or $i >= $R) $B[] = $A[$i]; } return $B;} // Driver Code$A = array(3, 5, 3, 4, 9, 3, 1, 6, 3, 11, 12, 3);$L = 2;$R = 7;$n = count($A);$res = deleteElement($A, $L, $R, $n);for ($i = 0; $i < count($res); $i++)echo "$res[$i] "; // This code is implemented by// Srathore?>
<script> // Javascript code to delete element in given range function deleteElement(A, L, R, N) { let B = []; for (let i = 0; i < N; i++) { if (i <= L || i >= R) { B.push(A[i]); } } return B; } let A = [3, 5, 3, 4, 9, 3, 1, 6, 3, 11, 12, 3]; let L = 2, R = 7; let n = A.length; let res = deleteElement(A, L, R, n); for(let i = 0; i < res.length; i++) document.write(res[i] + " "); // This code is contributed by divyeshrabadiya07.</script>
3 5 3 6 3 11 12 3
Time Complexity: O(n) Auxiliary Space : O(n)An efficient solution without using extra space. Below is the implementation of the above approach:
C++
Java
Python 3
C#
PHP
Javascript
// C++ code to delete element// in given range#include <bits/stdc++.h>using namespace std; // Delete L to R elementsint deleteElement(int A[], int L, int R, int N){ int i, j = 0; for (i = 0; i < N; i++) { if (i <= L || i >= R) { A[j] = A[i]; j++; } } // Return size of Array // after delete element return j;} // main Driverint main(){ int A[] = { 5, 8, 11, 15, 26, 14, 19, 17, 10, 14 }; int L = 2, R = 7; int n = sizeof(A) / sizeof(A[0]); int res_size = deleteElement(A, L, R, n); for (int i = 0; i < res_size; i++) cout << A[i] << " "; return 0;}
// Java code to delete element// in given rangeclass GFG{ // Delete L to R elementsstatic int deleteElement(int A[], int L, int R, int N){ int i, j = 0; for (i = 0; i < N; i++) { if (i <= L || i >= R) { A[j] = A[i]; j++; } } // Return size of Array // after delete element return j;} // Driver Codepublic static void main(String args[]){ int A[] = new int[] { 5, 8, 11, 15, 26, 14, 19, 17, 10, 14 }; int L = 2, R = 7; int n = A.length; int res_size = deleteElement(A, L, R, n); for (int i = 0; i < res_size; i++) System.out.print(A[i] + " ");}} // This code is contributed// by Kirti_Mangal
# Python 3 program to delete element# in given range # Function to delete L to R elementdef deleteElement(A, L, R, N) : j = 0 for i in range(N) : if i <= L or i >= R : A[j] = A[i] j += 1 # Return size of Array # after delete element return j # Driver Codeif __name__ == "__main__" : A = [5, 8, 11, 15, 26, 14, 19, 17, 10, 14] L, R = 2,7 n = len(A) res_size = deleteElement(A, L, R, n) for i in range(res_size) : print(A[i],end = " ") # This code is contributed by ANKITRAI1
// C# code to delete element// in given rangeusing System; class GFG{ // Delete L to R elementsstatic int deleteElement(int []A, int L, int R, int N){ int i, j = 0; for (i = 0; i < N; i++) { if (i <= L || i >= R) { A[j] = A[i]; j++; } } // Return size of Array // after delete element return j;} // Driver Codepublic static void Main(){ int []A = new int[] { 5, 8, 11, 15, 26, 14, 19, 17, 10, 14 }; int L = 2, R = 7; int n = A.Length; int res_size = deleteElement(A, L, R, n); for (int i = 0; i < res_size; i++) Console.Write(A[i] + " ");}} // This code is contributed by 29AjayKumar
<?php// PHP code to delete element// in given range // Delete L to R elementsfunction deleteElement(&$A, $L, $R, $N){ $i= 0; $j = 0; for ($i = 0; $i < $N; $i++) { if ($i <= $L || $i >= $R) { $A[$j] = $A[$i]; $j++; } } // Return size of Array // after delete element return $j;} // Driver Code$A = array(5, 8, 11, 15, 26, 14, 19, 17, 10, 14);$L = 2;$R = 7;$n = sizeof($A);$res_size = deleteElement($A, $L, $R, $n);for ($i = 0; $i < $res_size; $i++){ echo ($A[$i]); echo (" ");} // This code is contributed// by Shivi_Aggarwal?>
<script> // JavaScript code to delete element in given range // Delete L to R elements function deleteElement(A, L, R, N) { let i, j = 0; for (i = 0; i < N; i++) { if (i <= L || i >= R) { A[j] = A[i]; j++; } } // Return size of Array // after delete element return j; } let A = [ 5, 8, 11, 15, 26, 14, 19, 17, 10, 14 ]; let L = 2, R = 7; let n = A.length; let res_size = deleteElement(A, L, R, n); for (let i = 0; i < res_size; i++) document.write(A[i] + " "); </script>
5 8 11 17 10 14
Time Complexity: O(n) Auxiliary Space : O(1)
Kirti_Mangal
ankthon
Shivi_Aggarwal
29AjayKumar
SURENDRA_GANGWAR
princiraj1992
Rajput-Ji
princi singh
divyesh072019
divyeshrabadiya07
cpp-vector
Arrays
Searching
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 201,
"s": 54,
"text": "Given an array A[] and size of an array is N. The task is to delete elements of array A[] are in given range L to R both are exclusive.Examples: "
},
{
"code": null,
"e": 523,
"s": 201,
"text": "Input : N = 12\n A[] = { 3, 5, 3, 4, 9, 3, 1, 6, 3, 11, 12, 3}\n L = 2\n R = 7\nOutput : 3 5 3 6 3 11 12 3 \nsince A[2] = 3 but this is exclude \nA[7] = 6 this also exclude \n\nInput : N = 10\n A[] ={ 5, 8, 11, 15, 26, 14, 19, 17, 10, 14 }\n L = 4\n R = 6\nOutput :5 8 11 15 26 19 17 10 14 "
},
{
"code": null,
"e": 650,
"s": 525,
"text": "A naive approach is to delete elements in range L to R with extra space.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 654,
"s": 650,
"text": "C++"
},
{
"code": null,
"e": 659,
"s": 654,
"text": "Java"
},
{
"code": null,
"e": 667,
"s": 659,
"text": "Python3"
},
{
"code": null,
"e": 670,
"s": 667,
"text": "C#"
},
{
"code": null,
"e": 674,
"s": 670,
"text": "PHP"
},
{
"code": null,
"e": 685,
"s": 674,
"text": "Javascript"
},
{
"code": "// C++ code to delete element// in given range#include <bits/stdc++.h>using namespace std; // Delete L to R elementvector<int> deleteElement(int A[], int L, int R, int N){ vector<int> B; for (int i = 0; i < N; i++) if (i <= L || i >= R) B.push_back(A[i]); return B;} // main Driverint main(){ int A[] = { 3, 5, 3, 4, 9, 3, 1, 6, 3, 11, 12, 3 }; int L = 2, R = 7; int n = sizeof(A) / sizeof(A[0]); vector<int> res = deleteElement(A, L, R, n); for (auto x : res) cout << x << \" \"; return 0;}",
"e": 1239,
"s": 685,
"text": null
},
{
"code": "import java.util.Vector; // Java code to delete element// in given rangeclass GFG {// Delete L to R element static Vector<Integer> deleteElement(int A[], int L, int R, int N) { Vector<Integer> B = new Vector<>(); for (int i = 0; i < N; i++) { if (i <= L || i >= R) { B.add(A[i]); } } return B; } // main Driver public static void main(String[] args) { int A[] = {3, 5, 3, 4, 9, 3, 1, 6, 3, 11, 12, 3}; int L = 2, R = 7; int n = A.length; Vector<Integer> res = deleteElement(A, L, R, n); for (Integer x : res) { System.out.print(x + \" \"); } }}// This code is contributed by PrinciRaj1992",
"e": 1959,
"s": 1239,
"text": null
},
{
"code": "# Python 3 code to delete element# in given range # Delete L to R elementdef deleteElement(A, L, R, N): B = [] for i in range(0, N, 1): if (i <= L or i >= R): B.append(A[i]) return B # Driver Codeif __name__ == '__main__': A = [3, 5, 3, 4, 9, 3, 1, 6, 3, 11, 12, 3] L = 2 R = 7 n = len(A) res = deleteElement(A, L, R, n) for i in range(len(res)): print(res[i], end = \" \") # THis code is implemented by# Surendra_Gangwar",
"e": 2449,
"s": 1959,
"text": null
},
{
"code": "// C# code to delete element// in given rangeusing System;using System.Collections.Generic; class GFG{ // Delete L to R element static List<int> deleteElement(int []A, int L, int R, int N) { List<int> B = new List<int>(); for (int i = 0; i < N; i++) { if (i <= L || i >= R) { B.Add(A[i]); } } return B; } // Driver code public static void Main() { int []A = {3, 5, 3, 4, 9, 3, 1, 6, 3, 11, 12, 3}; int L = 2, R = 7; int n = A.Length; List<int> res = deleteElement(A, L, R, n); foreach (int x in res) { Console.Write(x + \" \"); } }} // This code is contributed by Rajput-Ji",
"e": 3244,
"s": 2449,
"text": null
},
{
"code": "<?php// PHP code to delete element// in given range // Delete L to R elementfunction deleteElement($A, $L, $R, $N){ $B = array(); for ($i = 0; $i < $N; $i++) { if ($i <= $L or $i >= $R) $B[] = $A[$i]; } return $B;} // Driver Code$A = array(3, 5, 3, 4, 9, 3, 1, 6, 3, 11, 12, 3);$L = 2;$R = 7;$n = count($A);$res = deleteElement($A, $L, $R, $n);for ($i = 0; $i < count($res); $i++)echo \"$res[$i] \"; // This code is implemented by// Srathore?>",
"e": 3733,
"s": 3244,
"text": null
},
{
"code": "<script> // Javascript code to delete element in given range function deleteElement(A, L, R, N) { let B = []; for (let i = 0; i < N; i++) { if (i <= L || i >= R) { B.push(A[i]); } } return B; } let A = [3, 5, 3, 4, 9, 3, 1, 6, 3, 11, 12, 3]; let L = 2, R = 7; let n = A.length; let res = deleteElement(A, L, R, n); for(let i = 0; i < res.length; i++) document.write(res[i] + \" \"); // This code is contributed by divyeshrabadiya07.</script>",
"e": 4281,
"s": 3733,
"text": null
},
{
"code": null,
"e": 4299,
"s": 4281,
"text": "3 5 3 6 3 11 12 3"
},
{
"code": null,
"e": 4446,
"s": 4301,
"text": "Time Complexity: O(n) Auxiliary Space : O(n)An efficient solution without using extra space. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 4450,
"s": 4446,
"text": "C++"
},
{
"code": null,
"e": 4455,
"s": 4450,
"text": "Java"
},
{
"code": null,
"e": 4464,
"s": 4455,
"text": "Python 3"
},
{
"code": null,
"e": 4467,
"s": 4464,
"text": "C#"
},
{
"code": null,
"e": 4471,
"s": 4467,
"text": "PHP"
},
{
"code": null,
"e": 4482,
"s": 4471,
"text": "Javascript"
},
{
"code": "// C++ code to delete element// in given range#include <bits/stdc++.h>using namespace std; // Delete L to R elementsint deleteElement(int A[], int L, int R, int N){ int i, j = 0; for (i = 0; i < N; i++) { if (i <= L || i >= R) { A[j] = A[i]; j++; } } // Return size of Array // after delete element return j;} // main Driverint main(){ int A[] = { 5, 8, 11, 15, 26, 14, 19, 17, 10, 14 }; int L = 2, R = 7; int n = sizeof(A) / sizeof(A[0]); int res_size = deleteElement(A, L, R, n); for (int i = 0; i < res_size; i++) cout << A[i] << \" \"; return 0;}",
"e": 5111,
"s": 4482,
"text": null
},
{
"code": "// Java code to delete element// in given rangeclass GFG{ // Delete L to R elementsstatic int deleteElement(int A[], int L, int R, int N){ int i, j = 0; for (i = 0; i < N; i++) { if (i <= L || i >= R) { A[j] = A[i]; j++; } } // Return size of Array // after delete element return j;} // Driver Codepublic static void main(String args[]){ int A[] = new int[] { 5, 8, 11, 15, 26, 14, 19, 17, 10, 14 }; int L = 2, R = 7; int n = A.length; int res_size = deleteElement(A, L, R, n); for (int i = 0; i < res_size; i++) System.out.print(A[i] + \" \");}} // This code is contributed// by Kirti_Mangal",
"e": 5832,
"s": 5111,
"text": null
},
{
"code": "# Python 3 program to delete element# in given range # Function to delete L to R elementdef deleteElement(A, L, R, N) : j = 0 for i in range(N) : if i <= L or i >= R : A[j] = A[i] j += 1 # Return size of Array # after delete element return j # Driver Codeif __name__ == \"__main__\" : A = [5, 8, 11, 15, 26, 14, 19, 17, 10, 14] L, R = 2,7 n = len(A) res_size = deleteElement(A, L, R, n) for i in range(res_size) : print(A[i],end = \" \") # This code is contributed by ANKITRAI1",
"e": 6382,
"s": 5832,
"text": null
},
{
"code": "// C# code to delete element// in given rangeusing System; class GFG{ // Delete L to R elementsstatic int deleteElement(int []A, int L, int R, int N){ int i, j = 0; for (i = 0; i < N; i++) { if (i <= L || i >= R) { A[j] = A[i]; j++; } } // Return size of Array // after delete element return j;} // Driver Codepublic static void Main(){ int []A = new int[] { 5, 8, 11, 15, 26, 14, 19, 17, 10, 14 }; int L = 2, R = 7; int n = A.Length; int res_size = deleteElement(A, L, R, n); for (int i = 0; i < res_size; i++) Console.Write(A[i] + \" \");}} // This code is contributed by 29AjayKumar",
"e": 7101,
"s": 6382,
"text": null
},
{
"code": "<?php// PHP code to delete element// in given range // Delete L to R elementsfunction deleteElement(&$A, $L, $R, $N){ $i= 0; $j = 0; for ($i = 0; $i < $N; $i++) { if ($i <= $L || $i >= $R) { $A[$j] = $A[$i]; $j++; } } // Return size of Array // after delete element return $j;} // Driver Code$A = array(5, 8, 11, 15, 26, 14, 19, 17, 10, 14);$L = 2;$R = 7;$n = sizeof($A);$res_size = deleteElement($A, $L, $R, $n);for ($i = 0; $i < $res_size; $i++){ echo ($A[$i]); echo (\" \");} // This code is contributed// by Shivi_Aggarwal?>",
"e": 7712,
"s": 7101,
"text": null
},
{
"code": "<script> // JavaScript code to delete element in given range // Delete L to R elements function deleteElement(A, L, R, N) { let i, j = 0; for (i = 0; i < N; i++) { if (i <= L || i >= R) { A[j] = A[i]; j++; } } // Return size of Array // after delete element return j; } let A = [ 5, 8, 11, 15, 26, 14, 19, 17, 10, 14 ]; let L = 2, R = 7; let n = A.length; let res_size = deleteElement(A, L, R, n); for (let i = 0; i < res_size; i++) document.write(A[i] + \" \"); </script>",
"e": 8326,
"s": 7712,
"text": null
},
{
"code": null,
"e": 8342,
"s": 8326,
"text": "5 8 11 17 10 14"
},
{
"code": null,
"e": 8390,
"s": 8344,
"text": "Time Complexity: O(n) Auxiliary Space : O(1) "
},
{
"code": null,
"e": 8403,
"s": 8390,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 8411,
"s": 8403,
"text": "ankthon"
},
{
"code": null,
"e": 8426,
"s": 8411,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 8438,
"s": 8426,
"text": "29AjayKumar"
},
{
"code": null,
"e": 8455,
"s": 8438,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 8469,
"s": 8455,
"text": "princiraj1992"
},
{
"code": null,
"e": 8479,
"s": 8469,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 8492,
"s": 8479,
"text": "princi singh"
},
{
"code": null,
"e": 8506,
"s": 8492,
"text": "divyesh072019"
},
{
"code": null,
"e": 8524,
"s": 8506,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 8535,
"s": 8524,
"text": "cpp-vector"
},
{
"code": null,
"e": 8542,
"s": 8535,
"text": "Arrays"
},
{
"code": null,
"e": 8552,
"s": 8542,
"text": "Searching"
},
{
"code": null,
"e": 8559,
"s": 8552,
"text": "Arrays"
},
{
"code": null,
"e": 8569,
"s": 8559,
"text": "Searching"
}
] |
C# Program to Get Current Stack Trace Information Using Environment Class
|
21 Nov, 2021
In C#, Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that it retrieves command-line arguments information, exit codes information, environment variable settings information, contents of the call stack information, and time since the last system boot in milliseconds information. By just using some predefined methods we can get the information of the Operating System using the Environment class. Here in this article, we are using the StackTrace property to get the current stack trace information. This property is used to get the current stack trace information
Syntax:
string Environment.StackTrace
Return: string and gives the class name along with id
Example 1:
C#
// C# program to find the current stack trace informationusing System; class GFG{ static public void Main(){ // Define the variable with string string my_variable = "Hello Geeks"; // Get the current stack trace details // Using StackTrace property my_variable = Environment.StackTrace; Console.WriteLine("Information of current stack trace: \n" + my_variable);}}
Output:
Current Stack Trace Details:
at System.Environment.get_StackTrace () [0x00000] in <a1ae6166591d4020b810288d19af38d4>:0
at GFG.Main () [0x00000] in <ec0c23afce674aedba9f00d218402cf6>:0
Example 2:
C#
// C# program to find the current stack trace informationusing System; class GFG{ static public void Main(){ // Define the variable with integer string my_variable = "58"; // Get the current stack trace details // Using StackTrace property my_variable = Environment.StackTrace; Console.WriteLine("Information of current stack trace: \n" + my_variable);}}
Output:
Current Stack Trace Details:
at System.Environment.get_StackTrace () [0x00000] in <a1ae6166591d4020b810288d19af38d4>:0
at GFG.Main () [0x00000] in <092e5ea1577d4af6be34040e9472afab>:0
simmytarika5
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Nov, 2021"
},
{
"code": null,
"e": 763,
"s": 28,
"text": "In C#, Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that it retrieves command-line arguments information, exit codes information, environment variable settings information, contents of the call stack information, and time since the last system boot in milliseconds information. By just using some predefined methods we can get the information of the Operating System using the Environment class. Here in this article, we are using the StackTrace property to get the current stack trace information. This property is used to get the current stack trace information"
},
{
"code": null,
"e": 771,
"s": 763,
"text": "Syntax:"
},
{
"code": null,
"e": 801,
"s": 771,
"text": "string Environment.StackTrace"
},
{
"code": null,
"e": 856,
"s": 801,
"text": "Return: string and gives the class name along with id "
},
{
"code": null,
"e": 867,
"s": 856,
"text": "Example 1:"
},
{
"code": null,
"e": 870,
"s": 867,
"text": "C#"
},
{
"code": "// C# program to find the current stack trace informationusing System; class GFG{ static public void Main(){ // Define the variable with string string my_variable = \"Hello Geeks\"; // Get the current stack trace details // Using StackTrace property my_variable = Environment.StackTrace; Console.WriteLine(\"Information of current stack trace: \\n\" + my_variable);}}",
"e": 1278,
"s": 870,
"text": null
},
{
"code": null,
"e": 1286,
"s": 1278,
"text": "Output:"
},
{
"code": null,
"e": 1476,
"s": 1286,
"text": "Current Stack Trace Details: \n at System.Environment.get_StackTrace () [0x00000] in <a1ae6166591d4020b810288d19af38d4>:0 \n at GFG.Main () [0x00000] in <ec0c23afce674aedba9f00d218402cf6>:0"
},
{
"code": null,
"e": 1487,
"s": 1476,
"text": "Example 2:"
},
{
"code": null,
"e": 1490,
"s": 1487,
"text": "C#"
},
{
"code": "// C# program to find the current stack trace informationusing System; class GFG{ static public void Main(){ // Define the variable with integer string my_variable = \"58\"; // Get the current stack trace details // Using StackTrace property my_variable = Environment.StackTrace; Console.WriteLine(\"Information of current stack trace: \\n\" + my_variable);}}",
"e": 1894,
"s": 1490,
"text": null
},
{
"code": null,
"e": 1902,
"s": 1894,
"text": "Output:"
},
{
"code": null,
"e": 2093,
"s": 1902,
"text": "Current Stack Trace Details: \n at System.Environment.get_StackTrace () [0x00000] in <a1ae6166591d4020b810288d19af38d4>:0 \n at GFG.Main () [0x00000] in <092e5ea1577d4af6be34040e9472afab>:0 "
},
{
"code": null,
"e": 2106,
"s": 2093,
"text": "simmytarika5"
},
{
"code": null,
"e": 2122,
"s": 2106,
"text": "CSharp-programs"
},
{
"code": null,
"e": 2129,
"s": 2122,
"text": "Picked"
},
{
"code": null,
"e": 2132,
"s": 2129,
"text": "C#"
}
] |
Priority Queue using array in C++
|
25 Jan, 2022
Priority Queue is an extension of the Queue data structure where each element has a particular priority associated with it. It is based on the priority value, the elements from the queue are deleted.
Operations on Priority Queue:
enqueue(): This function is used to insert new data into the queue.
dequeue(): This function removes the element with the highest priority from the queue.
peek()/top(): This function is used to get the highest priority element in the queue without removing it from the queue.
Approach: The idea is to create a structure to store the value and priority of the element and then create an array of that structure to store elements. Below are the functionalities that are to be implemented:
enqueue(): It is used to insert the element at the end of the queue.
peek():Traverse across the priority queue and find the element with the highest priority and return its index.In the case of multiple elements with the same priority, find the element with the highest value having the highest priority.
Traverse across the priority queue and find the element with the highest priority and return its index.
In the case of multiple elements with the same priority, find the element with the highest value having the highest priority.
dequeue():Find the index with the highest priority using the peek() function let’s call that position as ind, and then shift the position of all the elements after the position ind one position to the left.Decrease the size by one.
Find the index with the highest priority using the peek() function let’s call that position as ind, and then shift the position of all the elements after the position ind one position to the left.
Decrease the size by one.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Structure for the elements in the// priority queuestruct item { int value; int priority;}; // Store the element of a priority queueitem pr[100000]; // Pointer to the last indexint size = -1; // Function to insert a new element// into priority queuevoid enqueue(int value, int priority){ // Increase the size size++; // Insert the element pr[size].value = value; pr[size].priority = priority;} // Function to check the top elementint peek(){ int highestPriority = INT_MIN; int ind = -1; // Check for the element with // highest priority for (int i = 0; i <= size; i++) { // If priority is same choose // the element with the // highest value if (highestPriority == pr[i].priority && ind > -1 && pr[ind].value < pr[i].value) { highestPriority = pr[i].priority; ind = i; } else if (highestPriority < pr[i].priority) { highestPriority = pr[i].priority; ind = i; } } // Return position of the element return ind;} // Function to remove the element with// the highest priorityvoid dequeue(){ // Find the position of the element // with highest priority int ind = peek(); // Shift the element one index before // from the position of the element // with highest priority is found for (int i = ind; i < size; i++) { pr[i] = pr[i + 1]; } // Decrease the size of the // priority queue by one size--;} // Driver Codeint main(){ // Function Call to insert elements // as per the priority enqueue(10, 2); enqueue(14, 4); enqueue(16, 4); enqueue(12, 3); // Stores the top element // at the moment int ind = peek(); cout << pr[ind].value << endl; // Dequeue the top element dequeue(); // Check the top element ind = peek(); cout << pr[ind].value << endl; // Dequeue the top element dequeue(); // Check the top element ind = peek(); cout << pr[ind].value << endl; return 0;}
16
14
12
Complexity Analysis:
enqueue(): O(1)
peek(): O(N)
dequeue: O(N)
Application of Priority Queue:
For Scheduling Algorithms the CPU has to process certain tasks having priorities. The process of having higher priority gets executed first.
In a time-sharing computer system, the process of waiting for the CPU time gets loaded in the priority queue.
A Sorting-priority queue is used to sort heaps.
anikakapoor
christopherbaboch
iit2020228
saimthis1997
as5853535
priority-queue
Technical Scripter 2020
C Programs
Queue
Searching
Technical Scripter
Searching
Queue
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Jan, 2022"
},
{
"code": null,
"e": 254,
"s": 54,
"text": "Priority Queue is an extension of the Queue data structure where each element has a particular priority associated with it. It is based on the priority value, the elements from the queue are deleted."
},
{
"code": null,
"e": 284,
"s": 254,
"text": "Operations on Priority Queue:"
},
{
"code": null,
"e": 352,
"s": 284,
"text": "enqueue(): This function is used to insert new data into the queue."
},
{
"code": null,
"e": 439,
"s": 352,
"text": "dequeue(): This function removes the element with the highest priority from the queue."
},
{
"code": null,
"e": 560,
"s": 439,
"text": "peek()/top(): This function is used to get the highest priority element in the queue without removing it from the queue."
},
{
"code": null,
"e": 771,
"s": 560,
"text": "Approach: The idea is to create a structure to store the value and priority of the element and then create an array of that structure to store elements. Below are the functionalities that are to be implemented:"
},
{
"code": null,
"e": 840,
"s": 771,
"text": "enqueue(): It is used to insert the element at the end of the queue."
},
{
"code": null,
"e": 1076,
"s": 840,
"text": "peek():Traverse across the priority queue and find the element with the highest priority and return its index.In the case of multiple elements with the same priority, find the element with the highest value having the highest priority."
},
{
"code": null,
"e": 1180,
"s": 1076,
"text": "Traverse across the priority queue and find the element with the highest priority and return its index."
},
{
"code": null,
"e": 1306,
"s": 1180,
"text": "In the case of multiple elements with the same priority, find the element with the highest value having the highest priority."
},
{
"code": null,
"e": 1538,
"s": 1306,
"text": "dequeue():Find the index with the highest priority using the peek() function let’s call that position as ind, and then shift the position of all the elements after the position ind one position to the left.Decrease the size by one."
},
{
"code": null,
"e": 1735,
"s": 1538,
"text": "Find the index with the highest priority using the peek() function let’s call that position as ind, and then shift the position of all the elements after the position ind one position to the left."
},
{
"code": null,
"e": 1761,
"s": 1735,
"text": "Decrease the size by one."
},
{
"code": null,
"e": 1812,
"s": 1761,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1816,
"s": 1812,
"text": "C++"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Structure for the elements in the// priority queuestruct item { int value; int priority;}; // Store the element of a priority queueitem pr[100000]; // Pointer to the last indexint size = -1; // Function to insert a new element// into priority queuevoid enqueue(int value, int priority){ // Increase the size size++; // Insert the element pr[size].value = value; pr[size].priority = priority;} // Function to check the top elementint peek(){ int highestPriority = INT_MIN; int ind = -1; // Check for the element with // highest priority for (int i = 0; i <= size; i++) { // If priority is same choose // the element with the // highest value if (highestPriority == pr[i].priority && ind > -1 && pr[ind].value < pr[i].value) { highestPriority = pr[i].priority; ind = i; } else if (highestPriority < pr[i].priority) { highestPriority = pr[i].priority; ind = i; } } // Return position of the element return ind;} // Function to remove the element with// the highest priorityvoid dequeue(){ // Find the position of the element // with highest priority int ind = peek(); // Shift the element one index before // from the position of the element // with highest priority is found for (int i = ind; i < size; i++) { pr[i] = pr[i + 1]; } // Decrease the size of the // priority queue by one size--;} // Driver Codeint main(){ // Function Call to insert elements // as per the priority enqueue(10, 2); enqueue(14, 4); enqueue(16, 4); enqueue(12, 3); // Stores the top element // at the moment int ind = peek(); cout << pr[ind].value << endl; // Dequeue the top element dequeue(); // Check the top element ind = peek(); cout << pr[ind].value << endl; // Dequeue the top element dequeue(); // Check the top element ind = peek(); cout << pr[ind].value << endl; return 0;}",
"e": 3994,
"s": 1816,
"text": null
},
{
"code": null,
"e": 4003,
"s": 3994,
"text": "16\n14\n12"
},
{
"code": null,
"e": 4024,
"s": 4003,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 4040,
"s": 4024,
"text": "enqueue(): O(1)"
},
{
"code": null,
"e": 4053,
"s": 4040,
"text": "peek(): O(N)"
},
{
"code": null,
"e": 4067,
"s": 4053,
"text": "dequeue: O(N)"
},
{
"code": null,
"e": 4098,
"s": 4067,
"text": "Application of Priority Queue:"
},
{
"code": null,
"e": 4239,
"s": 4098,
"text": "For Scheduling Algorithms the CPU has to process certain tasks having priorities. The process of having higher priority gets executed first."
},
{
"code": null,
"e": 4349,
"s": 4239,
"text": "In a time-sharing computer system, the process of waiting for the CPU time gets loaded in the priority queue."
},
{
"code": null,
"e": 4397,
"s": 4349,
"text": "A Sorting-priority queue is used to sort heaps."
},
{
"code": null,
"e": 4409,
"s": 4397,
"text": "anikakapoor"
},
{
"code": null,
"e": 4427,
"s": 4409,
"text": "christopherbaboch"
},
{
"code": null,
"e": 4438,
"s": 4427,
"text": "iit2020228"
},
{
"code": null,
"e": 4451,
"s": 4438,
"text": "saimthis1997"
},
{
"code": null,
"e": 4461,
"s": 4451,
"text": "as5853535"
},
{
"code": null,
"e": 4476,
"s": 4461,
"text": "priority-queue"
},
{
"code": null,
"e": 4500,
"s": 4476,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 4511,
"s": 4500,
"text": "C Programs"
},
{
"code": null,
"e": 4517,
"s": 4511,
"text": "Queue"
},
{
"code": null,
"e": 4527,
"s": 4517,
"text": "Searching"
},
{
"code": null,
"e": 4546,
"s": 4527,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4556,
"s": 4546,
"text": "Searching"
},
{
"code": null,
"e": 4562,
"s": 4556,
"text": "Queue"
},
{
"code": null,
"e": 4577,
"s": 4562,
"text": "priority-queue"
}
] |
include guards in C++
|
28 Jan, 2021
While programming in C++ we often use a class multiple times, and hence it requires to create a header file and just include it in the main program. Now, sometimes it happens that a certain header file directly or indirectly get included multiple times, then the class declared in the header file gets re-declared which gives an error. To understand the needs of include guards let us first understand one example:
Program 1: Creating an Animal class and save it as “Animal.h”. Below is the program for the same:
C++
// C++ program to create a header// file named as "Animal.h"#include <iostream>#include <string>using namespace std; // Animal Classclass Animal { string name, color, type; public: // Function to take input void input() { name = "Dog"; color = "White"; } // Function to display the member // variables void display() { cout << name << " is of " << color << endl; }};
Program 2: Creating a Dog class and save it as Dog.h. Remember to include “Animal.h” header file declared above:
C++
// C++ program to create header file// named as Dog.h // Include the header file "Animal.h"#include "Animal.h" // Dog Classclass Dog { Animal d; public: // Take input to member variable // using function call in another // header file void dog_input() { d.input(); } // Function to display the member // variable using function call // in another header file void dog_display() { d.display(); }};
Program 3: Create a main.cpp file and include above both header files. Below is the program for the same:
C++
// C++ program to illustrate the// include guards#include "Animal.h"#include "Dog.h"#include <iostream>using namespace std; // Driver Codeint main(){ // Object of Dog class in // "Dog.h" header file Dog a; // Member Function Call a.dog_input(); a.dog_display(); return 0;}
Output: Now, when the above program “main.cpp” is executed then the following error occurs:
Explanation: When the “main.cpp” program is compiled using include Animal.h and defines Animal class, thereafter while including Dog.h, Animal.h get included and in main program there are two definitions of Animal Class that’s why this error is generated. Now lets resolve the issue using include guards.
In the C and C++ programming languages, an #include guard, sometimes called a macro guard, header guard, or file guard, is a particular construct used to avoid the problem of double inclusion when dealing with the include directive.
Solution:Include guards ensures that compiler will process this file only once, no matter how many times it is included. Include guards are just series of preprocessor directives that guarantees file will only be included once.Preprocessors used:
#ifndef: if not defined, determines if provided macros does not exists.
#define: Defines the macros.
#endif: Closes off #ifndef directive.
The block of statements between #ifndef and #endif will be executed only if the macro or the identifier with #ifndef is not defined.
Syntax:
#ifndef ANIMAL(Any word you like but unique to program)
#define ANIMAL(same word as used earlier)
class Animal {
// Code
};
#endif
So, the “Animal.h” header file should be declared as:
C++
// Checks if _ANIMALS IF DECLARED#ifndef _ANIMALS_ // Defines _ANIMALS_ if above// conditions fails#define _ANIMALS_ #include <iostream>#include <string>using namespace std; // Animal Classclass Animal { string name, color, type; public: // Function to take input to // member variable void input() { name = "Dog"; color = "White"; } // Function to display the // member variable void display() { cout << name << " is of" << color << endl; }};#endif // _ANIMALS_
Output:
Explanation: When main.cpp runs, Animal.h is included and animal class is declared. Here the first line of Animal.h header while executed and as _ANIMALS_ is not defined code executes normally. When Dog.h header file gets included which in turn included Animal.h, this time _ANIMALS_ is defined in program, so first line #ifndef condition is true and entire code gets SKIPPED to last line i.e #endif. In simple words, if the preprocessor has that name defined then it skips entire file and goes to #endif, in other words it doesn’t process file.
CPP-Basics
Macro & Preprocessor
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jan, 2021"
},
{
"code": null,
"e": 467,
"s": 52,
"text": "While programming in C++ we often use a class multiple times, and hence it requires to create a header file and just include it in the main program. Now, sometimes it happens that a certain header file directly or indirectly get included multiple times, then the class declared in the header file gets re-declared which gives an error. To understand the needs of include guards let us first understand one example:"
},
{
"code": null,
"e": 565,
"s": 467,
"text": "Program 1: Creating an Animal class and save it as “Animal.h”. Below is the program for the same:"
},
{
"code": null,
"e": 569,
"s": 565,
"text": "C++"
},
{
"code": "// C++ program to create a header// file named as \"Animal.h\"#include <iostream>#include <string>using namespace std; // Animal Classclass Animal { string name, color, type; public: // Function to take input void input() { name = \"Dog\"; color = \"White\"; } // Function to display the member // variables void display() { cout << name << \" is of \" << color << endl; }};",
"e": 1003,
"s": 569,
"text": null
},
{
"code": null,
"e": 1116,
"s": 1003,
"text": "Program 2: Creating a Dog class and save it as Dog.h. Remember to include “Animal.h” header file declared above:"
},
{
"code": null,
"e": 1120,
"s": 1116,
"text": "C++"
},
{
"code": "// C++ program to create header file// named as Dog.h // Include the header file \"Animal.h\"#include \"Animal.h\" // Dog Classclass Dog { Animal d; public: // Take input to member variable // using function call in another // header file void dog_input() { d.input(); } // Function to display the member // variable using function call // in another header file void dog_display() { d.display(); }};",
"e": 1549,
"s": 1120,
"text": null
},
{
"code": null,
"e": 1655,
"s": 1549,
"text": "Program 3: Create a main.cpp file and include above both header files. Below is the program for the same:"
},
{
"code": null,
"e": 1659,
"s": 1655,
"text": "C++"
},
{
"code": "// C++ program to illustrate the// include guards#include \"Animal.h\"#include \"Dog.h\"#include <iostream>using namespace std; // Driver Codeint main(){ // Object of Dog class in // \"Dog.h\" header file Dog a; // Member Function Call a.dog_input(); a.dog_display(); return 0;}",
"e": 1958,
"s": 1659,
"text": null
},
{
"code": null,
"e": 2050,
"s": 1958,
"text": "Output: Now, when the above program “main.cpp” is executed then the following error occurs:"
},
{
"code": null,
"e": 2355,
"s": 2050,
"text": "Explanation: When the “main.cpp” program is compiled using include Animal.h and defines Animal class, thereafter while including Dog.h, Animal.h get included and in main program there are two definitions of Animal Class that’s why this error is generated. Now lets resolve the issue using include guards."
},
{
"code": null,
"e": 2588,
"s": 2355,
"text": "In the C and C++ programming languages, an #include guard, sometimes called a macro guard, header guard, or file guard, is a particular construct used to avoid the problem of double inclusion when dealing with the include directive."
},
{
"code": null,
"e": 2835,
"s": 2588,
"text": "Solution:Include guards ensures that compiler will process this file only once, no matter how many times it is included. Include guards are just series of preprocessor directives that guarantees file will only be included once.Preprocessors used:"
},
{
"code": null,
"e": 2907,
"s": 2835,
"text": "#ifndef: if not defined, determines if provided macros does not exists."
},
{
"code": null,
"e": 2936,
"s": 2907,
"text": "#define: Defines the macros."
},
{
"code": null,
"e": 2974,
"s": 2936,
"text": "#endif: Closes off #ifndef directive."
},
{
"code": null,
"e": 3107,
"s": 2974,
"text": "The block of statements between #ifndef and #endif will be executed only if the macro or the identifier with #ifndef is not defined."
},
{
"code": null,
"e": 3116,
"s": 3107,
"text": "Syntax: "
},
{
"code": null,
"e": 3253,
"s": 3116,
"text": "#ifndef ANIMAL(Any word you like but unique to program)\n#define ANIMAL(same word as used earlier)\n\nclass Animal {\n // Code\n};\n\n#endif"
},
{
"code": null,
"e": 3307,
"s": 3253,
"text": "So, the “Animal.h” header file should be declared as:"
},
{
"code": null,
"e": 3311,
"s": 3307,
"text": "C++"
},
{
"code": "// Checks if _ANIMALS IF DECLARED#ifndef _ANIMALS_ // Defines _ANIMALS_ if above// conditions fails#define _ANIMALS_ #include <iostream>#include <string>using namespace std; // Animal Classclass Animal { string name, color, type; public: // Function to take input to // member variable void input() { name = \"Dog\"; color = \"White\"; } // Function to display the // member variable void display() { cout << name << \" is of\" << color << endl; }};#endif // _ANIMALS_",
"e": 3846,
"s": 3311,
"text": null
},
{
"code": null,
"e": 3854,
"s": 3846,
"text": "Output:"
},
{
"code": null,
"e": 4400,
"s": 3854,
"text": "Explanation: When main.cpp runs, Animal.h is included and animal class is declared. Here the first line of Animal.h header while executed and as _ANIMALS_ is not defined code executes normally. When Dog.h header file gets included which in turn included Animal.h, this time _ANIMALS_ is defined in program, so first line #ifndef condition is true and entire code gets SKIPPED to last line i.e #endif. In simple words, if the preprocessor has that name defined then it skips entire file and goes to #endif, in other words it doesn’t process file."
},
{
"code": null,
"e": 4411,
"s": 4400,
"text": "CPP-Basics"
},
{
"code": null,
"e": 4432,
"s": 4411,
"text": "Macro & Preprocessor"
},
{
"code": null,
"e": 4436,
"s": 4432,
"text": "C++"
},
{
"code": null,
"e": 4449,
"s": 4436,
"text": "C++ Programs"
},
{
"code": null,
"e": 4453,
"s": 4449,
"text": "CPP"
}
] |
Minimum Cost Path in a directed graph via given set of intermediate nodes
|
15 Dec, 2021
Given a weighted, directed graph G, an array V[] consisting of vertices, the task is to find the Minimum Cost Path passing through all the vertices of the set V, from a given source S to a destination D.
Examples:
Input: V = {7}, S = 0, D = 6
Output: 11 Explanation: Minimum path 0->7->5->6. Therefore, the cost of the path = 3 + 6 + 2 = 11
Input: V = {7, 4}, S = 0, D = 6
Output: 12 Explanation: Minimum path 0->7->4->6. Therefore the cost of the path = 3 + 5 + 4 = 12
Approach: To solve the problem, the idea is to use Breadth-First-Search traversal. BFS is generally used to find the Shortest Paths in the graph and the minimum distance of all nodes from Source, intermediate nodes, and Destination can be calculated by the BFS from these nodes.
Follow the steps below to solve the problem:
Initialize minSum to INT_MAX.
Traverse the graph from the source node S using BFS.
Mark each neighbouring node of the source as the new source and perform BFS from that node.
Once the destination node D is encountered, then check if all the intermediate nodes are visited or not.
If all the intermediate nodes are visited, then update the minSum and return the minimum value.
If all the intermediate nodes are not visited, then return minSum.
Mark the source as unvisited.
Print the final value of minSum obtained.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Stores minimum-cost of path from sourceint minSum = INT_MAX; // Function to Perform BFS on graph g// starting from vertex vvoid getMinPathSum(unordered_map<int, vector<pair<int, int> > >& graph, vector<bool>& visited, vector<int> necessary, int src, int dest, int currSum){ // If destination is reached if (src == dest) { // Set flag to true bool flag = true; // Visit all the intermediate nodes for (int i : necessary) { // If any intermediate node // is not visited if (!visited[i]) { flag = false; break; } } // If all intermediate // nodes are visited if (flag) // Update the minSum minSum = min(minSum, currSum); return; } else { // Mark the current node // visited visited[src] = true; // Traverse adjacent nodes for (auto node : graph[src]) { if (!visited[node.first]) { // Mark the neighbour visited visited[node.first] = true; // Find minimum cost path // considering the neighbour // as the source getMinPathSum(graph, visited, necessary, node.first, dest, currSum + node.second); // Mark the neighbour unvisited visited[node.first] = false; } } // Mark the source unvisited visited[src] = false; }} // Driver Codeint main(){ // Stores the graph unordered_map<int, vector<pair<int, int> > > graph; graph[0] = { { 1, 2 }, { 2, 3 }, { 3, 2 } }; graph[1] = { { 4, 4 }, { 0, 1 } }; graph[2] = { { 4, 5 }, { 5, 6 } }; graph[3] = { { 5, 7 }, { 0, 1 } }; graph[4] = { { 6, 4 } }; graph[5] = { { 6, 2 } }; graph[6] = { { 7, 11 } }; // Number of nodes int n = 7; // Source int source = 0; // Destination int dest = 6; // Keeps a check on visited // and unvisited nodes vector<bool> visited(n, false); // Stores intermediate nodes vector<int> necessary{ 2, 4 }; getMinPathSum(graph, visited, necessary, source, dest, 0); // If no path is found if (minSum == INT_MAX) cout << "-1\n"; else cout << minSum << '\n'; return 0;}
// Java program to implement// the above approachimport java.util.*; class GFG{ static class pair{ int first, second; pair(int f, int s) { this.first = f; this.second = s; }} // Stores minimum-cost of path from sourcestatic int minSum = Integer.MAX_VALUE; // Function to Perform BFS on graph g// starting from vertex vstatic void getMinPathSum(Map<Integer, ArrayList<pair>> graph, boolean[] visited, ArrayList<Integer> necessary, int source, int dest, int currSum){ // If destination is reached if (src == dest) { // Set flag to true boolean flag = true; // Visit all the intermediate nodes for(int i : necessary) { // If any intermediate node // is not visited if (!visited[i]) { flag = false; break; } } // If all intermediate // nodes are visited if (flag) // Update the minSum minSum = Math.min(minSum, currSum); return; } else { // Mark the current node // visited visited[src] = true; // Traverse adjacent nodes for(pair node : graph.get(src)) { if (!visited[node.first]) { // Mark the neighbour visited visited[node.first] = true; // Find minimum cost path // considering the neighbour // as the source getMinPathSum(graph, visited, necessary, node.first, dest, currSum + node.second); // Mark the neighbour unvisited visited[node.first] = false; } } // Mark the source unvisited visited[src] = false; }} // Driver codepublic static void main(String[] args){ // Stores the graph Map<Integer, ArrayList<pair>> graph = new HashMap<>(); for(int i = 0; i <= 6; i++) graph.put(i, new ArrayList<pair>()); graph.get(0).add(new pair(1, 2)); graph.get(0).add(new pair(2, 3)); graph.get(0).add(new pair(3, 2)); graph.get(1).add(new pair(4, 4)); graph.get(1).add(new pair(0, 1)); graph.get(2).add(new pair(4, 5)); graph.get(2).add(new pair(5, 6)); graph.get(3).add(new pair(5, 7)); graph.get(3).add(new pair(0, 1)); graph.get(4).add(new pair(6, 4)); graph.get(5).add(new pair(4, 2)); graph.get(6).add(new pair(7, 11)); // Number of nodes int n = 7; // Source int source = 0; // Destination int dest = 6; // Keeps a check on visited // and unvisited nodes boolean[] visited = new boolean[n]; // Stores intermediate nodes ArrayList<Integer> necessary = new ArrayList<>( Arrays.asList(2, 4)); getMinPathSum(graph, visited, necessary, source, dest, 0); // If no path is found if (minSum == Integer.MAX_VALUE) System.out.println(-1); else System.out.println(minSum);}} // This code is contributed by offbeat
# Python3 Program to implement# the above approach # Stores minimum-cost of path from sourceminSum = 1000000000 # Function to Perform BFS on graph g# starting from vertex vdef getMinPathSum(graph, visited, necessary, source, dest, currSum): global minSum # If destination is reached if (src == dest): # Set flag to true flag = True; # Visit all the intermediate nodes for i in necessary: # If any intermediate node # is not visited if (not visited[i]): flag = False; break; # If all intermediate # nodes are visited if (flag): # Update the minSum minSum = min(minSum, currSum); return; else: # Mark the current node # visited visited[src] = True; # Traverse adjacent nodes for node in graph[src]: if not visited[node[0]]: # Mark the neighbour visited visited[node[0]] = True; # Find minimum cost path # considering the neighbour # as the source getMinPathSum(graph, visited, necessary, node[0], dest, currSum + node[1]); # Mark the neighbour unvisited visited[node[0]] = False; # Mark the source unvisited visited[src] = False; # Driver Codeif __name__=='__main__': # Stores the graph graph=dict() graph[0] = [ [ 1, 2 ], [ 2, 3 ], [ 3, 2 ] ]; graph[1] = [ [ 4, 4 ], [ 0, 1 ] ]; graph[2] = [ [ 4, 5 ], [ 5, 6 ] ]; graph[3] = [ [ 5, 7 ], [ 0, 1 ] ]; graph[4] = [ [ 6, 4 ] ]; graph[5] = [ [ 6, 2 ] ]; graph[6] = [ [ 7, 11 ] ]; # Number of nodes n = 7; # Source source = 0; # Destination dest = 6; # Keeps a check on visited # and unvisited nodes visited=[ False for i in range(n + 1)] # Stores intermediate nodes necessary = [ 2, 4 ]; getMinPathSum(graph, visited, necessary, source, dest, 0); # If no path is found if (minSum == 1000000000): print(-1) else: print(minSum) # This code is contributed by pratham76
// C# program to implement// the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ class pair{ public int first, second; public pair(int f, int s) { this.first = f; this.second = s; }} // Stores minimum-cost of path from sourcestatic int minSum = 100000000; // Function to Perform BFS on graph g// starting from vertex vstatic void getMinPathSum(Dictionary<int, ArrayList> graph, bool[] visited, ArrayList necessary, int source, int dest, int currSum){ // If destination is reached if (src == dest) { // Set flag to true bool flag = true; // Visit all the intermediate nodes foreach(int i in necessary) { // If any intermediate node // is not visited if (!visited[i]) { flag = false; break; } } // If all intermediate // nodes are visited if (flag) // Update the minSum minSum = Math.Min(minSum, currSum); return; } else { // Mark the current node // visited visited[src] = true; // Traverse adjacent nodes foreach(pair node in graph) { if (!visited[node.first]) { // Mark the neighbour visited visited[node.first] = true; // Find minimum cost path // considering the neighbour // as the source getMinPathSum(graph, visited, necessary, node.first, dest, currSum + node.second); // Mark the neighbour unvisited visited[node.first] = false; } } // Mark the source unvisited visited[src] = false; }} // Driver codepublic static void Main(string[] args){ // Stores the graph Dictionary<int, ArrayList> graph = new Dictionary<int, ArrayList>(); for(int i = 0; i <= 6; i++) graph[i] = new ArrayList(); graph[0].Add(new pair(1, 2)); graph[0].Add(new pair(2, 3)); graph[0].Add(new pair(3, 2)); graph[1].Add(new pair(4, 4)); graph[1].Add(new pair(0, 1)); graph[2].Add(new pair(4, 5)); graph[2].Add(new pair(5, 6)); graph[3].Add(new pair(5, 7)); graph[3].Add(new pair(0, 1)); graph[4].Add(new pair(6, 4)); graph[5].Add(new pair(4, 2)); graph[6].Add(new pair(7, 11)); // Number of nodes int n = 7; // Source int source = 0; // Destination int dest = 6; // Keeps a check on visited // and unvisited nodes bool[] visited = new bool[n]; // Stores intermediate nodes ArrayList necessary = new ArrayList(); necessary.Add(2); necessary.Add(4); getMinPathSum(graph, visited, necessary, source, dest, 0); // If no path is found if (minSum == 100000000) Console.WriteLine(-1); else Console.WriteLine(minSum);}} // This code is contributed by rutvik_56
<script> // Javascript program to implement// the above approach class pair{ constructor(f, s) { this.first = f; this.second = s; }} // Stores minimum-cost of path from sourcevar minSum = 100000000; // Function to Perform BFS on graph g// starting from vertex vfunction getMinPathSum(graph, visited,necessary, src, dest, currSum){ // If destination is reached if (src == dest) { // Set flag to true var flag = true; // Visit all the intermediate nodes for(var i of necessary) { // If any intermediate node // is not visited if (!visited[i]) { flag = false; break; } } // If all intermediate // nodes are visited if (flag) // Update the minSum minSum = Math.min(minSum, currSum); return; } else { // Mark the current node // visited visited[src] = true; // Traverse adjacent nodes for(var node of graph[src]) { if (!visited[node.first]) { // Mark the neighbour visited visited[node.first] = true; // Find minimum cost path // considering the neighbour // as the source getMinPathSum(graph, visited, necessary, node.first, dest, currSum + node.second); // Mark the neighbour unvisited visited[node.first] = false; } } // Mark the source unvisited visited[src] = false; }} // Driver code // Stores the graphvar graph = Array.from(Array(7), ()=>Array()); graph[0].push(new pair(1, 2));graph[0].push(new pair(2, 3));graph[0].push(new pair(3, 2));graph[1].push(new pair(4, 4));graph[1].push(new pair(0, 1));graph[2].push(new pair(4, 5));graph[2].push(new pair(5, 6));graph[3].push(new pair(5, 7));graph[3].push(new pair(0, 1));graph[4].push(new pair(6, 4));graph[5].push(new pair(4, 2));graph[6].push(new pair(7, 11)); // Number of nodesvar n = 7; // Sourcevar source = 0; // Destinationvar dest = 6; // Keeps a check on visited// and unvisited nodesvar visited = Array(n).fill(false); // Stores intermediate nodesvar necessary = [];necessary.push(2);necessary.push(4); getMinPathSum(graph, visited, necessary, source, dest, 0); // If no path is foundif (minSum == 100000000) document.write(-1);else document.write(minSum); </script>
12
Time Complexity: O(N+M) Auxiliary Space: O(N+M)
ahmednadeem1
offbeat
rutvik_56
pratham76
noob2000
simmytarika5
BFS
Graph Traversals
Shortest Path
Backtracking
Graph
Recursion
Recursion
Graph
Shortest Path
Backtracking
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 232,
"s": 28,
"text": "Given a weighted, directed graph G, an array V[] consisting of vertices, the task is to find the Minimum Cost Path passing through all the vertices of the set V, from a given source S to a destination D."
},
{
"code": null,
"e": 243,
"s": 232,
"text": "Examples: "
},
{
"code": null,
"e": 274,
"s": 243,
"text": "Input: V = {7}, S = 0, D = 6 "
},
{
"code": null,
"e": 372,
"s": 274,
"text": "Output: 11 Explanation: Minimum path 0->7->5->6. Therefore, the cost of the path = 3 + 6 + 2 = 11"
},
{
"code": null,
"e": 406,
"s": 372,
"text": "Input: V = {7, 4}, S = 0, D = 6 "
},
{
"code": null,
"e": 504,
"s": 406,
"text": "Output: 12 Explanation: Minimum path 0->7->4->6. Therefore the cost of the path = 3 + 5 + 4 = 12 "
},
{
"code": null,
"e": 783,
"s": 504,
"text": "Approach: To solve the problem, the idea is to use Breadth-First-Search traversal. BFS is generally used to find the Shortest Paths in the graph and the minimum distance of all nodes from Source, intermediate nodes, and Destination can be calculated by the BFS from these nodes."
},
{
"code": null,
"e": 830,
"s": 783,
"text": "Follow the steps below to solve the problem: "
},
{
"code": null,
"e": 860,
"s": 830,
"text": "Initialize minSum to INT_MAX."
},
{
"code": null,
"e": 913,
"s": 860,
"text": "Traverse the graph from the source node S using BFS."
},
{
"code": null,
"e": 1005,
"s": 913,
"text": "Mark each neighbouring node of the source as the new source and perform BFS from that node."
},
{
"code": null,
"e": 1110,
"s": 1005,
"text": "Once the destination node D is encountered, then check if all the intermediate nodes are visited or not."
},
{
"code": null,
"e": 1206,
"s": 1110,
"text": "If all the intermediate nodes are visited, then update the minSum and return the minimum value."
},
{
"code": null,
"e": 1273,
"s": 1206,
"text": "If all the intermediate nodes are not visited, then return minSum."
},
{
"code": null,
"e": 1303,
"s": 1273,
"text": "Mark the source as unvisited."
},
{
"code": null,
"e": 1345,
"s": 1303,
"text": "Print the final value of minSum obtained."
},
{
"code": null,
"e": 1396,
"s": 1345,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1400,
"s": 1396,
"text": "C++"
},
{
"code": null,
"e": 1405,
"s": 1400,
"text": "Java"
},
{
"code": null,
"e": 1413,
"s": 1405,
"text": "Python3"
},
{
"code": null,
"e": 1416,
"s": 1413,
"text": "C#"
},
{
"code": null,
"e": 1427,
"s": 1416,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Stores minimum-cost of path from sourceint minSum = INT_MAX; // Function to Perform BFS on graph g// starting from vertex vvoid getMinPathSum(unordered_map<int, vector<pair<int, int> > >& graph, vector<bool>& visited, vector<int> necessary, int src, int dest, int currSum){ // If destination is reached if (src == dest) { // Set flag to true bool flag = true; // Visit all the intermediate nodes for (int i : necessary) { // If any intermediate node // is not visited if (!visited[i]) { flag = false; break; } } // If all intermediate // nodes are visited if (flag) // Update the minSum minSum = min(minSum, currSum); return; } else { // Mark the current node // visited visited[src] = true; // Traverse adjacent nodes for (auto node : graph[src]) { if (!visited[node.first]) { // Mark the neighbour visited visited[node.first] = true; // Find minimum cost path // considering the neighbour // as the source getMinPathSum(graph, visited, necessary, node.first, dest, currSum + node.second); // Mark the neighbour unvisited visited[node.first] = false; } } // Mark the source unvisited visited[src] = false; }} // Driver Codeint main(){ // Stores the graph unordered_map<int, vector<pair<int, int> > > graph; graph[0] = { { 1, 2 }, { 2, 3 }, { 3, 2 } }; graph[1] = { { 4, 4 }, { 0, 1 } }; graph[2] = { { 4, 5 }, { 5, 6 } }; graph[3] = { { 5, 7 }, { 0, 1 } }; graph[4] = { { 6, 4 } }; graph[5] = { { 6, 2 } }; graph[6] = { { 7, 11 } }; // Number of nodes int n = 7; // Source int source = 0; // Destination int dest = 6; // Keeps a check on visited // and unvisited nodes vector<bool> visited(n, false); // Stores intermediate nodes vector<int> necessary{ 2, 4 }; getMinPathSum(graph, visited, necessary, source, dest, 0); // If no path is found if (minSum == INT_MAX) cout << \"-1\\n\"; else cout << minSum << '\\n'; return 0;}",
"e": 4071,
"s": 1427,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*; class GFG{ static class pair{ int first, second; pair(int f, int s) { this.first = f; this.second = s; }} // Stores minimum-cost of path from sourcestatic int minSum = Integer.MAX_VALUE; // Function to Perform BFS on graph g// starting from vertex vstatic void getMinPathSum(Map<Integer, ArrayList<pair>> graph, boolean[] visited, ArrayList<Integer> necessary, int source, int dest, int currSum){ // If destination is reached if (src == dest) { // Set flag to true boolean flag = true; // Visit all the intermediate nodes for(int i : necessary) { // If any intermediate node // is not visited if (!visited[i]) { flag = false; break; } } // If all intermediate // nodes are visited if (flag) // Update the minSum minSum = Math.min(minSum, currSum); return; } else { // Mark the current node // visited visited[src] = true; // Traverse adjacent nodes for(pair node : graph.get(src)) { if (!visited[node.first]) { // Mark the neighbour visited visited[node.first] = true; // Find minimum cost path // considering the neighbour // as the source getMinPathSum(graph, visited, necessary, node.first, dest, currSum + node.second); // Mark the neighbour unvisited visited[node.first] = false; } } // Mark the source unvisited visited[src] = false; }} // Driver codepublic static void main(String[] args){ // Stores the graph Map<Integer, ArrayList<pair>> graph = new HashMap<>(); for(int i = 0; i <= 6; i++) graph.put(i, new ArrayList<pair>()); graph.get(0).add(new pair(1, 2)); graph.get(0).add(new pair(2, 3)); graph.get(0).add(new pair(3, 2)); graph.get(1).add(new pair(4, 4)); graph.get(1).add(new pair(0, 1)); graph.get(2).add(new pair(4, 5)); graph.get(2).add(new pair(5, 6)); graph.get(3).add(new pair(5, 7)); graph.get(3).add(new pair(0, 1)); graph.get(4).add(new pair(6, 4)); graph.get(5).add(new pair(4, 2)); graph.get(6).add(new pair(7, 11)); // Number of nodes int n = 7; // Source int source = 0; // Destination int dest = 6; // Keeps a check on visited // and unvisited nodes boolean[] visited = new boolean[n]; // Stores intermediate nodes ArrayList<Integer> necessary = new ArrayList<>( Arrays.asList(2, 4)); getMinPathSum(graph, visited, necessary, source, dest, 0); // If no path is found if (minSum == Integer.MAX_VALUE) System.out.println(-1); else System.out.println(minSum);}} // This code is contributed by offbeat",
"e": 7309,
"s": 4071,
"text": null
},
{
"code": "# Python3 Program to implement# the above approach # Stores minimum-cost of path from sourceminSum = 1000000000 # Function to Perform BFS on graph g# starting from vertex vdef getMinPathSum(graph, visited, necessary, source, dest, currSum): global minSum # If destination is reached if (src == dest): # Set flag to true flag = True; # Visit all the intermediate nodes for i in necessary: # If any intermediate node # is not visited if (not visited[i]): flag = False; break; # If all intermediate # nodes are visited if (flag): # Update the minSum minSum = min(minSum, currSum); return; else: # Mark the current node # visited visited[src] = True; # Traverse adjacent nodes for node in graph[src]: if not visited[node[0]]: # Mark the neighbour visited visited[node[0]] = True; # Find minimum cost path # considering the neighbour # as the source getMinPathSum(graph, visited, necessary, node[0], dest, currSum + node[1]); # Mark the neighbour unvisited visited[node[0]] = False; # Mark the source unvisited visited[src] = False; # Driver Codeif __name__=='__main__': # Stores the graph graph=dict() graph[0] = [ [ 1, 2 ], [ 2, 3 ], [ 3, 2 ] ]; graph[1] = [ [ 4, 4 ], [ 0, 1 ] ]; graph[2] = [ [ 4, 5 ], [ 5, 6 ] ]; graph[3] = [ [ 5, 7 ], [ 0, 1 ] ]; graph[4] = [ [ 6, 4 ] ]; graph[5] = [ [ 6, 2 ] ]; graph[6] = [ [ 7, 11 ] ]; # Number of nodes n = 7; # Source source = 0; # Destination dest = 6; # Keeps a check on visited # and unvisited nodes visited=[ False for i in range(n + 1)] # Stores intermediate nodes necessary = [ 2, 4 ]; getMinPathSum(graph, visited, necessary, source, dest, 0); # If no path is found if (minSum == 1000000000): print(-1) else: print(minSum) # This code is contributed by pratham76",
"e": 9645,
"s": 7309,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ class pair{ public int first, second; public pair(int f, int s) { this.first = f; this.second = s; }} // Stores minimum-cost of path from sourcestatic int minSum = 100000000; // Function to Perform BFS on graph g// starting from vertex vstatic void getMinPathSum(Dictionary<int, ArrayList> graph, bool[] visited, ArrayList necessary, int source, int dest, int currSum){ // If destination is reached if (src == dest) { // Set flag to true bool flag = true; // Visit all the intermediate nodes foreach(int i in necessary) { // If any intermediate node // is not visited if (!visited[i]) { flag = false; break; } } // If all intermediate // nodes are visited if (flag) // Update the minSum minSum = Math.Min(minSum, currSum); return; } else { // Mark the current node // visited visited[src] = true; // Traverse adjacent nodes foreach(pair node in graph) { if (!visited[node.first]) { // Mark the neighbour visited visited[node.first] = true; // Find minimum cost path // considering the neighbour // as the source getMinPathSum(graph, visited, necessary, node.first, dest, currSum + node.second); // Mark the neighbour unvisited visited[node.first] = false; } } // Mark the source unvisited visited[src] = false; }} // Driver codepublic static void Main(string[] args){ // Stores the graph Dictionary<int, ArrayList> graph = new Dictionary<int, ArrayList>(); for(int i = 0; i <= 6; i++) graph[i] = new ArrayList(); graph[0].Add(new pair(1, 2)); graph[0].Add(new pair(2, 3)); graph[0].Add(new pair(3, 2)); graph[1].Add(new pair(4, 4)); graph[1].Add(new pair(0, 1)); graph[2].Add(new pair(4, 5)); graph[2].Add(new pair(5, 6)); graph[3].Add(new pair(5, 7)); graph[3].Add(new pair(0, 1)); graph[4].Add(new pair(6, 4)); graph[5].Add(new pair(4, 2)); graph[6].Add(new pair(7, 11)); // Number of nodes int n = 7; // Source int source = 0; // Destination int dest = 6; // Keeps a check on visited // and unvisited nodes bool[] visited = new bool[n]; // Stores intermediate nodes ArrayList necessary = new ArrayList(); necessary.Add(2); necessary.Add(4); getMinPathSum(graph, visited, necessary, source, dest, 0); // If no path is found if (minSum == 100000000) Console.WriteLine(-1); else Console.WriteLine(minSum);}} // This code is contributed by rutvik_56",
"e": 12823,
"s": 9645,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach class pair{ constructor(f, s) { this.first = f; this.second = s; }} // Stores minimum-cost of path from sourcevar minSum = 100000000; // Function to Perform BFS on graph g// starting from vertex vfunction getMinPathSum(graph, visited,necessary, src, dest, currSum){ // If destination is reached if (src == dest) { // Set flag to true var flag = true; // Visit all the intermediate nodes for(var i of necessary) { // If any intermediate node // is not visited if (!visited[i]) { flag = false; break; } } // If all intermediate // nodes are visited if (flag) // Update the minSum minSum = Math.min(minSum, currSum); return; } else { // Mark the current node // visited visited[src] = true; // Traverse adjacent nodes for(var node of graph[src]) { if (!visited[node.first]) { // Mark the neighbour visited visited[node.first] = true; // Find minimum cost path // considering the neighbour // as the source getMinPathSum(graph, visited, necessary, node.first, dest, currSum + node.second); // Mark the neighbour unvisited visited[node.first] = false; } } // Mark the source unvisited visited[src] = false; }} // Driver code // Stores the graphvar graph = Array.from(Array(7), ()=>Array()); graph[0].push(new pair(1, 2));graph[0].push(new pair(2, 3));graph[0].push(new pair(3, 2));graph[1].push(new pair(4, 4));graph[1].push(new pair(0, 1));graph[2].push(new pair(4, 5));graph[2].push(new pair(5, 6));graph[3].push(new pair(5, 7));graph[3].push(new pair(0, 1));graph[4].push(new pair(6, 4));graph[5].push(new pair(4, 2));graph[6].push(new pair(7, 11)); // Number of nodesvar n = 7; // Sourcevar source = 0; // Destinationvar dest = 6; // Keeps a check on visited// and unvisited nodesvar visited = Array(n).fill(false); // Stores intermediate nodesvar necessary = [];necessary.push(2);necessary.push(4); getMinPathSum(graph, visited, necessary, source, dest, 0); // If no path is foundif (minSum == 100000000) document.write(-1);else document.write(minSum); </script>",
"e": 15455,
"s": 12823,
"text": null
},
{
"code": null,
"e": 15458,
"s": 15455,
"text": "12"
},
{
"code": null,
"e": 15509,
"s": 15460,
"text": "Time Complexity: O(N+M) Auxiliary Space: O(N+M) "
},
{
"code": null,
"e": 15524,
"s": 15511,
"text": "ahmednadeem1"
},
{
"code": null,
"e": 15532,
"s": 15524,
"text": "offbeat"
},
{
"code": null,
"e": 15542,
"s": 15532,
"text": "rutvik_56"
},
{
"code": null,
"e": 15552,
"s": 15542,
"text": "pratham76"
},
{
"code": null,
"e": 15561,
"s": 15552,
"text": "noob2000"
},
{
"code": null,
"e": 15574,
"s": 15561,
"text": "simmytarika5"
},
{
"code": null,
"e": 15578,
"s": 15574,
"text": "BFS"
},
{
"code": null,
"e": 15595,
"s": 15578,
"text": "Graph Traversals"
},
{
"code": null,
"e": 15609,
"s": 15595,
"text": "Shortest Path"
},
{
"code": null,
"e": 15622,
"s": 15609,
"text": "Backtracking"
},
{
"code": null,
"e": 15628,
"s": 15622,
"text": "Graph"
},
{
"code": null,
"e": 15638,
"s": 15628,
"text": "Recursion"
},
{
"code": null,
"e": 15648,
"s": 15638,
"text": "Recursion"
},
{
"code": null,
"e": 15654,
"s": 15648,
"text": "Graph"
},
{
"code": null,
"e": 15668,
"s": 15654,
"text": "Shortest Path"
},
{
"code": null,
"e": 15681,
"s": 15668,
"text": "Backtracking"
},
{
"code": null,
"e": 15685,
"s": 15681,
"text": "BFS"
}
] |
matplotlib.axes.Axes.twiny() in Python
|
21 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.twiny() function in axes module of matplotlib library is used to create a twin Axes sharing the yaxis.
Syntax: Axes.twiny(self)
Return value: This method is used to returns the following.
ax_twin : This returns the newly created Axes instance.
Below examples illustrate the matplotlib.axes.Axes.twiny() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib function# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np def GFG1(temp): return (5. / 9.) * (temp - 32) def GFG2(ax1): y1, y2 = ax1.get_ylim() ax_twin .set_ylim(GFG1(y1), GFG1(y2)) ax_twin .figure.canvas.draw() fig, ax1 = plt.subplots()ax_twin = ax1.twiny() ax1.callbacks.connect("ylim_changed", GFG2)ax1.plot(np.linspace(-40, 120, 100))ax1.set_ylim(0, 100) ax1.set_xlabel('Fahrenheit')ax_twin .set_xlabel('Celsius') fig.suptitle('matplotlib.axes.Axes.twiny()\ function Example\n\n', fontweight ="bold")plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt # Create some mock datat = np.arange(0.01, 10.0, 0.001)data1 = np.exp(t)data2 = np.sin(0.4 * np.pi * t) fig, ax1 = plt.subplots() color = 'tab:blue'ax1.set_ylabel('time (s)')ax1.set_xlabel('exp', color = color)ax1.plot(data1, t, color = color)ax1.tick_params(axis ='x', labelcolor = color) ax2 = ax1.twiny() color = 'tab:green'ax2.set_xlabel('sin', color = color)ax2.plot(data2, t, color = color)ax2.tick_params(axis ='x', labelcolor = color) fig.suptitle('matplotlib.axes.Axes.twiny()\ function Example\n\n', fontweight ="bold")plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Introduction To PYTHON
Python OOPs Concepts
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()
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 440,
"s": 328,
"text": "The Axes.twiny() function in axes module of matplotlib library is used to create a twin Axes sharing the yaxis."
},
{
"code": null,
"e": 465,
"s": 440,
"text": "Syntax: Axes.twiny(self)"
},
{
"code": null,
"e": 525,
"s": 465,
"text": "Return value: This method is used to returns the following."
},
{
"code": null,
"e": 581,
"s": 525,
"text": "ax_twin : This returns the newly created Axes instance."
},
{
"code": null,
"e": 669,
"s": 581,
"text": "Below examples illustrate the matplotlib.axes.Axes.twiny() function in matplotlib.axes:"
},
{
"code": null,
"e": 680,
"s": 669,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib function# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np def GFG1(temp): return (5. / 9.) * (temp - 32) def GFG2(ax1): y1, y2 = ax1.get_ylim() ax_twin .set_ylim(GFG1(y1), GFG1(y2)) ax_twin .figure.canvas.draw() fig, ax1 = plt.subplots()ax_twin = ax1.twiny() ax1.callbacks.connect(\"ylim_changed\", GFG2)ax1.plot(np.linspace(-40, 120, 100))ax1.set_ylim(0, 100) ax1.set_xlabel('Fahrenheit')ax_twin .set_xlabel('Celsius') fig.suptitle('matplotlib.axes.Axes.twiny()\\ function Example\\n\\n', fontweight =\"bold\")plt.show()",
"e": 1291,
"s": 680,
"text": null
},
{
"code": null,
"e": 1299,
"s": 1291,
"text": "Output:"
},
{
"code": null,
"e": 1310,
"s": 1299,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt # Create some mock datat = np.arange(0.01, 10.0, 0.001)data1 = np.exp(t)data2 = np.sin(0.4 * np.pi * t) fig, ax1 = plt.subplots() color = 'tab:blue'ax1.set_ylabel('time (s)')ax1.set_xlabel('exp', color = color)ax1.plot(data1, t, color = color)ax1.tick_params(axis ='x', labelcolor = color) ax2 = ax1.twiny() color = 'tab:green'ax2.set_xlabel('sin', color = color)ax2.plot(data2, t, color = color)ax2.tick_params(axis ='x', labelcolor = color) fig.suptitle('matplotlib.axes.Axes.twiny()\\ function Example\\n\\n', fontweight =\"bold\")plt.show()",
"e": 1945,
"s": 1310,
"text": null
},
{
"code": null,
"e": 1953,
"s": 1945,
"text": "Output:"
},
{
"code": null,
"e": 1971,
"s": 1953,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 1978,
"s": 1971,
"text": "Python"
},
{
"code": null,
"e": 2076,
"s": 1978,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2108,
"s": 2076,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2135,
"s": 2108,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2158,
"s": 2135,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2179,
"s": 2158,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2210,
"s": 2179,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2266,
"s": 2210,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2308,
"s": 2266,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2350,
"s": 2308,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2385,
"s": 2350,
"text": "Python - Pandas dataframe.append()"
}
] |
Importance of Thread Synchronization in Java
|
11 Apr, 2022
Our systems are working in a multithreading environment that becomes an important part for OS to provide better utilization of resources. The process of running two or more parts of the program simultaneously is known as Multithreading. A program is a set of instructions in which multiple processes are running and within a process, multiple threads are working. Threads are nothing but lightweight processes. For example, in the computer we are playing video games at the same time we are working with MS word and listen to music. So, these are the processes we are working on concurrently. In this, every application has multiple sub-processes i.e. threads. In the previous example, we listen to music in which we are having a music player as an application that contains multiple sub-processes which are running like managing playlist, accessing the internet, etc. So, threads are the task to be performed and multithreading is multiple tasks/processes getting executed at the same time in the same program.
This is the basic introduction of multithreading which will further help to understand the importance of thread synchronization.
Thread Priorities
In java, every thread is assigned with a priority that determines how the threads should be treated with respect to each other. Thread’s priority is used to decide when to switch from one running thread to the next. A higher priority thread can preempt a lower priority thread and may take more CPU time. In a simple way, a thread with higher priority gets the resource first as compared to the thread with lower priority. But, in case, when two threads with the same priority want the same resource then the situation becomes more complicated. So, in a multithreading environment, if threads with the same priority are working with the same resource give unwanted results or erroneous code.
Let’s take an example. In a room, we have multiple computers that are attached to a single printer. At one time, one computer wants to print a document, so it uses a printer. At the same time, another computer wants the printer to print its document. So, two computers are demanding the same resource i.e. printer. So if both the processes running together then the printer will print the document of one as well as of another computer. This will produce invalid output. Now, the same thing happens in the case of threads if two threads with the same priority or want the same resource leads to inconsistent output.
In java, when two or more threads try to access the same resource simultaneously it causes the java runtime to execute one or more threads slowly, or even suspend their execution. In order to overcome this problem, we have thread synchronization.
Synchronization means coordination between multiple processes/threads.
Types of synchronization:
There are two types of synchronization that are as follows:
Process synchronizationThread synchronization
Process synchronization
Thread synchronization
Here we will be mainly focusing on thread synchronization.
Thread synchronization basically refers to The concept of one thread execute at a time and the rest of the threads are in waiting state. This process is known as thread synchronization. It prevents the thread interference and inconsistency problem.
Synchronization is build using locks or monitor. In Java, a monitor is an object that is used as a mutually exclusive lock. Only a single thread at a time has the right to own a monitor. When a thread gets a lock then all other threads will get suspended which are trying to acquire the locked monitor. So, other threads are said to be waiting for the monitor, until the first thread exits the monitor. In a simple way, when a thread request a resource then that resource gets locked so that no other thread can work or do any modification until the resource gets released.
Thread Synchronization are of two types:
Mutual ExclusiveInter-Thread Communication
Mutual Exclusive
Inter-Thread Communication
A. Mutual Exclusive
While sharing any resource, this will keep the thread interfering with one another i.e. mutual exclusive. We can achieve this via
Synchronized Method
Synchronized Block
Static Synchronization
Synchronized Method
We can declare a method as synchronized using the “synchronized” keyword. This will make the code written inside the method thread-safe so that no other thread will execute while the resource is shared.
Implementation:
We will be proposing prints the two threads simultaneously showing the asynchronous behavior without thread synchronization.
Example 1:
Java
// Class 1// Helper class// Extending Thread classpublic class PrintTest extends Thread { // Non synchronized Code // Method 1 public void printThread(int n) { // This loop will print the currently executed // thread for (int i = 1; i <= 10; i++) { System.out.println("Thread " + n + " is working..."); // Try block to check for exceptions try { // Pause the execution of current thread // for 0.600 seconds using sleep() method Thread.sleep(600); } // Catch block to handle the exceptions catch (Exception ex) { // Overriding existing toString() method and // prints exception if occur System.out.println(ex.toString()); } } // Display message for better readability System.out.println("--------------------------"); try { // Pause the execution of current thread // for 0.1000 millisecond or 1sec using sleep // method Thread.sleep(1000); } catch (Exception ex) { // Printing the exception System.out.println(ex.toString()); } }} // Class 2// Helper class extending Thread Classpublic class Thread1 extends Thread { // Declaring variable of type Class1 PrintTest test; // Constructor for class1 Thread1(PrintTest p) { test = p; } // run() method of this class for // entry point for thread1 public void run() { // Calling method 1 as in above class test.printThread(1); }} // Class 3// Helper class extending Thread Classpublic class Thread2 extends Thread { // Declaring variable of type Class1 PrintTest test; // Constructor for class2 Thread2(PrintTest p) { test = p; } // run() method of this class for // entry point for thread2 public void run() { test.printThread(2); }} // Class 4// Main classpublic class SynchroTest { // Main driver method public static void main(String[] args) { // Creating object of class 1 inside main() method PrintTest p = new PrintTest(); // Passing the same object of class PrintTest to // both threads Thread1 t1 = new Thread1(p); Thread2 t2 = new Thread2(p); // Start executing the threads // using start() method t1.start(); t2.start(); // This will print both the threads simultaneously }}
Output:
Now using synchronized method, it will lock the object for the shared resource and gives the consistent output.
Example 2:
Java
// Java Program Illustrating Lock the Object for// the shared resource giving consistent output // Class 1// Helper class extending Thread classpublic class PrintTest extends Thread { // synchronized code // synchronized method will lock the object and // releases when thread is terminated or completed its // execution. synchronized public void printThread(int n) { for (int i = 1; i <= 10; i++) { System.out.println("Thread " + n + " is working..."); try { // pause the execution of current thread // for 600 millisecond Thread.sleep(600); } catch (Exception ex) { // overrides toString() method and prints // exception if occur System.out.println(ex.toString()); } } System.out.println("--------------------------"); try { // pause the execution of current thread for // 1000 millisecond Thread.sleep(1000); } catch (Exception ex) { System.out.println(ex.toString()); } }}// creating thread1 extending Thread Class public class Thread1 extends Thread { PrintTest test; Thread1(PrintTest p) { test = p; } public void run() // entry point for thread1 { test.printThread(1); }}// creating thread2 extending Thread Class public class Thread2 extends Thread { PrintTest test; Thread2(PrintTest p) { test = p; } public void run() // entry point for thread2 { test.printThread(2); }} public class SynchroTest { public static void main(String[] args) { PrintTest p = new PrintTest(); // passing the same object of class PrintTest to // both threads Thread1 t1 = new Thread1(p); Thread2 t2 = new Thread2(p); // start function will execute the threads t1.start(); t2.start(); }}
Output:
B. Synchronized Block
If we declare a block as synchronized, only the code which is written inside that block is executed sequentially not the complete code. This is used when we want sequential access to some part of code or to synchronize some part of code.
Syntax:
synchronized (object reference)
{
// Insert code here
}
Example
Java
// Java Program Illustrating Synchronized Code// Using synchronized block // Class 1// Helper class extending Thread classclass PrintTest extends Thread { // Method 1 // To print the thread public void printThread(int n) { // Making synchronized block that makes the block // synchronized synchronized (this) { // Iterating using for loop for (int i = 1; i <= 10; i++) { // Print message when these thread are // executing System.out.println("Thread " + n + " is working..."); // Try block to check for exceptions try { // Making thread to pause for 0.6 // seconds Thread.sleep(600); } // Catch block to handle exceptions catch (Exception ex) { // Print message when exception.s occur System.out.println(ex.toString()); } } } // Display message only System.out.println("--------------------------"); try { // Making thread t osleep for 1 sec Thread.sleep(1000); } catch (Exception ex) { System.out.println(ex.toString()); } }} // Class 2// Helper class extending Thread classclass Thread1 extends Thread { PrintTest test; Thread1(PrintTest p) { test = p; } public void run() { test.printThread(1); }} // Class 3// Helper class extending Thread classclass Thread2 extends Thread { PrintTest test; Thread2(PrintTest p) { test = p; } public void run() { test.printThread(2); }} // Class 4// Main classclass SynchroTest { // Main driver method public static void main(String[] args) { // Creating instance for class 1 inside main() PrintTest p = new PrintTest(); // Creating threads and // passing same object Thread1 t1 = new Thread1(p); Thread2 t2 = new Thread2(p); // Starting these thread using start() method t1.start(); t2.start(); }}
Output:
C. Static Synchronization
In this, the synchronized method is declared as “static” which means the lock or monitor is applied on the class not on the object so that only one thread will access the class at a time.
Example
Java
// Java Program Illustrate Synchronized// Using static synchronization // Class 1// Helper classclass PrintTest extends Thread { // Static synchronization locks the class PrintTest synchronized public static void printThread(int n) { for (int i = 1; i <= 10; i++) { // Print message when threads are executing System.out.println("Thread " + n + " is working..."); // Try block to check for exceptions try { // making thread to sleep for 0.6 seconds Thread.sleep(600); } // Catch block to handle the exceptions catch (Exception ex) { // Print message when exception occurs System.out.println(ex.toString()); } } // Display message for better readability System.out.println("--------------------------"); try { Thread.sleep(1000); } catch (Exception ex) { System.out.println(ex.toString()); } }} // Class 2// Helper class extending Thread classclass Thread1 extends Thread { // run() method for thread public void run() { // Passing the class not the object PrintTest.printThread(1); }} // Class 3// Helper class extending Thread classclass Thread2 extends Thread { public void run() { // Passing the class not the object PrintTest.printThread(2); }} // Class 4// Main classclass SynchroTest { // Main driver method public static void main(String[] args) { // No shared object // Creating objects of class 2 and 3 that // are extending to Thread class Thread1 t1 = new Thread1(); Thread2 t2 = new Thread2(); // Starting thread with help of start() method t1.start(); t2.start(); }}
Output:
simmytarika5
surindertarika1234
nnr223442
anikakapoor
surinderdawra388
sweetyty
sagartomar9927
germanshephered48
arorakashish0911
Java-Multithreading
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 1067,
"s": 53,
"text": "Our systems are working in a multithreading environment that becomes an important part for OS to provide better utilization of resources. The process of running two or more parts of the program simultaneously is known as Multithreading. A program is a set of instructions in which multiple processes are running and within a process, multiple threads are working. Threads are nothing but lightweight processes. For example, in the computer we are playing video games at the same time we are working with MS word and listen to music. So, these are the processes we are working on concurrently. In this, every application has multiple sub-processes i.e. threads. In the previous example, we listen to music in which we are having a music player as an application that contains multiple sub-processes which are running like managing playlist, accessing the internet, etc. So, threads are the task to be performed and multithreading is multiple tasks/processes getting executed at the same time in the same program. "
},
{
"code": null,
"e": 1196,
"s": 1067,
"text": "This is the basic introduction of multithreading which will further help to understand the importance of thread synchronization."
},
{
"code": null,
"e": 1214,
"s": 1196,
"text": "Thread Priorities"
},
{
"code": null,
"e": 1906,
"s": 1214,
"text": "In java, every thread is assigned with a priority that determines how the threads should be treated with respect to each other. Thread’s priority is used to decide when to switch from one running thread to the next. A higher priority thread can preempt a lower priority thread and may take more CPU time. In a simple way, a thread with higher priority gets the resource first as compared to the thread with lower priority. But, in case, when two threads with the same priority want the same resource then the situation becomes more complicated. So, in a multithreading environment, if threads with the same priority are working with the same resource give unwanted results or erroneous code."
},
{
"code": null,
"e": 2522,
"s": 1906,
"text": "Let’s take an example. In a room, we have multiple computers that are attached to a single printer. At one time, one computer wants to print a document, so it uses a printer. At the same time, another computer wants the printer to print its document. So, two computers are demanding the same resource i.e. printer. So if both the processes running together then the printer will print the document of one as well as of another computer. This will produce invalid output. Now, the same thing happens in the case of threads if two threads with the same priority or want the same resource leads to inconsistent output."
},
{
"code": null,
"e": 2770,
"s": 2522,
"text": "In java, when two or more threads try to access the same resource simultaneously it causes the java runtime to execute one or more threads slowly, or even suspend their execution. In order to overcome this problem, we have thread synchronization. "
},
{
"code": null,
"e": 2843,
"s": 2770,
"text": "Synchronization means coordination between multiple processes/threads. "
},
{
"code": null,
"e": 2869,
"s": 2843,
"text": "Types of synchronization:"
},
{
"code": null,
"e": 2929,
"s": 2869,
"text": "There are two types of synchronization that are as follows:"
},
{
"code": null,
"e": 2975,
"s": 2929,
"text": "Process synchronizationThread synchronization"
},
{
"code": null,
"e": 2999,
"s": 2975,
"text": "Process synchronization"
},
{
"code": null,
"e": 3022,
"s": 2999,
"text": "Thread synchronization"
},
{
"code": null,
"e": 3082,
"s": 3022,
"text": "Here we will be mainly focusing on thread synchronization. "
},
{
"code": null,
"e": 3331,
"s": 3082,
"text": "Thread synchronization basically refers to The concept of one thread execute at a time and the rest of the threads are in waiting state. This process is known as thread synchronization. It prevents the thread interference and inconsistency problem."
},
{
"code": null,
"e": 3905,
"s": 3331,
"text": "Synchronization is build using locks or monitor. In Java, a monitor is an object that is used as a mutually exclusive lock. Only a single thread at a time has the right to own a monitor. When a thread gets a lock then all other threads will get suspended which are trying to acquire the locked monitor. So, other threads are said to be waiting for the monitor, until the first thread exits the monitor. In a simple way, when a thread request a resource then that resource gets locked so that no other thread can work or do any modification until the resource gets released."
},
{
"code": null,
"e": 3946,
"s": 3905,
"text": "Thread Synchronization are of two types:"
},
{
"code": null,
"e": 3989,
"s": 3946,
"text": "Mutual ExclusiveInter-Thread Communication"
},
{
"code": null,
"e": 4006,
"s": 3989,
"text": "Mutual Exclusive"
},
{
"code": null,
"e": 4033,
"s": 4006,
"text": "Inter-Thread Communication"
},
{
"code": null,
"e": 4053,
"s": 4033,
"text": "A. Mutual Exclusive"
},
{
"code": null,
"e": 4183,
"s": 4053,
"text": "While sharing any resource, this will keep the thread interfering with one another i.e. mutual exclusive. We can achieve this via"
},
{
"code": null,
"e": 4203,
"s": 4183,
"text": "Synchronized Method"
},
{
"code": null,
"e": 4222,
"s": 4203,
"text": "Synchronized Block"
},
{
"code": null,
"e": 4245,
"s": 4222,
"text": "Static Synchronization"
},
{
"code": null,
"e": 4265,
"s": 4245,
"text": "Synchronized Method"
},
{
"code": null,
"e": 4468,
"s": 4265,
"text": "We can declare a method as synchronized using the “synchronized” keyword. This will make the code written inside the method thread-safe so that no other thread will execute while the resource is shared."
},
{
"code": null,
"e": 4484,
"s": 4468,
"text": "Implementation:"
},
{
"code": null,
"e": 4610,
"s": 4484,
"text": "We will be proposing prints the two threads simultaneously showing the asynchronous behavior without thread synchronization. "
},
{
"code": null,
"e": 4621,
"s": 4610,
"text": "Example 1:"
},
{
"code": null,
"e": 4626,
"s": 4621,
"text": "Java"
},
{
"code": "// Class 1// Helper class// Extending Thread classpublic class PrintTest extends Thread { // Non synchronized Code // Method 1 public void printThread(int n) { // This loop will print the currently executed // thread for (int i = 1; i <= 10; i++) { System.out.println(\"Thread \" + n + \" is working...\"); // Try block to check for exceptions try { // Pause the execution of current thread // for 0.600 seconds using sleep() method Thread.sleep(600); } // Catch block to handle the exceptions catch (Exception ex) { // Overriding existing toString() method and // prints exception if occur System.out.println(ex.toString()); } } // Display message for better readability System.out.println(\"--------------------------\"); try { // Pause the execution of current thread // for 0.1000 millisecond or 1sec using sleep // method Thread.sleep(1000); } catch (Exception ex) { // Printing the exception System.out.println(ex.toString()); } }} // Class 2// Helper class extending Thread Classpublic class Thread1 extends Thread { // Declaring variable of type Class1 PrintTest test; // Constructor for class1 Thread1(PrintTest p) { test = p; } // run() method of this class for // entry point for thread1 public void run() { // Calling method 1 as in above class test.printThread(1); }} // Class 3// Helper class extending Thread Classpublic class Thread2 extends Thread { // Declaring variable of type Class1 PrintTest test; // Constructor for class2 Thread2(PrintTest p) { test = p; } // run() method of this class for // entry point for thread2 public void run() { test.printThread(2); }} // Class 4// Main classpublic class SynchroTest { // Main driver method public static void main(String[] args) { // Creating object of class 1 inside main() method PrintTest p = new PrintTest(); // Passing the same object of class PrintTest to // both threads Thread1 t1 = new Thread1(p); Thread2 t2 = new Thread2(p); // Start executing the threads // using start() method t1.start(); t2.start(); // This will print both the threads simultaneously }}",
"e": 7184,
"s": 4626,
"text": null
},
{
"code": null,
"e": 7193,
"s": 7184,
"text": "Output: "
},
{
"code": null,
"e": 7307,
"s": 7193,
"text": "Now using synchronized method, it will lock the object for the shared resource and gives the consistent output. "
},
{
"code": null,
"e": 7319,
"s": 7307,
"text": "Example 2: "
},
{
"code": null,
"e": 7324,
"s": 7319,
"text": "Java"
},
{
"code": "// Java Program Illustrating Lock the Object for// the shared resource giving consistent output // Class 1// Helper class extending Thread classpublic class PrintTest extends Thread { // synchronized code // synchronized method will lock the object and // releases when thread is terminated or completed its // execution. synchronized public void printThread(int n) { for (int i = 1; i <= 10; i++) { System.out.println(\"Thread \" + n + \" is working...\"); try { // pause the execution of current thread // for 600 millisecond Thread.sleep(600); } catch (Exception ex) { // overrides toString() method and prints // exception if occur System.out.println(ex.toString()); } } System.out.println(\"--------------------------\"); try { // pause the execution of current thread for // 1000 millisecond Thread.sleep(1000); } catch (Exception ex) { System.out.println(ex.toString()); } }}// creating thread1 extending Thread Class public class Thread1 extends Thread { PrintTest test; Thread1(PrintTest p) { test = p; } public void run() // entry point for thread1 { test.printThread(1); }}// creating thread2 extending Thread Class public class Thread2 extends Thread { PrintTest test; Thread2(PrintTest p) { test = p; } public void run() // entry point for thread2 { test.printThread(2); }} public class SynchroTest { public static void main(String[] args) { PrintTest p = new PrintTest(); // passing the same object of class PrintTest to // both threads Thread1 t1 = new Thread1(p); Thread2 t2 = new Thread2(p); // start function will execute the threads t1.start(); t2.start(); }}",
"e": 9322,
"s": 7324,
"text": null
},
{
"code": null,
"e": 9330,
"s": 9322,
"text": "Output:"
},
{
"code": null,
"e": 9352,
"s": 9330,
"text": "B. Synchronized Block"
},
{
"code": null,
"e": 9590,
"s": 9352,
"text": "If we declare a block as synchronized, only the code which is written inside that block is executed sequentially not the complete code. This is used when we want sequential access to some part of code or to synchronize some part of code."
},
{
"code": null,
"e": 9598,
"s": 9590,
"text": "Syntax:"
},
{
"code": null,
"e": 9662,
"s": 9598,
"text": "synchronized (object reference) \n{ \n // Insert code here\n}"
},
{
"code": null,
"e": 9671,
"s": 9662,
"text": "Example "
},
{
"code": null,
"e": 9676,
"s": 9671,
"text": "Java"
},
{
"code": "// Java Program Illustrating Synchronized Code// Using synchronized block // Class 1// Helper class extending Thread classclass PrintTest extends Thread { // Method 1 // To print the thread public void printThread(int n) { // Making synchronized block that makes the block // synchronized synchronized (this) { // Iterating using for loop for (int i = 1; i <= 10; i++) { // Print message when these thread are // executing System.out.println(\"Thread \" + n + \" is working...\"); // Try block to check for exceptions try { // Making thread to pause for 0.6 // seconds Thread.sleep(600); } // Catch block to handle exceptions catch (Exception ex) { // Print message when exception.s occur System.out.println(ex.toString()); } } } // Display message only System.out.println(\"--------------------------\"); try { // Making thread t osleep for 1 sec Thread.sleep(1000); } catch (Exception ex) { System.out.println(ex.toString()); } }} // Class 2// Helper class extending Thread classclass Thread1 extends Thread { PrintTest test; Thread1(PrintTest p) { test = p; } public void run() { test.printThread(1); }} // Class 3// Helper class extending Thread classclass Thread2 extends Thread { PrintTest test; Thread2(PrintTest p) { test = p; } public void run() { test.printThread(2); }} // Class 4// Main classclass SynchroTest { // Main driver method public static void main(String[] args) { // Creating instance for class 1 inside main() PrintTest p = new PrintTest(); // Creating threads and // passing same object Thread1 t1 = new Thread1(p); Thread2 t2 = new Thread2(p); // Starting these thread using start() method t1.start(); t2.start(); }}",
"e": 11851,
"s": 9676,
"text": null
},
{
"code": null,
"e": 11860,
"s": 11851,
"text": "Output: "
},
{
"code": null,
"e": 11886,
"s": 11860,
"text": "C. Static Synchronization"
},
{
"code": null,
"e": 12074,
"s": 11886,
"text": "In this, the synchronized method is declared as “static” which means the lock or monitor is applied on the class not on the object so that only one thread will access the class at a time."
},
{
"code": null,
"e": 12084,
"s": 12074,
"text": "Example "
},
{
"code": null,
"e": 12089,
"s": 12084,
"text": "Java"
},
{
"code": "// Java Program Illustrate Synchronized// Using static synchronization // Class 1// Helper classclass PrintTest extends Thread { // Static synchronization locks the class PrintTest synchronized public static void printThread(int n) { for (int i = 1; i <= 10; i++) { // Print message when threads are executing System.out.println(\"Thread \" + n + \" is working...\"); // Try block to check for exceptions try { // making thread to sleep for 0.6 seconds Thread.sleep(600); } // Catch block to handle the exceptions catch (Exception ex) { // Print message when exception occurs System.out.println(ex.toString()); } } // Display message for better readability System.out.println(\"--------------------------\"); try { Thread.sleep(1000); } catch (Exception ex) { System.out.println(ex.toString()); } }} // Class 2// Helper class extending Thread classclass Thread1 extends Thread { // run() method for thread public void run() { // Passing the class not the object PrintTest.printThread(1); }} // Class 3// Helper class extending Thread classclass Thread2 extends Thread { public void run() { // Passing the class not the object PrintTest.printThread(2); }} // Class 4// Main classclass SynchroTest { // Main driver method public static void main(String[] args) { // No shared object // Creating objects of class 2 and 3 that // are extending to Thread class Thread1 t1 = new Thread1(); Thread2 t2 = new Thread2(); // Starting thread with help of start() method t1.start(); t2.start(); }}",
"e": 13972,
"s": 12089,
"text": null
},
{
"code": null,
"e": 13981,
"s": 13972,
"text": "Output: "
},
{
"code": null,
"e": 13994,
"s": 13981,
"text": "simmytarika5"
},
{
"code": null,
"e": 14013,
"s": 13994,
"text": "surindertarika1234"
},
{
"code": null,
"e": 14023,
"s": 14013,
"text": "nnr223442"
},
{
"code": null,
"e": 14035,
"s": 14023,
"text": "anikakapoor"
},
{
"code": null,
"e": 14052,
"s": 14035,
"text": "surinderdawra388"
},
{
"code": null,
"e": 14061,
"s": 14052,
"text": "sweetyty"
},
{
"code": null,
"e": 14076,
"s": 14061,
"text": "sagartomar9927"
},
{
"code": null,
"e": 14094,
"s": 14076,
"text": "germanshephered48"
},
{
"code": null,
"e": 14111,
"s": 14094,
"text": "arorakashish0911"
},
{
"code": null,
"e": 14131,
"s": 14111,
"text": "Java-Multithreading"
},
{
"code": null,
"e": 14136,
"s": 14131,
"text": "Java"
},
{
"code": null,
"e": 14141,
"s": 14136,
"text": "Java"
}
] |
Setting full screen iframe in JavaScript?
|
Following is the code for setting full screen iframe in JavaScript −
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-weight: 500;
font-size: 18px;
color: blueviolet;
}
.fullScreen {
width: 100vw;
height: 100vh;
}
</style>
</head>
<body>
<h1>Setting full screen iframe</h1>
<iframe class="frame" src="https://www.wikipedia.com" width="300px" height="200px"
></iframe>
<button class="Btn" style="margin: 15px;">Fullscreen</button>
<h3>Click on the above button to make the iframe go fullscreen</h3>
<script>
let BtnEle = document.querySelector(".Btn");
let frameEle = document.querySelector(".frame");
BtnEle.addEventListener("click", () => {
frameEle.className = "fullScreen";
});
</script>
</body>
</html>
On clicking the ‘Fullscreen’ button −
|
[
{
"code": null,
"e": 1131,
"s": 1062,
"text": "Following is the code for setting full screen iframe in JavaScript −"
},
{
"code": null,
"e": 1142,
"s": 1131,
"text": " Live Demo"
},
{
"code": null,
"e": 2059,
"s": 1142,
"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-weight: 500;\n font-size: 18px;\n color: blueviolet;\n }\n .fullScreen {\n width: 100vw;\n height: 100vh;\n }\n</style>\n</head>\n<body>\n<h1>Setting full screen iframe</h1>\n<iframe class=\"frame\" src=\"https://www.wikipedia.com\" width=\"300px\" height=\"200px\"\n></iframe>\n<button class=\"Btn\" style=\"margin: 15px;\">Fullscreen</button>\n<h3>Click on the above button to make the iframe go fullscreen</h3>\n<script>\n let BtnEle = document.querySelector(\".Btn\");\n let frameEle = document.querySelector(\".frame\");\n BtnEle.addEventListener(\"click\", () => {\n frameEle.className = \"fullScreen\";\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2097,
"s": 2059,
"text": "On clicking the ‘Fullscreen’ button −"
}
] |
Perl lock Function
|
This function places an advisory lock on a shared variable, or referenced object contained in THING until the lock goes out of scope.
lock() is a "weak keyword" : this means that if you've defined a function by this name before any calls to it, that function will be called instead.
Following is the simple syntax for this function −
lock THING
This function does not return any value.
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2354,
"s": 2220,
"text": "This function places an advisory lock on a shared variable, or referenced object contained in THING until the lock goes out of scope."
},
{
"code": null,
"e": 2503,
"s": 2354,
"text": "lock() is a \"weak keyword\" : this means that if you've defined a function by this name before any calls to it, that function will be called instead."
},
{
"code": null,
"e": 2554,
"s": 2503,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 2566,
"s": 2554,
"text": "lock THING\n"
},
{
"code": null,
"e": 2607,
"s": 2566,
"text": "This function does not return any value."
},
{
"code": null,
"e": 2642,
"s": 2607,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 2656,
"s": 2642,
"text": " Devi Killada"
},
{
"code": null,
"e": 2691,
"s": 2656,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2711,
"s": 2691,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 2744,
"s": 2711,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2760,
"s": 2744,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 2793,
"s": 2760,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2810,
"s": 2793,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 2843,
"s": 2810,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 2866,
"s": 2843,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 2901,
"s": 2866,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 2924,
"s": 2901,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 2931,
"s": 2924,
"text": " Print"
},
{
"code": null,
"e": 2942,
"s": 2931,
"text": " Add Notes"
}
] |
Get all MySQL records from the previous day (yesterday)?
|
To get the records from the previous day, the following is the syntax
select *from yourTableName where date(yourColumnName)= DATE(NOW() - INTERVAL 1 DAY);
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table yesterDayRecordsDemo
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> ArrivalDateTime datetime
-> );
Query OK, 0 rows affected (0.44 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into yesterDayRecordsDemo(ArrivalDateTime) values('2014-11-09 13:45:21');
Query OK, 1 row affected (0.11 sec)
mysql> insert into yesterDayRecordsDemo(ArrivalDateTime) values('2017-10-19 11:41:31');
Query OK, 1 row affected (0.15 sec)
mysql> insert into yesterDayRecordsDemo(ArrivalDateTime) values('2019-02-25 10:40:45');
Query OK, 1 row affected (0.14 sec)
mysql> insert into yesterDayRecordsDemo(ArrivalDateTime) values('2019-02-26 12:06:07');
Query OK, 1 row affected (0.15 sec)
mysql> insert into yesterDayRecordsDemo(ArrivalDateTime) values('2019-02-25 12:06:47');
Query OK, 1 row affected (0.19 sec)
mysql> insert into yesterDayRecordsDemo(ArrivalDateTime) values('2019-02-27 11:45:49');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement
mysql> select *from yesterDayRecordsDemo;
The following is the output
+----+---------------------+
| Id | ArrivalDateTime |
+----+---------------------+
| 1 | 2014-11-09 13:45:21 |
| 2 | 2017-10-19 11:41:31 |
| 3 | 2019-02-25 10:40:45 |
| 4 | 2019-02-26 12:06:07 |
| 5 | 2019-02-25 12:06:47 |
| 6 | 2019-02-27 11:45:49 |
+----+---------------------+
6 rows in set (0.00 sec)
Here is the query to get MySQL records from yesterday
mysql> select *from yesterDayRecordsDemo where date(ArrivalDateTime)= DATE(NOW() - INTERVAL 1 DAY);
The following is the output
+----+---------------------+
| Id | ArrivalDateTime |
+----+---------------------+
| 4 | 2019-02-26 12:06:07 |
+----+---------------------+
1 row in set (0.08 sec)
|
[
{
"code": null,
"e": 1132,
"s": 1062,
"text": "To get the records from the previous day, the following is the syntax"
},
{
"code": null,
"e": 1217,
"s": 1132,
"text": "select *from yourTableName where date(yourColumnName)= DATE(NOW() - INTERVAL 1 DAY);"
},
{
"code": null,
"e": 1314,
"s": 1217,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows"
},
{
"code": null,
"e": 1490,
"s": 1314,
"text": "mysql> create table yesterDayRecordsDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> ArrivalDateTime datetime\n -> );\nQuery OK, 0 rows affected (0.44 sec)"
},
{
"code": null,
"e": 1545,
"s": 1490,
"text": "Insert some records in the table using insert command."
},
{
"code": null,
"e": 1569,
"s": 1545,
"text": "The query is as follows"
},
{
"code": null,
"e": 2313,
"s": 1569,
"text": "mysql> insert into yesterDayRecordsDemo(ArrivalDateTime) values('2014-11-09 13:45:21');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into yesterDayRecordsDemo(ArrivalDateTime) values('2017-10-19 11:41:31');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into yesterDayRecordsDemo(ArrivalDateTime) values('2019-02-25 10:40:45');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into yesterDayRecordsDemo(ArrivalDateTime) values('2019-02-26 12:06:07');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into yesterDayRecordsDemo(ArrivalDateTime) values('2019-02-25 12:06:47');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into yesterDayRecordsDemo(ArrivalDateTime) values('2019-02-27 11:45:49');\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 2371,
"s": 2313,
"text": "Display all records from the table using select statement"
},
{
"code": null,
"e": 2413,
"s": 2371,
"text": "mysql> select *from yesterDayRecordsDemo;"
},
{
"code": null,
"e": 2441,
"s": 2413,
"text": "The following is the output"
},
{
"code": null,
"e": 2756,
"s": 2441,
"text": "+----+---------------------+\n| Id | ArrivalDateTime |\n+----+---------------------+\n| 1 | 2014-11-09 13:45:21 |\n| 2 | 2017-10-19 11:41:31 |\n| 3 | 2019-02-25 10:40:45 |\n| 4 | 2019-02-26 12:06:07 |\n| 5 | 2019-02-25 12:06:47 |\n| 6 | 2019-02-27 11:45:49 |\n+----+---------------------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2810,
"s": 2756,
"text": "Here is the query to get MySQL records from yesterday"
},
{
"code": null,
"e": 2910,
"s": 2810,
"text": "mysql> select *from yesterDayRecordsDemo where date(ArrivalDateTime)= DATE(NOW() - INTERVAL 1 DAY);"
},
{
"code": null,
"e": 2938,
"s": 2910,
"text": "The following is the output"
},
{
"code": null,
"e": 3107,
"s": 2938,
"text": "+----+---------------------+\n| Id | ArrivalDateTime |\n+----+---------------------+\n| 4 | 2019-02-26 12:06:07 |\n+----+---------------------+\n1 row in set (0.08 sec)"
}
] |
Basic calculator program using Python
|
In this program we will see how to accomplish the basic calculator functionalities of a calculator using a python program. Here we create individual functions to carry out the calculations and return the result. Also user input is accepted along with the choice of operator.
# This function performs additiion
def add(a, b):
return a + b
# This function performs subtraction
def subtract(a, b):
return a - b
# This function performs multiplication
def multiply(a, b):
return a * b
# This function performs division
def divide(a, b):
return a / b
print("Select an operation.")
print("+")
print("-")
print("*")
print("/")
# User input
choice = input("Enter operator to use:")
A = int(input("Enter first number: "))
B = int(input("Enter second number: "))
if choice == '+':
print(A,"+",B,"=", add(A,B))
elif choice == '-':
print(A,"-",B,"=", subtract(A,B))
elif choice == '*':
print(A,"*",B,"=", multiply(A,B))
elif choice == '/':
print(A,"/",B,"=", divide(A,B))
else:
print("Invalid input")
Running the above code gives us the following result −
Select an operation.
+
-
*
/
Enter operator to use: -
Enter first number: 34
Enter second number: 20
34 - 20 = 14
|
[
{
"code": null,
"e": 1337,
"s": 1062,
"text": "In this program we will see how to accomplish the basic calculator functionalities of a calculator using a python program. Here we create individual functions to carry out the calculations and return the result. Also user input is accepted along with the choice of operator."
},
{
"code": null,
"e": 2072,
"s": 1337,
"text": "# This function performs additiion\ndef add(a, b):\n return a + b\n# This function performs subtraction\ndef subtract(a, b):\n return a - b\n# This function performs multiplication\ndef multiply(a, b):\n return a * b\n# This function performs division\ndef divide(a, b):\nreturn a / b\nprint(\"Select an operation.\")\nprint(\"+\")\nprint(\"-\")\nprint(\"*\")\nprint(\"/\")\n# User input\nchoice = input(\"Enter operator to use:\")\nA = int(input(\"Enter first number: \"))\nB = int(input(\"Enter second number: \"))\nif choice == '+':\n print(A,\"+\",B,\"=\", add(A,B))\nelif choice == '-':\n print(A,\"-\",B,\"=\", subtract(A,B))\nelif choice == '*':\n print(A,\"*\",B,\"=\", multiply(A,B))\nelif choice == '/':\n print(A,\"/\",B,\"=\", divide(A,B))\nelse:\nprint(\"Invalid input\")"
},
{
"code": null,
"e": 2127,
"s": 2072,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2241,
"s": 2127,
"text": "Select an operation.\n+\n-\n*\n/\nEnter operator to use: -\nEnter first number: 34\nEnter second number: 20\n34 - 20 = 14"
}
] |
QuestDB vs. TimescaleDB. How to use the Time Series Benchmark... | by Kovid Rathee | Towards Data Science
|
In the world more connected than ever, billions of users are generating more data than ever. From human communication to the digital footprint we create, IoT sensors have become ubiquitous, and financial transactions are digitized. We have an explosion of the volume of time-centric data, and we are struggling to keep up with it all. Timeseries databases are on the rise. OSS projects like QuestDB, InfluxDB, TimescaleDB, and cloud-based solutions like Amazon Timestream, etc., are in higher demand than ever. Timeseries databases have officially come of age.
All these products are competing for more space in the time-series domain, and in doing that, they’re making each other better. This article will look at two major timeseries databases and compare them using an open-source benchmarking tool called TSBS — Time Series Benchmarking Suite. This benchmarking suite is based on the testing scripts originally developed at InfluxDB, later enhanced by other major timeseries databases, and currently maintained by TimescaleDB.
For traditional databases like MySQL and PostgreSQL, many popular options like HammerDB and sysbench are standard tools to measure database read and write performance. Similar tools exist for different types of databases. Performance testing makes sense when the benchmarking tool simulates real-life scenarios by creating realistic bursts and reading streams. The access pattern for timeseries databases is very different from a traditional database — that is why we need a tool like TSBS.
TSBS currently supports two kinds of loads:
IoT — emulates the IoT data generated from the sensors of a trucking company. Imagine tracking a trucking fleet with real-time diagnostic data from every truck in your fleet.
DevOps — emulates data usage generated by a server that tracks memory usage, CPU usage, disk usage, and so on. Imagine looking at the Grafana dashboard with these metrics and getting alerts on breaches.
For this tutorial, we will be using the DevOps option. First, you need to follow these steps:
Install Docker on your machine so that you can install and run QuestDB and TimescaleDB from Docker Hub.
Clone the TSBS repository — Once all three are up and running, clone the TSBS repository on your machine.
Note: This benchmark run was completed on a 16-core Intel(R) Xeon(R) Platinum 8175M CPU @ 2.50GHz with 128 GB RAM on AWS EC2.
We will test the performance of these two databases in four phases:
Generate DevOps data for one day, where nine different metrics are collected every 10 seconds for 200 devices. The data will be generated separately for QuestDB and TimescaleDB based on their respective formats. Use the tsbs_generate_data utility for this.
Load the generated data. Use the tsbs_load_questdb and tsbs_load utilities to load data into QuestDB and TimescaleDB, respectively. This allows us to test the ingestion and write speeds of each system.
Generate queries to run on the loaded data for QuestDB and TimescaleDB. Use the tsbs_generate_queries utility for this.
Execute generated queries on QuestDB and TimescaleDB using tsbs_run_queries_questdb and tsbs_run_queries_timescaledb respectively.
Let’s go through the scripts for each of these steps, one by one.
For the scope of this tutorial, we’ll limit the scale of the benchmark run to 200 devices. As mentioned above, the data will be generated for one day, tracking nine metrics for every one of the hundred devices every 10 seconds. Using the tsbs_generate_data command, you can generate test data for any of the supported databases and use cases.
Note: The data generated can occupy a lot of space. You can scale up or down based on your benchmarking requirements and availability of disk space.
Note: The files generated for the data will be of different sizes because of the different formats used by TimescaleDB and QuestDB. QuestDB uses Influx Line Protocol format which is much lighter than any other format out there.
Loading the data is even simpler than generating it. For TimescaleDB, you can use the common utility tsbs_load. For QuestDB, you can use the tsbs_load_questdb utility as it supports some QuestDB-specific flags like --ilp-bind-to for Influx Line Protocol binding port and --url signifying QuestDB’s REST endpoint. You can use the following commands to load the data into TimescaleDB and QuestDB, respectively:
Note: Please follow the instructions for TimescaleDB’s config.yaml file.
To get a better idea of load performance, you can try changing the --workers parameter. Please ensure that the benchmarking parameters and conditions for both databases are the same so that you get a fair comparison.
./tsbs_load load timescaledb --config=./config.yaml...Summary:loaded 174528000 metrics in 59.376sec with 8 workers (mean rate 2939386.10 metrics/sec)loaded 15552000 rows in 59.376sec with 8 workers (mean rate 261925.49 rows/sec)
./tsbs_load_questdb --file /tmp/questdb-data --workers 8...Summary:loaded 174528000 metrics in 18.223sec with 8 workers (mean rate 9577373.06 metrics/sec)loaded 15552000 rows in 18.223sec with 8 workers (mean rate 853429.28 rows/sec)
The write performance of QuestDB with eight workers, in this case, is ~3.2x faster than TimescaleDB. For the complete output of this benchmark run, please visit this GitHub repository.
The data set TSBS has generated for both QuestDB and TimescaleDB contains metrics for 200 hosts. To query all the readings where one metric is above a threshold across all hosts, we will use the query type high-cpu-all. To generate 1000 queries with different time ranges during that one day, you need to run the following commands:
In this tutorial, we’re running just one type of read query. You can choose from the different types of queries you can run to test the read performance.
Now that we’ve generated the data, loaded it into QuestDB and TimescaleDB, and also generated the benchmarking queries that we want to run, we can finally perform the read performance benchmark using the following commands:
Note: Ensure that the queries have been generated properly before running the commands. To do that, you can run less /tmp/timescaledb-queries-high-cpu-all or less /tmp/queries_questdb-high-cpu-all.
Run complete after 1000 queries with 8 workers (Overall query rate 25.78 queries/sec):TimescaleDB CPU over threshold, all hosts:min: 222.49ms, med: 274.94ms, mean: 308.60ms, max: 580.13ms, stddev: 73.70ms, sum: 308.6sec, count: 1000all queries :min: 222.49ms, med: 274.94ms, mean: 308.60ms, max: 580.13ms, stddev: 73.70ms, sum: 308.6sec, count: 1000wall clock time: 38.827242sec
Run complete after 1000 queries with 8 workers (Overall query rate 70.18 queries/sec):QuestDB CPU over threshold, all hosts:min: 92.71ms, med: 109.10ms, mean: 113.32ms, max: 382.57ms, stddev: 19.34ms, sum: 113.3sec, count: 1000all queries :min: 92.71ms, med: 109.10ms, mean: 113.32ms, max: 382.57ms, stddev: 19.34ms, sum: 113.3sec, count: 1000wall clock time: 14.275811sec
QuestDB executed the queries ~2.7x faster than TimescaleDB.
To summarize the read and write benchmarks results, we can say that QuestDB is significantly faster in writes than TimescaleDB and extremely faster in reads. When we talk about the read performance, concluding with just one type of query is probably not fair, which is why you can try running the TSBS suite on your own for different types of queries for both these databases. Here’s the summary:
QuestDB performed ~320 % faster than TimescaleDB for write/load workloads.
QuestDB performed ~270 % faster than TimescaleDB for read/analytical workloads.
TSBS is the de facto standard for benchmarking timeseries databases. In this tutorial, you learned how to use TSBS to compare two timeseries databases by easily generating test data and emulating realistic read and write loads. As mentioned before, TSBS currently supports test data generation for DevOps and IoT (vehicle diagnostics). You can create your test data generation scripts to create more use cases for, say, real-time weather tracking, traffic signals, financial markets, and so on.
|
[
{
"code": null,
"e": 733,
"s": 172,
"text": "In the world more connected than ever, billions of users are generating more data than ever. From human communication to the digital footprint we create, IoT sensors have become ubiquitous, and financial transactions are digitized. We have an explosion of the volume of time-centric data, and we are struggling to keep up with it all. Timeseries databases are on the rise. OSS projects like QuestDB, InfluxDB, TimescaleDB, and cloud-based solutions like Amazon Timestream, etc., are in higher demand than ever. Timeseries databases have officially come of age."
},
{
"code": null,
"e": 1203,
"s": 733,
"text": "All these products are competing for more space in the time-series domain, and in doing that, they’re making each other better. This article will look at two major timeseries databases and compare them using an open-source benchmarking tool called TSBS — Time Series Benchmarking Suite. This benchmarking suite is based on the testing scripts originally developed at InfluxDB, later enhanced by other major timeseries databases, and currently maintained by TimescaleDB."
},
{
"code": null,
"e": 1694,
"s": 1203,
"text": "For traditional databases like MySQL and PostgreSQL, many popular options like HammerDB and sysbench are standard tools to measure database read and write performance. Similar tools exist for different types of databases. Performance testing makes sense when the benchmarking tool simulates real-life scenarios by creating realistic bursts and reading streams. The access pattern for timeseries databases is very different from a traditional database — that is why we need a tool like TSBS."
},
{
"code": null,
"e": 1738,
"s": 1694,
"text": "TSBS currently supports two kinds of loads:"
},
{
"code": null,
"e": 1913,
"s": 1738,
"text": "IoT — emulates the IoT data generated from the sensors of a trucking company. Imagine tracking a trucking fleet with real-time diagnostic data from every truck in your fleet."
},
{
"code": null,
"e": 2116,
"s": 1913,
"text": "DevOps — emulates data usage generated by a server that tracks memory usage, CPU usage, disk usage, and so on. Imagine looking at the Grafana dashboard with these metrics and getting alerts on breaches."
},
{
"code": null,
"e": 2210,
"s": 2116,
"text": "For this tutorial, we will be using the DevOps option. First, you need to follow these steps:"
},
{
"code": null,
"e": 2314,
"s": 2210,
"text": "Install Docker on your machine so that you can install and run QuestDB and TimescaleDB from Docker Hub."
},
{
"code": null,
"e": 2420,
"s": 2314,
"text": "Clone the TSBS repository — Once all three are up and running, clone the TSBS repository on your machine."
},
{
"code": null,
"e": 2546,
"s": 2420,
"text": "Note: This benchmark run was completed on a 16-core Intel(R) Xeon(R) Platinum 8175M CPU @ 2.50GHz with 128 GB RAM on AWS EC2."
},
{
"code": null,
"e": 2614,
"s": 2546,
"text": "We will test the performance of these two databases in four phases:"
},
{
"code": null,
"e": 2871,
"s": 2614,
"text": "Generate DevOps data for one day, where nine different metrics are collected every 10 seconds for 200 devices. The data will be generated separately for QuestDB and TimescaleDB based on their respective formats. Use the tsbs_generate_data utility for this."
},
{
"code": null,
"e": 3073,
"s": 2871,
"text": "Load the generated data. Use the tsbs_load_questdb and tsbs_load utilities to load data into QuestDB and TimescaleDB, respectively. This allows us to test the ingestion and write speeds of each system."
},
{
"code": null,
"e": 3193,
"s": 3073,
"text": "Generate queries to run on the loaded data for QuestDB and TimescaleDB. Use the tsbs_generate_queries utility for this."
},
{
"code": null,
"e": 3324,
"s": 3193,
"text": "Execute generated queries on QuestDB and TimescaleDB using tsbs_run_queries_questdb and tsbs_run_queries_timescaledb respectively."
},
{
"code": null,
"e": 3390,
"s": 3324,
"text": "Let’s go through the scripts for each of these steps, one by one."
},
{
"code": null,
"e": 3733,
"s": 3390,
"text": "For the scope of this tutorial, we’ll limit the scale of the benchmark run to 200 devices. As mentioned above, the data will be generated for one day, tracking nine metrics for every one of the hundred devices every 10 seconds. Using the tsbs_generate_data command, you can generate test data for any of the supported databases and use cases."
},
{
"code": null,
"e": 3882,
"s": 3733,
"text": "Note: The data generated can occupy a lot of space. You can scale up or down based on your benchmarking requirements and availability of disk space."
},
{
"code": null,
"e": 4110,
"s": 3882,
"text": "Note: The files generated for the data will be of different sizes because of the different formats used by TimescaleDB and QuestDB. QuestDB uses Influx Line Protocol format which is much lighter than any other format out there."
},
{
"code": null,
"e": 4519,
"s": 4110,
"text": "Loading the data is even simpler than generating it. For TimescaleDB, you can use the common utility tsbs_load. For QuestDB, you can use the tsbs_load_questdb utility as it supports some QuestDB-specific flags like --ilp-bind-to for Influx Line Protocol binding port and --url signifying QuestDB’s REST endpoint. You can use the following commands to load the data into TimescaleDB and QuestDB, respectively:"
},
{
"code": null,
"e": 4592,
"s": 4519,
"text": "Note: Please follow the instructions for TimescaleDB’s config.yaml file."
},
{
"code": null,
"e": 4809,
"s": 4592,
"text": "To get a better idea of load performance, you can try changing the --workers parameter. Please ensure that the benchmarking parameters and conditions for both databases are the same so that you get a fair comparison."
},
{
"code": null,
"e": 5038,
"s": 4809,
"text": "./tsbs_load load timescaledb --config=./config.yaml...Summary:loaded 174528000 metrics in 59.376sec with 8 workers (mean rate 2939386.10 metrics/sec)loaded 15552000 rows in 59.376sec with 8 workers (mean rate 261925.49 rows/sec)"
},
{
"code": null,
"e": 5272,
"s": 5038,
"text": "./tsbs_load_questdb --file /tmp/questdb-data --workers 8...Summary:loaded 174528000 metrics in 18.223sec with 8 workers (mean rate 9577373.06 metrics/sec)loaded 15552000 rows in 18.223sec with 8 workers (mean rate 853429.28 rows/sec)"
},
{
"code": null,
"e": 5457,
"s": 5272,
"text": "The write performance of QuestDB with eight workers, in this case, is ~3.2x faster than TimescaleDB. For the complete output of this benchmark run, please visit this GitHub repository."
},
{
"code": null,
"e": 5790,
"s": 5457,
"text": "The data set TSBS has generated for both QuestDB and TimescaleDB contains metrics for 200 hosts. To query all the readings where one metric is above a threshold across all hosts, we will use the query type high-cpu-all. To generate 1000 queries with different time ranges during that one day, you need to run the following commands:"
},
{
"code": null,
"e": 5944,
"s": 5790,
"text": "In this tutorial, we’re running just one type of read query. You can choose from the different types of queries you can run to test the read performance."
},
{
"code": null,
"e": 6168,
"s": 5944,
"text": "Now that we’ve generated the data, loaded it into QuestDB and TimescaleDB, and also generated the benchmarking queries that we want to run, we can finally perform the read performance benchmark using the following commands:"
},
{
"code": null,
"e": 6366,
"s": 6168,
"text": "Note: Ensure that the queries have been generated properly before running the commands. To do that, you can run less /tmp/timescaledb-queries-high-cpu-all or less /tmp/queries_questdb-high-cpu-all."
},
{
"code": null,
"e": 6745,
"s": 6366,
"text": "Run complete after 1000 queries with 8 workers (Overall query rate 25.78 queries/sec):TimescaleDB CPU over threshold, all hosts:min: 222.49ms, med: 274.94ms, mean: 308.60ms, max: 580.13ms, stddev: 73.70ms, sum: 308.6sec, count: 1000all queries :min: 222.49ms, med: 274.94ms, mean: 308.60ms, max: 580.13ms, stddev: 73.70ms, sum: 308.6sec, count: 1000wall clock time: 38.827242sec"
},
{
"code": null,
"e": 7118,
"s": 6745,
"text": "Run complete after 1000 queries with 8 workers (Overall query rate 70.18 queries/sec):QuestDB CPU over threshold, all hosts:min: 92.71ms, med: 109.10ms, mean: 113.32ms, max: 382.57ms, stddev: 19.34ms, sum: 113.3sec, count: 1000all queries :min: 92.71ms, med: 109.10ms, mean: 113.32ms, max: 382.57ms, stddev: 19.34ms, sum: 113.3sec, count: 1000wall clock time: 14.275811sec"
},
{
"code": null,
"e": 7178,
"s": 7118,
"text": "QuestDB executed the queries ~2.7x faster than TimescaleDB."
},
{
"code": null,
"e": 7575,
"s": 7178,
"text": "To summarize the read and write benchmarks results, we can say that QuestDB is significantly faster in writes than TimescaleDB and extremely faster in reads. When we talk about the read performance, concluding with just one type of query is probably not fair, which is why you can try running the TSBS suite on your own for different types of queries for both these databases. Here’s the summary:"
},
{
"code": null,
"e": 7650,
"s": 7575,
"text": "QuestDB performed ~320 % faster than TimescaleDB for write/load workloads."
},
{
"code": null,
"e": 7730,
"s": 7650,
"text": "QuestDB performed ~270 % faster than TimescaleDB for read/analytical workloads."
}
] |
How to set the day of a date in JavaScript?
|
Following is the code to set the day of a date in JavaScript −
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,.sample {
font-size: 20px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>Setting day of the date in JavaScript</h1>
<div class="sample"></div>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to change the day of the above date object
</h3>
<script>
let sampleEle = document.querySelector('.sample');
let resEle = document.querySelector(".result");
let dateObj = new Date();
sampleEle.innerHTML = dateObj;
document.querySelector(".Btn").addEventListener("click", () => {
dateObj.setDate(28)
resEle.innerHTML = 'Changing day of the date = <br> '+dateObj;
});
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
|
[
{
"code": null,
"e": 1125,
"s": 1062,
"text": "Following is the code to set the day of a date in JavaScript −"
},
{
"code": null,
"e": 1136,
"s": 1125,
"text": " Live Demo"
},
{
"code": null,
"e": 2103,
"s": 1136,
"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,.sample {\n font-size: 20px;\n font-weight: 500;\n }\n</style>\n</head>\n<body>\n<h1>Setting day of the date in JavaScript</h1>\n<div class=\"sample\"></div>\n<div style=\"color: green;\" class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>\nClick on the above button to change the day of the above date object\n</h3>\n<script>\n let sampleEle = document.querySelector('.sample');\n let resEle = document.querySelector(\".result\");\n let dateObj = new Date();\n sampleEle.innerHTML = dateObj;\n document.querySelector(\".Btn\").addEventListener(\"click\", () => {\n dateObj.setDate(28)\n resEle.innerHTML = 'Changing day of the date = <br> '+dateObj;\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2154,
"s": 2103,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2192,
"s": 2154,
"text": "On clicking the ‘CLICK HERE’ button −"
}
] |
SQL DELETE Statement
|
The DELETE statement is used to delete existing records in a table.
Note: Be careful when deleting records in a table! Notice the
WHERE clause in the
DELETE statement.
The WHERE clause specifies which record(s) should be deleted. If
you omit the WHERE clause, all records in the table will be deleted!
Below is a selection from the "Customers" table in the Northwind sample
database:
The following SQL statement deletes the customer "Alfreds Futterkiste" from
the "Customers" table:
The "Customers" table will now look like this:
It is possible to delete all rows in a table without deleting the table. This
means that the table structure, attributes, and indexes will be intact:
The following SQL statement deletes all rows in the "Customers" table,
without deleting the table:
Delete all the records from the Customers table where the Country value is 'Norway'.
Customers
Country = 'Norway';
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 68,
"s": 0,
"text": "The DELETE statement is used to delete existing records in a table."
},
{
"code": null,
"e": 305,
"s": 68,
"text": "Note: Be careful when deleting records in a table! Notice the \nWHERE clause in the \nDELETE statement.\nThe WHERE clause specifies which record(s) should be deleted. If \nyou omit the WHERE clause, all records in the table will be deleted!"
},
{
"code": null,
"e": 388,
"s": 305,
"text": "Below is a selection from the \"Customers\" table in the Northwind sample \ndatabase:"
},
{
"code": null,
"e": 488,
"s": 388,
"text": "The following SQL statement deletes the customer \"Alfreds Futterkiste\" from \nthe \"Customers\" table:"
},
{
"code": null,
"e": 535,
"s": 488,
"text": "The \"Customers\" table will now look like this:"
},
{
"code": null,
"e": 686,
"s": 535,
"text": "It is possible to delete all rows in a table without deleting the table. This \nmeans that the table structure, attributes, and indexes will be intact:"
},
{
"code": null,
"e": 786,
"s": 686,
"text": "The following SQL statement deletes all rows in the \"Customers\" table, \nwithout deleting the table:"
},
{
"code": null,
"e": 871,
"s": 786,
"text": "Delete all the records from the Customers table where the Country value is 'Norway'."
},
{
"code": null,
"e": 904,
"s": 871,
"text": " Customers\n Country = 'Norway';\n"
},
{
"code": null,
"e": 923,
"s": 904,
"text": "Start the Exercise"
},
{
"code": null,
"e": 956,
"s": 923,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 998,
"s": 956,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1105,
"s": 998,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1124,
"s": 1105,
"text": "[email protected]"
}
] |
Result of sizeof operator using C++
|
Sizeof operator is one of the most used operators in C language used to compute the size of any data structure or data type that we pass through it. The sizeof operator returns unsigned integer type, and this operator can be applied to primitive and compound data types. We can use sizeof operator directly to data types and know the memory it is taking up −
#include <bits/stdc++.h>
using namespace std;
int main() {
cout << sizeof(int) << "\n";
cout << sizeof(char) << "\n";
cout << sizeof(float) << "\n";
cout << sizeof(long) << "\n";
return 0;
}
4
1
4
8
8
By using this functionality, we can know the space any variable of this data type takes up. The output also depends on the compiler as a 16_bit compiler will give a different value for int than a 32_bit compiler.
We can also apply this operation to an expression −
#include <bits/stdc++.h>
using namespace std;
int main() {
cout << sizeof(int) << "\n";
cout << sizeof(char) << "\n";
cout << sizeof(float) << "\n";
cout << sizeof(double) << "\n";
cout << sizeof(long) << "\n";
return 0;
}
4
4
As you can see, the previous value of x was four, and even after the prefix operation, it happens to remain the same. This is all because of the sizeof the operator because this operator is used during the compile-time, so it doesn’t change the value of the expression we applied.
There are various uses of the sizeof operator. Still, it is mainly used to determine a compound data type size like an array, structure, union, etc.
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5}; // the given array
int size = sizeof(arr) / sizeof(int); // calculating the size of array
cout << size << "\n"; // outputting the size of given array
}
5
Here firstly, we calculate the size of the whole array or calculate the memory it is taking up. Then we divide that number with the sizeof of the data type; in this program, it is int.
The second most important use case for this operator is allocating a dynamic memory, so we use the sizeof operator when allotting the space.
#include <bits/stdc++.h>
using namespace std;
int main() {
int* ptr = (int*)malloc(10 * sizeof(int)); // here we allot a memory of 40 bytes
// the sizeof(int) is 4 and we are allocating 10 blocks
// i.e. 40 bytes
}
In this article, we are discussing the uses of the sizeof operator and how this works. We also coded different types of its use cases to see the output and discuss it. We implemented the use cases of this operator in C++. We can write the same program in other languages such as C, Java, Python, etc. We hope you find this article helpful.
|
[
{
"code": null,
"e": 1421,
"s": 1062,
"text": "Sizeof operator is one of the most used operators in C language used to compute the size of any data structure or data type that we pass through it. The sizeof operator returns unsigned integer type, and this operator can be applied to primitive and compound data types. We can use sizeof operator directly to data types and know the memory it is taking up −"
},
{
"code": null,
"e": 1628,
"s": 1421,
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n cout << sizeof(int) << \"\\n\";\n cout << sizeof(char) << \"\\n\";\n cout << sizeof(float) << \"\\n\";\n cout << sizeof(long) << \"\\n\";\n return 0;\n}"
},
{
"code": null,
"e": 1638,
"s": 1628,
"text": "4\n1\n4\n8\n8"
},
{
"code": null,
"e": 1851,
"s": 1638,
"text": "By using this functionality, we can know the space any variable of this data type takes up. The output also depends on the compiler as a 16_bit compiler will give a different value for int than a 32_bit compiler."
},
{
"code": null,
"e": 1903,
"s": 1851,
"text": "We can also apply this operation to an expression −"
},
{
"code": null,
"e": 2145,
"s": 1903,
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n cout << sizeof(int) << \"\\n\";\n cout << sizeof(char) << \"\\n\";\n cout << sizeof(float) << \"\\n\";\n cout << sizeof(double) << \"\\n\";\n cout << sizeof(long) << \"\\n\";\n return 0;\n}"
},
{
"code": null,
"e": 2149,
"s": 2145,
"text": "4\n4"
},
{
"code": null,
"e": 2430,
"s": 2149,
"text": "As you can see, the previous value of x was four, and even after the prefix operation, it happens to remain the same. This is all because of the sizeof the operator because this operator is used during the compile-time, so it doesn’t change the value of the expression we applied."
},
{
"code": null,
"e": 2579,
"s": 2430,
"text": "There are various uses of the sizeof operator. Still, it is mainly used to determine a compound data type size like an array, structure, union, etc."
},
{
"code": null,
"e": 2832,
"s": 2579,
"text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n int arr[] = {1, 2, 3, 4, 5}; // the given array\n\n int size = sizeof(arr) / sizeof(int); // calculating the size of array\n\n cout << size << \"\\n\"; // outputting the size of given array\n}"
},
{
"code": null,
"e": 2834,
"s": 2832,
"text": "5"
},
{
"code": null,
"e": 3019,
"s": 2834,
"text": "Here firstly, we calculate the size of the whole array or calculate the memory it is taking up. Then we divide that number with the sizeof of the data type; in this program, it is int."
},
{
"code": null,
"e": 3160,
"s": 3019,
"text": "The second most important use case for this operator is allocating a dynamic memory, so we use the sizeof operator when allotting the space."
},
{
"code": null,
"e": 3386,
"s": 3160,
"text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n int* ptr = (int*)malloc(10 * sizeof(int)); // here we allot a memory of 40 bytes\n // the sizeof(int) is 4 and we are allocating 10 blocks\n // i.e. 40 bytes\n}"
},
{
"code": null,
"e": 3726,
"s": 3386,
"text": "In this article, we are discussing the uses of the sizeof operator and how this works. We also coded different types of its use cases to see the output and discuss it. We implemented the use cases of this operator in C++. We can write the same program in other languages such as C, Java, Python, etc. We hope you find this article helpful."
}
] |
Predict Any Cryptocurrency Applying NLP using Global News | by Federico Riveroll | Towards Data Science
|
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
On today’s harsh global economic conditions, traditional indicators and techniques can have poor performances (to say the least).
In this tutorial we’ll search for useful information on news and transform it to a numerical format using NLP to train a Machine Learning model which will predict the rise or fall of any given Cryptocurrency (using Python).
Have Python 3.1+ installed
Install pandas, sklearn and openblender (with pip)
$ pip install pandas OpenBlender scikit-learn
We can use any cryptocurrency. For this example, let’s use this Bitcoin dataset.
Let’s pull the daily price candles from the beginning of 2020.
import pandas as pdimport numpy as npimport OpenBlenderimport jsontoken = 'YOUR_TOKEN_HERE'action = 'API_getObservationsFromDataset'# ANCHOR: 'Bitcoin vs USD' parameters = { 'token' : token, 'id_dataset' : '5d4c3af79516290b01c83f51', 'date_filter':{"start_date" : "2020-01-01", "end_date" : "2020-08-29"} }df = pd.read_json(json.dumps(OpenBlender.call(action, parameters)['sample']), convert_dates=False, convert_axes=False).sort_values('timestamp', ascending=False)df.reset_index(drop=True, inplace=True)df['date'] = [OpenBlender.unixToDate(ts, timezone = 'GMT') for ts in df.timestamp]df = df.drop('timestamp', axis = 1)
Note: You need to create an account on openblender.io (free) and add your token (you’ll find it in the ‘Account’ section).
Let’s take a look.
print(df.shape)df.head()
We have 254 daily observations of Bitcoin prices since the beginning of the year.
*Note: The same pipeline which will be applied to these 24 hour candles can be applied to any size of candle (even per second).
On our Bitcoin data, we have a column ‘price’ with the closing price of the day and ‘open’ with the opening price of the day.
We want to get the percentage difference from the closing price with respect to the opening price so we have a variable with that day’s performance.
To get this variable we will calculate the logarithmic difference between the close and open price.
df['log_diff'] = np.log(df['price']) - np.log(df['open'])df
The ‘log_diff’ can be thought of as percentage change as it approximates it, for the purpose of this tutorial, they are practically equivalent.
(We can see the very high correlation with ‘change’)
Let’s take a look.
We can see a bearish behaviour through the year and a stable variation between -0.1 and 0.1 change (minding a violent outlier).
Now, let’s generate our target variable by setting “1” if the performance was positive (log_diff > 0) and “0” if else.
df['target'] = [1 if log_diff > 0 else 0 for log_diff in df['log_diff']]df
Simply put, our target will be to predict if the performance will be positive or not the following day (so we can make a potential trading decision).
Now, we want to time-blend external data with our Bitcoin data. Simply put, this means to outer join another dataset using the timestamp as key.
We can do this very easily with the OpenBlender API, but first we need to create a Unix Timestamp variable.
The Unix Timestamp is the number of seconds since 1970 on UTC, it is a very convenient format because it is the same in every time zone in the world!
format = '%d-%m-%Y %H:%M:%S'timezone = 'GMT'df['u_timestamp'] = OpenBlender.dateToUnix(df['date'], date_format = format, timezone = timezone)df = df[['date', 'timestamp', 'price', 'target']]df.head()
Now, let’s search for useful datasets that are time-intersected with ours.
search_keyword = 'bitcoin'df = df.sort_values('timestamp').reset_index(drop = True)print('From : ' + OpenBlender.unixToDate(min(df.timestamp)))print('Until: ' + OpenBlender.unixToDate(max(df.timestamp)))OpenBlender.searchTimeBlends(token, df.timestamp, search_keyword)
We retrieved several datasets on a list with their names, description, url to the interface and even the features, but more importantly, the percentage of time overlap (intersection) with our dataset.
After browsing through some, this one about Bitcoin News and latest threads looks interesting.
Now, from the above dataset, we are only interested in the ‘TEXT’ feature which contains the news. So let’s blend the news for the past 24 hours.
# We need to add the 'id_dataset' and the 'feature' name we want.blend_source = { 'id_dataset':'5ea2039095162936337156c9', 'feature' : 'text' }# Now, let's 'timeBlend' it to our datasetdf_blend = OpenBlender.timeBlend( token = token, anchor_ts = df.timestamp, blend_source = blend_source, blend_type = 'agg_in_intervals', interval_size = 60 * 60 * 24, direction = 'time_prior', interval_output = 'list', missing_values = 'raw')df = pd.concat([df, df_blend.loc[:, df_blend.columns != 'timestamp']], axis = 1)df.head()
The parameters for the Time Blend:
anchor_ts: We only need to send our timestamp column so that it can be used as an anchor to blend the external data.
blend_source: The information about the feature we want.
blend_type: ‘agg_in_intervals’ because we want 24 hour interval aggregation to each of our observations.
inverval_size: The size of the interval in seconds (24 hours in this case).
direction: ‘time_prior’ because we want the interval to gather observations from the prior 24 hours and not forward.
And now we have our same dataset but with 2 added columns. One with a list of the texts gathered within the 24 hour interval (‘last1days’) and the other with the count.
Now let’s be a bit more specific, and let’s try to gather ‘positive’ and ‘negative’ news with a filter adding some ngrams (off the top of my head).
# We add the ngrams to match on a 'positive' feature.positive_filter = {'name' : 'positive', 'match_ngrams': ['positive', 'buy', 'bull', 'boost']}blend_source = { 'id_dataset':'5ea2039095162936337156c9', 'feature' : 'text', 'filter_text' : positive_filter }df_blend = OpenBlender.timeBlend( token = token, anchor_ts = df.timestamp, blend_source = blend_source, blend_type = 'agg_in_intervals', interval_size = 60 * 60 * 24, direction = 'time_prior', interval_output = 'list', missing_values = 'raw')df = pd.concat([df, df_blend.loc[:, df_blend.columns != 'timestamp']], axis = 1)# And now the negativesnegative_filter = {'name' : 'negative', 'match_ngrams': ['negative', 'loss', 'drop', 'plummet', 'sell', 'fundraising']}blend_source = { 'id_dataset':'5ea2039095162936337156c9', 'feature' : 'text', 'filter_text' : negative_filter }df_blend = OpenBlender.timeBlend( token = token, anchor_ts = df.timestamp, blend_source = blend_source, blend_type = 'agg_in_intervals', #closest_observation interval_size = 60 * 60 * 24, direction = 'time_prior', interval_output = 'list', missing_values = 'raw')df = pd.concat([df, df_blend.loc[:, df_blend.columns != 'timestamp']], axis = 1)
Now we have 4 new columns, the number and list of ‘positive’ and ‘negative’ news.
Let’s take a look at the correlation between the target and the other numerical features.
features = ['target', 'BITCOIN_NE.text_COUNT_last1days:positive', 'BITCOIN_NE.text_COUNT_last1days:negative']df_anchor[features].corr()['target']
We can notice slight negative and positive correlations with our new generated features respectively.
Now let’s use a TextVectorizer to get a lot of auto generated token features.
I created this TextVectorizer on OpenBlender for the ‘text’ feature on the BTC News dataset with over 1200 ngrams.
Lets blend those features with ours. We can use the exact same code, we only need to pass the ‘id_textVectorizer’ on the blend_source.
# BTC Text Vectorizerblend_source = { 'id_textVectorizer':'5f739fe7951629649472e167' }df_blend = OpenBlender.timeBlend( token = token, anchor_ts = df_anchor.timestamp, blend_source = blend_source, blend_type = 'agg_in_intervals', interval_size = 60 * 60 * 24, direction = 'time_prior', interval_output = 'list', missing_values = 'raw') .add_prefix('VEC.')df_anchor = pd.concat([df_anchor, df_blend.loc[:, df_blend.columns != 'timestamp']], axis = 1)df_anchor.head()
Now we have a 1229 column dataset with binary features of ngram occurrences on the aggregated news of each interval, aligned with our target.
Now, let’s apply some simple ML to view some results.
from sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import accuracy_scorefrom sklearn.metrics import precision_score# We drop correlated features because with so many binary # ngram variables there's a lot of noisecorr_matrix = df_anchor.corr().abs()upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))df_anchor.drop([column for column in upper.columns if any(upper[column] > 0.5)], axis=1, inplace=True)# Now we separate in train/test setsX = df_.loc[:, df_.columns != 'target'].select_dtypes(include=[np.number]).drop(drop_cols, axis = 1).valuesy = df_.loc[:,['target']].valuesdiv = int(round(len(X) * 0.2))X_train = X[:div]y_train = y[:div]X_test = X[div:]y_test = y[div:]# Finally, we perform ML and see resultsrf = RandomForestRegressor(n_estimators = 1000, random_state=0)rf.fit(X_train, y_train)y_pred = rf.predict(X_test)df_res = pd.DataFrame({'y_test':y_test[:, 0], 'y_pred':y_pred})threshold = 0.5preds = [1 if val > threshold else 0 for val in df_res['y_pred']]print(metrics.confusion_matrix(preds, df_res['y_test']))print('Accuracy Score:')print(accuracy_score(preds, df_res['y_test']))print('Precision Score:')print(precision_score(preds, df_res['y_test']))
While the overall Accuracy isn’t impressive, we are particularly interested in the ‘Precision Score’ as our goal is to detect which following days will most likely have an uprise (and avoid downfalls).
How we read the above confusion matrix is:
Our model predicted ‘uprise’ 102 times, from those, 84 were actual uprises and 17 were not (0.83 Precision Score).
In total, there were 157 uprises. Our model detected 84 of them and missed 73.
In total, there were 32 ‘downfall’ (or simply not ‘uprise’) cases, our model detected 15 of them and missed 17.
In other words, if the priority is to avoid downfalls -even if it means sacrificing a lot of ‘uprise’ cases-, this model worked well in this period of time.
We can also say that if the priority was to avoid missing uprises (even if a few downfalls infiltrated), this model with this threshold would not not be a good option at all.
|
[
{
"code": null,
"e": 472,
"s": 172,
"text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details."
},
{
"code": null,
"e": 602,
"s": 472,
"text": "On today’s harsh global economic conditions, traditional indicators and techniques can have poor performances (to say the least)."
},
{
"code": null,
"e": 826,
"s": 602,
"text": "In this tutorial we’ll search for useful information on news and transform it to a numerical format using NLP to train a Machine Learning model which will predict the rise or fall of any given Cryptocurrency (using Python)."
},
{
"code": null,
"e": 853,
"s": 826,
"text": "Have Python 3.1+ installed"
},
{
"code": null,
"e": 904,
"s": 853,
"text": "Install pandas, sklearn and openblender (with pip)"
},
{
"code": null,
"e": 950,
"s": 904,
"text": "$ pip install pandas OpenBlender scikit-learn"
},
{
"code": null,
"e": 1031,
"s": 950,
"text": "We can use any cryptocurrency. For this example, let’s use this Bitcoin dataset."
},
{
"code": null,
"e": 1094,
"s": 1031,
"text": "Let’s pull the daily price candles from the beginning of 2020."
},
{
"code": null,
"e": 1746,
"s": 1094,
"text": "import pandas as pdimport numpy as npimport OpenBlenderimport jsontoken = 'YOUR_TOKEN_HERE'action = 'API_getObservationsFromDataset'# ANCHOR: 'Bitcoin vs USD' parameters = { 'token' : token, 'id_dataset' : '5d4c3af79516290b01c83f51', 'date_filter':{\"start_date\" : \"2020-01-01\", \"end_date\" : \"2020-08-29\"} }df = pd.read_json(json.dumps(OpenBlender.call(action, parameters)['sample']), convert_dates=False, convert_axes=False).sort_values('timestamp', ascending=False)df.reset_index(drop=True, inplace=True)df['date'] = [OpenBlender.unixToDate(ts, timezone = 'GMT') for ts in df.timestamp]df = df.drop('timestamp', axis = 1)"
},
{
"code": null,
"e": 1869,
"s": 1746,
"text": "Note: You need to create an account on openblender.io (free) and add your token (you’ll find it in the ‘Account’ section)."
},
{
"code": null,
"e": 1888,
"s": 1869,
"text": "Let’s take a look."
},
{
"code": null,
"e": 1913,
"s": 1888,
"text": "print(df.shape)df.head()"
},
{
"code": null,
"e": 1995,
"s": 1913,
"text": "We have 254 daily observations of Bitcoin prices since the beginning of the year."
},
{
"code": null,
"e": 2123,
"s": 1995,
"text": "*Note: The same pipeline which will be applied to these 24 hour candles can be applied to any size of candle (even per second)."
},
{
"code": null,
"e": 2249,
"s": 2123,
"text": "On our Bitcoin data, we have a column ‘price’ with the closing price of the day and ‘open’ with the opening price of the day."
},
{
"code": null,
"e": 2398,
"s": 2249,
"text": "We want to get the percentage difference from the closing price with respect to the opening price so we have a variable with that day’s performance."
},
{
"code": null,
"e": 2498,
"s": 2398,
"text": "To get this variable we will calculate the logarithmic difference between the close and open price."
},
{
"code": null,
"e": 2558,
"s": 2498,
"text": "df['log_diff'] = np.log(df['price']) - np.log(df['open'])df"
},
{
"code": null,
"e": 2702,
"s": 2558,
"text": "The ‘log_diff’ can be thought of as percentage change as it approximates it, for the purpose of this tutorial, they are practically equivalent."
},
{
"code": null,
"e": 2755,
"s": 2702,
"text": "(We can see the very high correlation with ‘change’)"
},
{
"code": null,
"e": 2774,
"s": 2755,
"text": "Let’s take a look."
},
{
"code": null,
"e": 2902,
"s": 2774,
"text": "We can see a bearish behaviour through the year and a stable variation between -0.1 and 0.1 change (minding a violent outlier)."
},
{
"code": null,
"e": 3021,
"s": 2902,
"text": "Now, let’s generate our target variable by setting “1” if the performance was positive (log_diff > 0) and “0” if else."
},
{
"code": null,
"e": 3096,
"s": 3021,
"text": "df['target'] = [1 if log_diff > 0 else 0 for log_diff in df['log_diff']]df"
},
{
"code": null,
"e": 3246,
"s": 3096,
"text": "Simply put, our target will be to predict if the performance will be positive or not the following day (so we can make a potential trading decision)."
},
{
"code": null,
"e": 3391,
"s": 3246,
"text": "Now, we want to time-blend external data with our Bitcoin data. Simply put, this means to outer join another dataset using the timestamp as key."
},
{
"code": null,
"e": 3499,
"s": 3391,
"text": "We can do this very easily with the OpenBlender API, but first we need to create a Unix Timestamp variable."
},
{
"code": null,
"e": 3649,
"s": 3499,
"text": "The Unix Timestamp is the number of seconds since 1970 on UTC, it is a very convenient format because it is the same in every time zone in the world!"
},
{
"code": null,
"e": 3935,
"s": 3649,
"text": "format = '%d-%m-%Y %H:%M:%S'timezone = 'GMT'df['u_timestamp'] = OpenBlender.dateToUnix(df['date'], date_format = format, timezone = timezone)df = df[['date', 'timestamp', 'price', 'target']]df.head()"
},
{
"code": null,
"e": 4010,
"s": 3935,
"text": "Now, let’s search for useful datasets that are time-intersected with ours."
},
{
"code": null,
"e": 4335,
"s": 4010,
"text": "search_keyword = 'bitcoin'df = df.sort_values('timestamp').reset_index(drop = True)print('From : ' + OpenBlender.unixToDate(min(df.timestamp)))print('Until: ' + OpenBlender.unixToDate(max(df.timestamp)))OpenBlender.searchTimeBlends(token, df.timestamp, search_keyword)"
},
{
"code": null,
"e": 4536,
"s": 4335,
"text": "We retrieved several datasets on a list with their names, description, url to the interface and even the features, but more importantly, the percentage of time overlap (intersection) with our dataset."
},
{
"code": null,
"e": 4631,
"s": 4536,
"text": "After browsing through some, this one about Bitcoin News and latest threads looks interesting."
},
{
"code": null,
"e": 4777,
"s": 4631,
"text": "Now, from the above dataset, we are only interested in the ‘TEXT’ feature which contains the news. So let’s blend the news for the past 24 hours."
},
{
"code": null,
"e": 5566,
"s": 4777,
"text": "# We need to add the 'id_dataset' and the 'feature' name we want.blend_source = { 'id_dataset':'5ea2039095162936337156c9', 'feature' : 'text' }# Now, let's 'timeBlend' it to our datasetdf_blend = OpenBlender.timeBlend( token = token, anchor_ts = df.timestamp, blend_source = blend_source, blend_type = 'agg_in_intervals', interval_size = 60 * 60 * 24, direction = 'time_prior', interval_output = 'list', missing_values = 'raw')df = pd.concat([df, df_blend.loc[:, df_blend.columns != 'timestamp']], axis = 1)df.head()"
},
{
"code": null,
"e": 5601,
"s": 5566,
"text": "The parameters for the Time Blend:"
},
{
"code": null,
"e": 5718,
"s": 5601,
"text": "anchor_ts: We only need to send our timestamp column so that it can be used as an anchor to blend the external data."
},
{
"code": null,
"e": 5775,
"s": 5718,
"text": "blend_source: The information about the feature we want."
},
{
"code": null,
"e": 5880,
"s": 5775,
"text": "blend_type: ‘agg_in_intervals’ because we want 24 hour interval aggregation to each of our observations."
},
{
"code": null,
"e": 5956,
"s": 5880,
"text": "inverval_size: The size of the interval in seconds (24 hours in this case)."
},
{
"code": null,
"e": 6073,
"s": 5956,
"text": "direction: ‘time_prior’ because we want the interval to gather observations from the prior 24 hours and not forward."
},
{
"code": null,
"e": 6242,
"s": 6073,
"text": "And now we have our same dataset but with 2 added columns. One with a list of the texts gathered within the 24 hour interval (‘last1days’) and the other with the count."
},
{
"code": null,
"e": 6390,
"s": 6242,
"text": "Now let’s be a bit more specific, and let’s try to gather ‘positive’ and ‘negative’ news with a filter adding some ngrams (off the top of my head)."
},
{
"code": null,
"e": 8214,
"s": 6390,
"text": "# We add the ngrams to match on a 'positive' feature.positive_filter = {'name' : 'positive', 'match_ngrams': ['positive', 'buy', 'bull', 'boost']}blend_source = { 'id_dataset':'5ea2039095162936337156c9', 'feature' : 'text', 'filter_text' : positive_filter }df_blend = OpenBlender.timeBlend( token = token, anchor_ts = df.timestamp, blend_source = blend_source, blend_type = 'agg_in_intervals', interval_size = 60 * 60 * 24, direction = 'time_prior', interval_output = 'list', missing_values = 'raw')df = pd.concat([df, df_blend.loc[:, df_blend.columns != 'timestamp']], axis = 1)# And now the negativesnegative_filter = {'name' : 'negative', 'match_ngrams': ['negative', 'loss', 'drop', 'plummet', 'sell', 'fundraising']}blend_source = { 'id_dataset':'5ea2039095162936337156c9', 'feature' : 'text', 'filter_text' : negative_filter }df_blend = OpenBlender.timeBlend( token = token, anchor_ts = df.timestamp, blend_source = blend_source, blend_type = 'agg_in_intervals', #closest_observation interval_size = 60 * 60 * 24, direction = 'time_prior', interval_output = 'list', missing_values = 'raw')df = pd.concat([df, df_blend.loc[:, df_blend.columns != 'timestamp']], axis = 1)"
},
{
"code": null,
"e": 8296,
"s": 8214,
"text": "Now we have 4 new columns, the number and list of ‘positive’ and ‘negative’ news."
},
{
"code": null,
"e": 8386,
"s": 8296,
"text": "Let’s take a look at the correlation between the target and the other numerical features."
},
{
"code": null,
"e": 8532,
"s": 8386,
"text": "features = ['target', 'BITCOIN_NE.text_COUNT_last1days:positive', 'BITCOIN_NE.text_COUNT_last1days:negative']df_anchor[features].corr()['target']"
},
{
"code": null,
"e": 8634,
"s": 8532,
"text": "We can notice slight negative and positive correlations with our new generated features respectively."
},
{
"code": null,
"e": 8712,
"s": 8634,
"text": "Now let’s use a TextVectorizer to get a lot of auto generated token features."
},
{
"code": null,
"e": 8827,
"s": 8712,
"text": "I created this TextVectorizer on OpenBlender for the ‘text’ feature on the BTC News dataset with over 1200 ngrams."
},
{
"code": null,
"e": 8962,
"s": 8827,
"text": "Lets blend those features with ours. We can use the exact same code, we only need to pass the ‘id_textVectorizer’ on the blend_source."
},
{
"code": null,
"e": 9689,
"s": 8962,
"text": "# BTC Text Vectorizerblend_source = { 'id_textVectorizer':'5f739fe7951629649472e167' }df_blend = OpenBlender.timeBlend( token = token, anchor_ts = df_anchor.timestamp, blend_source = blend_source, blend_type = 'agg_in_intervals', interval_size = 60 * 60 * 24, direction = 'time_prior', interval_output = 'list', missing_values = 'raw') .add_prefix('VEC.')df_anchor = pd.concat([df_anchor, df_blend.loc[:, df_blend.columns != 'timestamp']], axis = 1)df_anchor.head()"
},
{
"code": null,
"e": 9831,
"s": 9689,
"text": "Now we have a 1229 column dataset with binary features of ngram occurrences on the aggregated news of each interval, aligned with our target."
},
{
"code": null,
"e": 9885,
"s": 9831,
"text": "Now, let’s apply some simple ML to view some results."
},
{
"code": null,
"e": 11106,
"s": 9885,
"text": "from sklearn.ensemble import RandomForestRegressorfrom sklearn.metrics import accuracy_scorefrom sklearn.metrics import precision_score# We drop correlated features because with so many binary # ngram variables there's a lot of noisecorr_matrix = df_anchor.corr().abs()upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))df_anchor.drop([column for column in upper.columns if any(upper[column] > 0.5)], axis=1, inplace=True)# Now we separate in train/test setsX = df_.loc[:, df_.columns != 'target'].select_dtypes(include=[np.number]).drop(drop_cols, axis = 1).valuesy = df_.loc[:,['target']].valuesdiv = int(round(len(X) * 0.2))X_train = X[:div]y_train = y[:div]X_test = X[div:]y_test = y[div:]# Finally, we perform ML and see resultsrf = RandomForestRegressor(n_estimators = 1000, random_state=0)rf.fit(X_train, y_train)y_pred = rf.predict(X_test)df_res = pd.DataFrame({'y_test':y_test[:, 0], 'y_pred':y_pred})threshold = 0.5preds = [1 if val > threshold else 0 for val in df_res['y_pred']]print(metrics.confusion_matrix(preds, df_res['y_test']))print('Accuracy Score:')print(accuracy_score(preds, df_res['y_test']))print('Precision Score:')print(precision_score(preds, df_res['y_test']))"
},
{
"code": null,
"e": 11308,
"s": 11106,
"text": "While the overall Accuracy isn’t impressive, we are particularly interested in the ‘Precision Score’ as our goal is to detect which following days will most likely have an uprise (and avoid downfalls)."
},
{
"code": null,
"e": 11351,
"s": 11308,
"text": "How we read the above confusion matrix is:"
},
{
"code": null,
"e": 11466,
"s": 11351,
"text": "Our model predicted ‘uprise’ 102 times, from those, 84 were actual uprises and 17 were not (0.83 Precision Score)."
},
{
"code": null,
"e": 11545,
"s": 11466,
"text": "In total, there were 157 uprises. Our model detected 84 of them and missed 73."
},
{
"code": null,
"e": 11657,
"s": 11545,
"text": "In total, there were 32 ‘downfall’ (or simply not ‘uprise’) cases, our model detected 15 of them and missed 17."
},
{
"code": null,
"e": 11814,
"s": 11657,
"text": "In other words, if the priority is to avoid downfalls -even if it means sacrificing a lot of ‘uprise’ cases-, this model worked well in this period of time."
}
] |
How to Create Text Reveal Effect for Buttons using HTML and CSS ? - GeeksforGeeks
|
30 Jun, 2020
Buttons are the most important user interface component for any website. It is very important to design the buttons in a creatively unique way. The text-reveal effect for a button is used when it is used to reveal some offer or exciting content for enhancing the user experience.
Approach: The approach is to cover the button with a strip of the same dimension as of button and then moving it to anyone direction on mouse-hover.
HTML Code: The following code snippet implements the creation of a button.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title>Text Reveal Effect for Buttons</title> </head> <body> <button>GeeksforGeeks</button> </body></html>
CSS Code:
Step 1: Apply some basic styling to button like adding padding and border-radius to have rounded corners.
Step 2: Now use the before selector to create a strip of same dimension to cover the whole button.
Step 3: Now use hover selector to move the strip to any one direction as it is moved to the left in the example.
Note: You can move strip to any direction according to your need. Also you can use some other properties to tweak the effect according to you.
<style> button { position: absolute; top: 50%; left: 50%; font-size: 20px; padding: 15px; } button::before { content: ""; position: absolute; top: 0%; left: 0%; width: 100%; height: 100%; background: green; transition: 0.5s ease-in-out; } button:hover::before { left: -100%; }</style>
Complete Code: It is the combination of the above two sections of code.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title> Text Reveal Effect for Buttons </title> <style> button { position: absolute; top: 50%; left: 50%; font-size: 20px; padding: 15px; } button::before { content: ""; position: absolute; top: 0%; left: 0%; width: 100%; height: 100%; background: green; transition: 0.5s ease-in-out; } button:hover::before { left: -100%; } </style></head> <body> <button>GeeksforGeeks</button></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
How to set space between the flexbox ?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
|
[
{
"code": null,
"e": 25931,
"s": 25903,
"text": "\n30 Jun, 2020"
},
{
"code": null,
"e": 26211,
"s": 25931,
"text": "Buttons are the most important user interface component for any website. It is very important to design the buttons in a creatively unique way. The text-reveal effect for a button is used when it is used to reveal some offer or exciting content for enhancing the user experience."
},
{
"code": null,
"e": 26360,
"s": 26211,
"text": "Approach: The approach is to cover the button with a strip of the same dimension as of button and then moving it to anyone direction on mouse-hover."
},
{
"code": null,
"e": 26435,
"s": 26360,
"text": "HTML Code: The following code snippet implements the creation of a button."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title>Text Reveal Effect for Buttons</title> </head> <body> <button>GeeksforGeeks</button> </body></html>",
"e": 26703,
"s": 26435,
"text": null
},
{
"code": null,
"e": 26713,
"s": 26703,
"text": "CSS Code:"
},
{
"code": null,
"e": 26819,
"s": 26713,
"text": "Step 1: Apply some basic styling to button like adding padding and border-radius to have rounded corners."
},
{
"code": null,
"e": 26918,
"s": 26819,
"text": "Step 2: Now use the before selector to create a strip of same dimension to cover the whole button."
},
{
"code": null,
"e": 27031,
"s": 26918,
"text": "Step 3: Now use hover selector to move the strip to any one direction as it is moved to the left in the example."
},
{
"code": null,
"e": 27174,
"s": 27031,
"text": "Note: You can move strip to any direction according to your need. Also you can use some other properties to tweak the effect according to you."
},
{
"code": "<style> button { position: absolute; top: 50%; left: 50%; font-size: 20px; padding: 15px; } button::before { content: \"\"; position: absolute; top: 0%; left: 0%; width: 100%; height: 100%; background: green; transition: 0.5s ease-in-out; } button:hover::before { left: -100%; }</style>",
"e": 27579,
"s": 27174,
"text": null
},
{
"code": null,
"e": 27651,
"s": 27579,
"text": "Complete Code: It is the combination of the above two sections of code."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title> Text Reveal Effect for Buttons </title> <style> button { position: absolute; top: 50%; left: 50%; font-size: 20px; padding: 15px; } button::before { content: \"\"; position: absolute; top: 0%; left: 0%; width: 100%; height: 100%; background: green; transition: 0.5s ease-in-out; } button:hover::before { left: -100%; } </style></head> <body> <button>GeeksforGeeks</button></body> </html>",
"e": 28425,
"s": 27651,
"text": null
},
{
"code": null,
"e": 28433,
"s": 28425,
"text": "Output:"
},
{
"code": null,
"e": 28570,
"s": 28433,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 28579,
"s": 28570,
"text": "CSS-Misc"
},
{
"code": null,
"e": 28589,
"s": 28579,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28593,
"s": 28589,
"text": "CSS"
},
{
"code": null,
"e": 28598,
"s": 28593,
"text": "HTML"
},
{
"code": null,
"e": 28615,
"s": 28598,
"text": "Web Technologies"
},
{
"code": null,
"e": 28642,
"s": 28615,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28647,
"s": 28642,
"text": "HTML"
},
{
"code": null,
"e": 28745,
"s": 28647,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28793,
"s": 28745,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 28848,
"s": 28793,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 28885,
"s": 28848,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 28949,
"s": 28885,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 28988,
"s": 28949,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29036,
"s": 28988,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 29096,
"s": 29036,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 29149,
"s": 29096,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 29210,
"s": 29149,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
How to Calculate Quartiles in R? - GeeksforGeeks
|
19 Dec, 2021
In this article, we will discuss how to calculate quartiles in the R programming language.
Quartiles are just special percentiles that occur after a certain percent of data has been covered.
First quartile: Refers to 25th percentile of the data. This depicts that 25% percent of data is under the produced value.
Second quartile: Refers to 50th percentile of the data. This depicts that 50% percent of data is under the produced value. This is also the median of the data.
Third quartile: Refers to the 75th percentile of the data. This predicts that 75% percent of the data is under the produced value.
To obtain the required quartiles, the quantile() function is used.
Syntax: quantile( data, probs)
Parameter:
data: data whose percentiles are to be calculated
probs: percentile value
R
x = c(2,13,5,36,12,50) res<-quantile(x, probs = c(0,0.25,0.5,0.75,1))res
Output:
0% 25% 50% 75% 100%
2.00 6.75 12.50 30.25 50.00
R
df<-data.frame(x = c(2,13,5,36,12,50),y = c('a','b','c','c','c','b')) res<-quantile(df$x, probs = c(0,0.25,0.5,0.75,1))res
Output:
0% 25% 50% 75% 100%
2.00 6.75 12.50 30.25 50.00
Picked
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
How to import an Excel File into R ?
Replace Specific Characters in String in R
R - if statement
Time Series Analysis in R
|
[
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 25334,
"s": 25242,
"text": "In this article, we will discuss how to calculate quartiles in the R programming language. "
},
{
"code": null,
"e": 25434,
"s": 25334,
"text": "Quartiles are just special percentiles that occur after a certain percent of data has been covered."
},
{
"code": null,
"e": 25556,
"s": 25434,
"text": "First quartile: Refers to 25th percentile of the data. This depicts that 25% percent of data is under the produced value."
},
{
"code": null,
"e": 25716,
"s": 25556,
"text": "Second quartile: Refers to 50th percentile of the data. This depicts that 50% percent of data is under the produced value. This is also the median of the data."
},
{
"code": null,
"e": 25847,
"s": 25716,
"text": "Third quartile: Refers to the 75th percentile of the data. This predicts that 75% percent of the data is under the produced value."
},
{
"code": null,
"e": 25914,
"s": 25847,
"text": "To obtain the required quartiles, the quantile() function is used."
},
{
"code": null,
"e": 25945,
"s": 25914,
"text": "Syntax: quantile( data, probs)"
},
{
"code": null,
"e": 25956,
"s": 25945,
"text": "Parameter:"
},
{
"code": null,
"e": 26006,
"s": 25956,
"text": "data: data whose percentiles are to be calculated"
},
{
"code": null,
"e": 26030,
"s": 26006,
"text": "probs: percentile value"
},
{
"code": null,
"e": 26032,
"s": 26030,
"text": "R"
},
{
"code": "x = c(2,13,5,36,12,50) res<-quantile(x, probs = c(0,0.25,0.5,0.75,1))res",
"e": 26106,
"s": 26032,
"text": null
},
{
"code": null,
"e": 26114,
"s": 26106,
"text": "Output:"
},
{
"code": null,
"e": 26176,
"s": 26114,
"text": " 0% 25% 50% 75% 100% \n2.00 6.75 12.50 30.25 50.00 "
},
{
"code": null,
"e": 26178,
"s": 26176,
"text": "R"
},
{
"code": "df<-data.frame(x = c(2,13,5,36,12,50),y = c('a','b','c','c','c','b')) res<-quantile(df$x, probs = c(0,0.25,0.5,0.75,1))res",
"e": 26302,
"s": 26178,
"text": null
},
{
"code": null,
"e": 26310,
"s": 26302,
"text": "Output:"
},
{
"code": null,
"e": 26371,
"s": 26310,
"text": " 0% 25% 50% 75% 100% \n2.00 6.75 12.50 30.25 50.00 "
},
{
"code": null,
"e": 26378,
"s": 26371,
"text": "Picked"
},
{
"code": null,
"e": 26391,
"s": 26378,
"text": "R-Statistics"
},
{
"code": null,
"e": 26402,
"s": 26391,
"text": "R Language"
},
{
"code": null,
"e": 26500,
"s": 26402,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26552,
"s": 26500,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26590,
"s": 26552,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26625,
"s": 26590,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 26683,
"s": 26625,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 26732,
"s": 26683,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 26782,
"s": 26732,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 26819,
"s": 26782,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 26862,
"s": 26819,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 26879,
"s": 26862,
"text": "R - if statement"
}
] |
Complex Queries in SQL. Texts on SQL are good at providing the... | by Robert de Graaf | Towards Data Science
|
Texts on SQL are good at providing the basic templates of SQL syntax, but sometimes the queries in those books are a little idealised compared to real life, with no more than two or three tables to join and a small number of fields to deal with. As a result, the queries themselves are usually no more than a dozen lines long.
It often happens in the wild that you end up joining across many tables with long winded ‘WHERE’ clauses that are easy to lose track of. These are hard enough to use the first time you employ them, but can be impossible to debug and understand if you need to re-use them. What can be done to make long and complicated queries easier to write and easier to read?
Firstly, though, ask yourself whether you need a long, complex query at all. Is it vital that your single query does all the work? If you still think it is, ask yourself at least two more times. In the excellent SQL Antipatterns, using a single query to solve a complex task or multiple tasks is identified as a key anti-pattern of queries, underlining its status as something to be wary of. One particular danger that this book identifies is that as the query becomes more difficult to follow, the risk of accidentally making a Cartesian join ( a join where the number of rows returned is the product of the number of rows in the tables involved in the join. By contrast, the maximum rows in an inner or outer join will be the number of rows in the largest table), taking a protracted period of time to return many unwanted rows grows enormously.
Hence the crucial piece of advice is to check whether or not the large query could be performed with more than one smaller easier to understand queries.
If you think that the complex query you are writing is completely unavoidable, there are a few ways to make it a less painful process.
Specify the column names within the query; don’t fall into the ‘SELECT *’ trap. A complex query that doesn’t specify which columns to return is likely to return columns that aren’t needed, making it harder to find the information you are looking for. Additionally, there is a decent chance of returning redundant columns.Format your query carefully to make it as readable as possible for another human being. Put each field to be selected on its own line, and put each new table joined onto on its own line, and each element of a ‘WHERE’ clause on its own line.Use meaningful aliases for tables to further aid readability. You are likely to need to refer to your tables multiple times within your query, and if you are working within someone else’s database with their naming convention, the table names can contain redundant information about they refer e.g. ‘MyDBTable1’ — so you call a table like that ‘T1’ as you already know you’re working within ‘MyDB’Create a redundant ‘Where’ clause e.g. ‘WHERE 0=0’ to enable easy testing of different parts of the WHERE clause (h/t former colleague Mark Watson). That is, because the ‘WHERE 0=0’ is automatically sitting at the beginning of the ‘WHERE’ clause, you can turn the rest of it on and off (e.g. comment it out) without a syntax error to check the effect.Plan your query, potentially making a sketch on paper so that you know what you are trying to achieve in terms of where your data is located and how the tables in your query relate to each other before you start converting it to code.
Specify the column names within the query; don’t fall into the ‘SELECT *’ trap. A complex query that doesn’t specify which columns to return is likely to return columns that aren’t needed, making it harder to find the information you are looking for. Additionally, there is a decent chance of returning redundant columns.
Format your query carefully to make it as readable as possible for another human being. Put each field to be selected on its own line, and put each new table joined onto on its own line, and each element of a ‘WHERE’ clause on its own line.
Use meaningful aliases for tables to further aid readability. You are likely to need to refer to your tables multiple times within your query, and if you are working within someone else’s database with their naming convention, the table names can contain redundant information about they refer e.g. ‘MyDBTable1’ — so you call a table like that ‘T1’ as you already know you’re working within ‘MyDB’
Create a redundant ‘Where’ clause e.g. ‘WHERE 0=0’ to enable easy testing of different parts of the WHERE clause (h/t former colleague Mark Watson). That is, because the ‘WHERE 0=0’ is automatically sitting at the beginning of the ‘WHERE’ clause, you can turn the rest of it on and off (e.g. comment it out) without a syntax error to check the effect.
Plan your query, potentially making a sketch on paper so that you know what you are trying to achieve in terms of where your data is located and how the tables in your query relate to each other before you start converting it to code.
The end result of taking these steps is that your code will look a bit like this:
SELECT Var1 , Var2 ... , VarNFROM Table1 T1 JOIN Table2 T2 on T1.Var1=T2.Var1 JOIN Table3 T3 on T1.Var1=T3.Var1 WHERE 0=0 AND T1.Var1 > 0
Overall, it is preferable to have more small queries rather than fewer large queries. Some database strutctures make this difficult however, for example if the you need to join on to get a secondary key to find what you are really need from table B. In these cases, planning and careful formatting can assist avoiding your code turning to spaghetti.
Robert de Graaf has written a number of pieces on SQL for Data Scientists, including most recently, SQL For Missing Values.
Robert de Graaf’s book, Managing Your Data Science Projects, is out now through Apress.
Follow Robert on Twitter
|
[
{
"code": null,
"e": 498,
"s": 171,
"text": "Texts on SQL are good at providing the basic templates of SQL syntax, but sometimes the queries in those books are a little idealised compared to real life, with no more than two or three tables to join and a small number of fields to deal with. As a result, the queries themselves are usually no more than a dozen lines long."
},
{
"code": null,
"e": 860,
"s": 498,
"text": "It often happens in the wild that you end up joining across many tables with long winded ‘WHERE’ clauses that are easy to lose track of. These are hard enough to use the first time you employ them, but can be impossible to debug and understand if you need to re-use them. What can be done to make long and complicated queries easier to write and easier to read?"
},
{
"code": null,
"e": 1708,
"s": 860,
"text": "Firstly, though, ask yourself whether you need a long, complex query at all. Is it vital that your single query does all the work? If you still think it is, ask yourself at least two more times. In the excellent SQL Antipatterns, using a single query to solve a complex task or multiple tasks is identified as a key anti-pattern of queries, underlining its status as something to be wary of. One particular danger that this book identifies is that as the query becomes more difficult to follow, the risk of accidentally making a Cartesian join ( a join where the number of rows returned is the product of the number of rows in the tables involved in the join. By contrast, the maximum rows in an inner or outer join will be the number of rows in the largest table), taking a protracted period of time to return many unwanted rows grows enormously."
},
{
"code": null,
"e": 1861,
"s": 1708,
"text": "Hence the crucial piece of advice is to check whether or not the large query could be performed with more than one smaller easier to understand queries."
},
{
"code": null,
"e": 1996,
"s": 1861,
"text": "If you think that the complex query you are writing is completely unavoidable, there are a few ways to make it a less painful process."
},
{
"code": null,
"e": 3540,
"s": 1996,
"text": "Specify the column names within the query; don’t fall into the ‘SELECT *’ trap. A complex query that doesn’t specify which columns to return is likely to return columns that aren’t needed, making it harder to find the information you are looking for. Additionally, there is a decent chance of returning redundant columns.Format your query carefully to make it as readable as possible for another human being. Put each field to be selected on its own line, and put each new table joined onto on its own line, and each element of a ‘WHERE’ clause on its own line.Use meaningful aliases for tables to further aid readability. You are likely to need to refer to your tables multiple times within your query, and if you are working within someone else’s database with their naming convention, the table names can contain redundant information about they refer e.g. ‘MyDBTable1’ — so you call a table like that ‘T1’ as you already know you’re working within ‘MyDB’Create a redundant ‘Where’ clause e.g. ‘WHERE 0=0’ to enable easy testing of different parts of the WHERE clause (h/t former colleague Mark Watson). That is, because the ‘WHERE 0=0’ is automatically sitting at the beginning of the ‘WHERE’ clause, you can turn the rest of it on and off (e.g. comment it out) without a syntax error to check the effect.Plan your query, potentially making a sketch on paper so that you know what you are trying to achieve in terms of where your data is located and how the tables in your query relate to each other before you start converting it to code."
},
{
"code": null,
"e": 3862,
"s": 3540,
"text": "Specify the column names within the query; don’t fall into the ‘SELECT *’ trap. A complex query that doesn’t specify which columns to return is likely to return columns that aren’t needed, making it harder to find the information you are looking for. Additionally, there is a decent chance of returning redundant columns."
},
{
"code": null,
"e": 4103,
"s": 3862,
"text": "Format your query carefully to make it as readable as possible for another human being. Put each field to be selected on its own line, and put each new table joined onto on its own line, and each element of a ‘WHERE’ clause on its own line."
},
{
"code": null,
"e": 4501,
"s": 4103,
"text": "Use meaningful aliases for tables to further aid readability. You are likely to need to refer to your tables multiple times within your query, and if you are working within someone else’s database with their naming convention, the table names can contain redundant information about they refer e.g. ‘MyDBTable1’ — so you call a table like that ‘T1’ as you already know you’re working within ‘MyDB’"
},
{
"code": null,
"e": 4853,
"s": 4501,
"text": "Create a redundant ‘Where’ clause e.g. ‘WHERE 0=0’ to enable easy testing of different parts of the WHERE clause (h/t former colleague Mark Watson). That is, because the ‘WHERE 0=0’ is automatically sitting at the beginning of the ‘WHERE’ clause, you can turn the rest of it on and off (e.g. comment it out) without a syntax error to check the effect."
},
{
"code": null,
"e": 5088,
"s": 4853,
"text": "Plan your query, potentially making a sketch on paper so that you know what you are trying to achieve in terms of where your data is located and how the tables in your query relate to each other before you start converting it to code."
},
{
"code": null,
"e": 5170,
"s": 5088,
"text": "The end result of taking these steps is that your code will look a bit like this:"
},
{
"code": null,
"e": 5368,
"s": 5170,
"text": "SELECT Var1 , Var2 ... , VarNFROM Table1 T1 JOIN Table2 T2 on T1.Var1=T2.Var1 JOIN Table3 T3 on T1.Var1=T3.Var1 WHERE 0=0 AND T1.Var1 > 0"
},
{
"code": null,
"e": 5718,
"s": 5368,
"text": "Overall, it is preferable to have more small queries rather than fewer large queries. Some database strutctures make this difficult however, for example if the you need to join on to get a secondary key to find what you are really need from table B. In these cases, planning and careful formatting can assist avoiding your code turning to spaghetti."
},
{
"code": null,
"e": 5842,
"s": 5718,
"text": "Robert de Graaf has written a number of pieces on SQL for Data Scientists, including most recently, SQL For Missing Values."
},
{
"code": null,
"e": 5930,
"s": 5842,
"text": "Robert de Graaf’s book, Managing Your Data Science Projects, is out now through Apress."
}
] |
Java program to delete duplicate characters from a given String
|
The interface Set does not allow duplicate elements, therefore, create a set object and try to add each element to it using the add() method in case of repetition of elements this method returns false −
If you try to add all the elements of the array to a Set, it accepts only unique elements so, to find duplicate characters in a given string
Convert it into a character array.
Try to insert elements of the above-created array into a hash set using add method.
If the addition is successful this method returns true.
Since Set doesn't allow duplicate elements this method returns 0 when you try to insert duplicate elements
Print those elements
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class DuplicateCharacters {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the required string value ::");
String reqString = sc.next();
char[] myArray = reqString.toCharArray();
System.out.println("indices of the duplicate characters in the given string :: ");
Set set = new HashSet();
for(int i=0; i<myArray.length; i++){
if(!set.add(myArray[i])){
System.out.println("Index :: "+i+" character :: "+myArray[i]);
}
}
}
}
Enter the required string value ::
malayalam
indices of the duplicate characters in the given string ::
Index :: 3 character :: a
Index :: 5 character :: a
Index :: 6 character :: l
Index :: 7 character :: a
Index :: 8 character :: m
|
[
{
"code": null,
"e": 1265,
"s": 1062,
"text": "The interface Set does not allow duplicate elements, therefore, create a set object and try to add each element to it using the add() method in case of repetition of elements this method returns false −"
},
{
"code": null,
"e": 1406,
"s": 1265,
"text": "If you try to add all the elements of the array to a Set, it accepts only unique elements so, to find duplicate characters in a given string"
},
{
"code": null,
"e": 1441,
"s": 1406,
"text": "Convert it into a character array."
},
{
"code": null,
"e": 1525,
"s": 1441,
"text": "Try to insert elements of the above-created array into a hash set using add method."
},
{
"code": null,
"e": 1581,
"s": 1525,
"text": "If the addition is successful this method returns true."
},
{
"code": null,
"e": 1688,
"s": 1581,
"text": "Since Set doesn't allow duplicate elements this method returns 0 when you try to insert duplicate elements"
},
{
"code": null,
"e": 1709,
"s": 1688,
"text": "Print those elements"
},
{
"code": null,
"e": 2353,
"s": 1709,
"text": "import java.util.HashSet;\nimport java.util.Scanner;\nimport java.util.Set;\n\npublic class DuplicateCharacters {\n public static void main(String args[]){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the required string value ::\");\n String reqString = sc.next();\n char[] myArray = reqString.toCharArray();\n System.out.println(\"indices of the duplicate characters in the given string :: \");\n Set set = new HashSet();\n\n for(int i=0; i<myArray.length; i++){\n if(!set.add(myArray[i])){\n System.out.println(\"Index :: \"+i+\" character :: \"+myArray[i]);\n }\n }\n }\n}"
},
{
"code": null,
"e": 2587,
"s": 2353,
"text": "Enter the required string value ::\nmalayalam\nindices of the duplicate characters in the given string ::\nIndex :: 3 character :: a\nIndex :: 5 character :: a\nIndex :: 6 character :: l\nIndex :: 7 character :: a\nIndex :: 8 character :: m"
}
] |
Program to Add Two Complex Numbers in C
|
Given are the two complex numbers in the form of a1+ ib1 and a2 + ib2, the task is to add these two complex numbers.
Complex numbers are those numbers which can be expressed in the form of “a+ib” where “a” and “b” are the real numbers and i is the imaginary number which is the solution of the expression x 2 = −1 as no real number satisfies the equation that’s why it is called as imaginary number.
Input
a1 = 3, b1 = 8
a2 = 5, b2 = 2
Output
Complex number 1: 3 + i8
Complex number 2: 5 + i2
Sum of the complex numbers: 8 + i10
Explanation
(3+i8) + (5+i2) = (3+5) + i(8+2) = 8 + i10
Input
a1 = 5, b1 = 3
a2 = 2, b2 = 2
Output
Complex number 1: 5 + i3
Complex number 2: 2 + i2
Sum of the complex numbers: 7 + i5
Explanation
(5+i3) + (2+i2) = (5+2) + i(3+2) = 7 + i5
Declare a struct for storing the real and imaginary numbers.
Declare a struct for storing the real and imaginary numbers.
Take the input and add the real numbers and imaginary numbers of all the complex numbers.
Take the input and add the real numbers and imaginary numbers of all the complex numbers.
Start
Decalre a struct complexnum with following elements
1. real
2. img
In function complexnum sumcomplex(complexnum a, complexnum b)
Step 1→ Declare a signature struct complexnum c
Step 2→ Set c.real as a.real + b.real
Step 3→ Set c.img as a.img + b.img
Step 4→ Return c
In function int main()
Step 1→ Declare and initialize complexnum a = {1, 2} and b = {4, 5}
Step 2→ Declare and set complexnum c as sumcomplex(a, b)
Step 3→ Print the first complex number
Step 4→ Print the second complex number
Step 5→ Print the sum of both in c.real, c.img
Stop
#include <stdio.h>
//structure for storing the real and imaginery
//values of complex number
struct complexnum{
int real, img;
};
complexnum sumcomplex(complexnum a, complexnum b){
struct complexnum c;
//Adding up two complex numbers
c.real = a.real + b.real;
c.img = a.img + b.img;
return c;
}
int main(){
struct complexnum a = {1, 2};
struct complexnum b = {4, 5};
struct complexnum c = sumcomplex(a, b);
printf("Complex number 1: %d + i%d\n", a.real, a.img);
printf("Complex number 2: %d + i%d\n", b.real, b.img);
printf("Sum of the complex numbers: %d + i%d\n", c.real, c.img);
return 0;
}
If run the above code it will generate the following output −
Complex number 1: 1 + i2
Complex number 2: 4 + i5
Sum of the complex numbers: 5 + i7
|
[
{
"code": null,
"e": 1179,
"s": 1062,
"text": "Given are the two complex numbers in the form of a1+ ib1 and a2 + ib2, the task is to add these two complex numbers."
},
{
"code": null,
"e": 1462,
"s": 1179,
"text": "Complex numbers are those numbers which can be expressed in the form of “a+ib” where “a” and “b” are the real numbers and i is the imaginary number which is the solution of the expression x 2 = −1 as no real number satisfies the equation that’s why it is called as imaginary number."
},
{
"code": null,
"e": 1469,
"s": 1462,
"text": "Input "
},
{
"code": null,
"e": 1499,
"s": 1469,
"text": "a1 = 3, b1 = 8\na2 = 5, b2 = 2"
},
{
"code": null,
"e": 1507,
"s": 1499,
"text": "Output "
},
{
"code": null,
"e": 1593,
"s": 1507,
"text": "Complex number 1: 3 + i8\nComplex number 2: 5 + i2\nSum of the complex numbers: 8 + i10"
},
{
"code": null,
"e": 1606,
"s": 1593,
"text": "Explanation "
},
{
"code": null,
"e": 1649,
"s": 1606,
"text": "(3+i8) + (5+i2) = (3+5) + i(8+2) = 8 + i10"
},
{
"code": null,
"e": 1656,
"s": 1649,
"text": "Input "
},
{
"code": null,
"e": 1686,
"s": 1656,
"text": "a1 = 5, b1 = 3\na2 = 2, b2 = 2"
},
{
"code": null,
"e": 1694,
"s": 1686,
"text": "Output "
},
{
"code": null,
"e": 1779,
"s": 1694,
"text": "Complex number 1: 5 + i3\nComplex number 2: 2 + i2\nSum of the complex numbers: 7 + i5"
},
{
"code": null,
"e": 1792,
"s": 1779,
"text": "Explanation "
},
{
"code": null,
"e": 1834,
"s": 1792,
"text": "(5+i3) + (2+i2) = (5+2) + i(3+2) = 7 + i5"
},
{
"code": null,
"e": 1895,
"s": 1834,
"text": "Declare a struct for storing the real and imaginary numbers."
},
{
"code": null,
"e": 1956,
"s": 1895,
"text": "Declare a struct for storing the real and imaginary numbers."
},
{
"code": null,
"e": 2046,
"s": 1956,
"text": "Take the input and add the real numbers and imaginary numbers of all the complex numbers."
},
{
"code": null,
"e": 2136,
"s": 2046,
"text": "Take the input and add the real numbers and imaginary numbers of all the complex numbers."
},
{
"code": null,
"e": 2721,
"s": 2136,
"text": "Start\nDecalre a struct complexnum with following elements\n 1. real\n 2. img\nIn function complexnum sumcomplex(complexnum a, complexnum b)\n Step 1→ Declare a signature struct complexnum c\n Step 2→ Set c.real as a.real + b.real\n Step 3→ Set c.img as a.img + b.img\n Step 4→ Return c\nIn function int main()\n Step 1→ Declare and initialize complexnum a = {1, 2} and b = {4, 5}\n Step 2→ Declare and set complexnum c as sumcomplex(a, b)\n Step 3→ Print the first complex number\n Step 4→ Print the second complex number\n Step 5→ Print the sum of both in c.real, c.img\nStop"
},
{
"code": null,
"e": 3354,
"s": 2721,
"text": "#include <stdio.h>\n//structure for storing the real and imaginery\n//values of complex number\nstruct complexnum{\n int real, img;\n};\ncomplexnum sumcomplex(complexnum a, complexnum b){\n struct complexnum c;\n //Adding up two complex numbers\n c.real = a.real + b.real;\n c.img = a.img + b.img;\n return c;\n}\nint main(){\n struct complexnum a = {1, 2};\n struct complexnum b = {4, 5};\n struct complexnum c = sumcomplex(a, b);\n printf(\"Complex number 1: %d + i%d\\n\", a.real, a.img);\n printf(\"Complex number 2: %d + i%d\\n\", b.real, b.img);\n printf(\"Sum of the complex numbers: %d + i%d\\n\", c.real, c.img);\n return 0;\n}"
},
{
"code": null,
"e": 3416,
"s": 3354,
"text": "If run the above code it will generate the following output −"
},
{
"code": null,
"e": 3501,
"s": 3416,
"text": "Complex number 1: 1 + i2\nComplex number 2: 4 + i5\nSum of the complex numbers: 5 + i7"
}
] |
CSS mask-image Property - GeeksforGeeks
|
10 Aug, 2021
The mask-image property in CSS is used to set the mask of an image or a text. It is used to form a mask layer for a particular element in CSS.
Syntax:
mask-image: none | <mask-source>
none: No mask layer is set and transparent black layer is set.
Syntax:
mask-image: none
Example:
In this example, no mask is created.
html
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <style> .container{ background-color: green; background-repeat: no-repeat; width: 400px; height: 400px; display: flex; align-items: center; justify-content: center; } .mask{ background:black; width: 200px; height: 200px; -webkit-mask-image: none; } .mask h1{ height: 400px; width: 400px; } wrap text h1 </style> <body> <div class="container"> <div class="mask"></div> </div> </body></html>
Output:
<mask-source>: Used to give the source of the image url.
Syntax:
mask-image: url();
Example :
The icon is a mask over background color which is black. It can be changed as required.
html
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <style> .container{ background-color: green; background-repeat: no-repeat; width: 400px; height: 400px; display: flex; align-items: center; justify-content: center; } .mask{ background:black; width: 200px; height: 200px; -webkit-mask-image: url("https://image.flaticon.com/icons/svg/942/942195.svg"); } .mask h1{ height: 400px; width: 400px; } wrap text h1 </style> <body> <div class="container"> <div class="mask"></div> </div> </body></html>
Output:
Browsers supported:
Chrome
Edge
Firefox
Opera
Safari
surindertarika1234
CSS-Properties
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 25376,
"s": 25348,
"text": "\n10 Aug, 2021"
},
{
"code": null,
"e": 25519,
"s": 25376,
"text": "The mask-image property in CSS is used to set the mask of an image or a text. It is used to form a mask layer for a particular element in CSS."
},
{
"code": null,
"e": 25527,
"s": 25519,
"text": "Syntax:"
},
{
"code": null,
"e": 25560,
"s": 25527,
"text": "mask-image: none | <mask-source>"
},
{
"code": null,
"e": 25624,
"s": 25560,
"text": "none: No mask layer is set and transparent black layer is set. "
},
{
"code": null,
"e": 25632,
"s": 25624,
"text": "Syntax:"
},
{
"code": null,
"e": 25649,
"s": 25632,
"text": "mask-image: none"
},
{
"code": null,
"e": 25658,
"s": 25649,
"text": "Example:"
},
{
"code": null,
"e": 25695,
"s": 25658,
"text": "In this example, no mask is created."
},
{
"code": null,
"e": 25700,
"s": 25695,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> </head> <style> .container{ background-color: green; background-repeat: no-repeat; width: 400px; height: 400px; display: flex; align-items: center; justify-content: center; } .mask{ background:black; width: 200px; height: 200px; -webkit-mask-image: none; } .mask h1{ height: 400px; width: 400px; } wrap text h1 </style> <body> <div class=\"container\"> <div class=\"mask\"></div> </div> </body></html>",
"e": 26524,
"s": 25700,
"text": null
},
{
"code": null,
"e": 26533,
"s": 26524,
"text": "Output: "
},
{
"code": null,
"e": 26590,
"s": 26533,
"text": "<mask-source>: Used to give the source of the image url."
},
{
"code": null,
"e": 26598,
"s": 26590,
"text": "Syntax:"
},
{
"code": null,
"e": 26617,
"s": 26598,
"text": "mask-image: url();"
},
{
"code": null,
"e": 26627,
"s": 26617,
"text": "Example :"
},
{
"code": null,
"e": 26715,
"s": 26627,
"text": "The icon is a mask over background color which is black. It can be changed as required."
},
{
"code": null,
"e": 26720,
"s": 26715,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> </head> <style> .container{ background-color: green; background-repeat: no-repeat; width: 400px; height: 400px; display: flex; align-items: center; justify-content: center; } .mask{ background:black; width: 200px; height: 200px; -webkit-mask-image: url(\"https://image.flaticon.com/icons/svg/942/942195.svg\"); } .mask h1{ height: 400px; width: 400px; } wrap text h1 </style> <body> <div class=\"container\"> <div class=\"mask\"></div> </div> </body></html>",
"e": 27598,
"s": 26720,
"text": null
},
{
"code": null,
"e": 27606,
"s": 27598,
"text": "Output:"
},
{
"code": null,
"e": 27626,
"s": 27606,
"text": "Browsers supported:"
},
{
"code": null,
"e": 27633,
"s": 27626,
"text": "Chrome"
},
{
"code": null,
"e": 27638,
"s": 27633,
"text": "Edge"
},
{
"code": null,
"e": 27646,
"s": 27638,
"text": "Firefox"
},
{
"code": null,
"e": 27652,
"s": 27646,
"text": "Opera"
},
{
"code": null,
"e": 27659,
"s": 27652,
"text": "Safari"
},
{
"code": null,
"e": 27678,
"s": 27659,
"text": "surindertarika1234"
},
{
"code": null,
"e": 27693,
"s": 27678,
"text": "CSS-Properties"
},
{
"code": null,
"e": 27697,
"s": 27693,
"text": "CSS"
},
{
"code": null,
"e": 27714,
"s": 27697,
"text": "Web Technologies"
},
{
"code": null,
"e": 27812,
"s": 27714,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27849,
"s": 27812,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 27878,
"s": 27849,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27917,
"s": 27878,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 27959,
"s": 27917,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 28006,
"s": 27959,
"text": "How to Create Time-Table schedule using HTML ?"
},
{
"code": null,
"e": 28048,
"s": 28006,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28081,
"s": 28048,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28124,
"s": 28081,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28169,
"s": 28124,
"text": "Convert a string to an integer in JavaScript"
}
] |
What does 'Space Complexity' mean? - GeeksforGeeks
|
24 Sep, 2021
Space Complexity: The term Space Complexity is misused for Auxiliary Space at many places. Following are the correct definitions of Auxiliary Space and Space Complexity.
Auxiliary Space is the extra space or temporary space used by an algorithm.
Space Complexity of an algorithm is the total space taken by the algorithm with respect to the input size. Space complexity includes both Auxiliary space and space used by input.
For example, if we want to compare standard sorting algorithms on the basis of space, then Auxiliary Space would be a better criterion than Space Complexity. Merge Sort uses O(n) auxiliary space, Insertion sort, and Heap Sort use O(1) auxiliary space. The space complexity of all these sorting algorithms is O(n) though.
Space complexity is a parallel concept to time complexity. If we need to create an array of size n, this will require O(n) space. If we create a two-dimensional array of size n*n, this will require O(n2) space.
In recursive calls stack space also counts.
Example :
int add (int n){
if (n <= 0){
return 0;
}
return n + add (n-1);
}
Here each call add a level to the stack :
1. add(4)
2. -> add(3)
3. -> add(2)
4. -> add(1)
5. -> add(0)
Each of these calls is added to call stack and takes up actual memory.
So it takes O(n) space.
However, just because you have n calls total doesn’t mean it takes O(n) space.
Look at the below function :
int addSequence (int n){
int sum = 0;
for (int i = 0; i < n; i++){
sum += pairSum(i, i+1);
}
return sum;
}
int pairSum(int x, int y){
return x + y;
}
There will be roughly O(n) calls to pairSum. However, those
calls do not exist simultaneously on the call stack,
so you only need O(1) space.
Note: It’s necessary to mention that space complexity depends on a variety of things such as the programming language, the compiler, or even the machine running the algorithm.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
tripathipriyanshu1998
hritikrommie
filipprayden
Analysis
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Understanding Time Complexity with Simple Examples
Time Complexity and Space Complexity
Practice Questions on Time Complexity Analysis
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Time Complexity of building a heap
Analysis of different sorting techniques
NP-Completeness | Set 1 (Introduction)
Analysis of Algorithms | Big-O analysis
Difference between Big Oh, Big Omega and Big Theta
|
[
{
"code": null,
"e": 34595,
"s": 34567,
"text": "\n24 Sep, 2021"
},
{
"code": null,
"e": 34766,
"s": 34595,
"text": "Space Complexity: The term Space Complexity is misused for Auxiliary Space at many places. Following are the correct definitions of Auxiliary Space and Space Complexity. "
},
{
"code": null,
"e": 34843,
"s": 34766,
"text": "Auxiliary Space is the extra space or temporary space used by an algorithm. "
},
{
"code": null,
"e": 35023,
"s": 34843,
"text": "Space Complexity of an algorithm is the total space taken by the algorithm with respect to the input size. Space complexity includes both Auxiliary space and space used by input. "
},
{
"code": null,
"e": 35345,
"s": 35023,
"text": "For example, if we want to compare standard sorting algorithms on the basis of space, then Auxiliary Space would be a better criterion than Space Complexity. Merge Sort uses O(n) auxiliary space, Insertion sort, and Heap Sort use O(1) auxiliary space. The space complexity of all these sorting algorithms is O(n) though. "
},
{
"code": null,
"e": 35556,
"s": 35345,
"text": "Space complexity is a parallel concept to time complexity. If we need to create an array of size n, this will require O(n) space. If we create a two-dimensional array of size n*n, this will require O(n2) space."
},
{
"code": null,
"e": 35601,
"s": 35556,
"text": "In recursive calls stack space also counts. "
},
{
"code": null,
"e": 35612,
"s": 35601,
"text": "Example : "
},
{
"code": null,
"e": 35925,
"s": 35612,
"text": "int add (int n){\n if (n <= 0){\n return 0;\n }\n return n + add (n-1);\n}\n\nHere each call add a level to the stack :\n\n1. add(4)\n2. -> add(3)\n3. -> add(2)\n4. -> add(1)\n5. -> add(0)\n\nEach of these calls is added to call stack and takes up actual memory.\nSo it takes O(n) space."
},
{
"code": null,
"e": 36004,
"s": 35925,
"text": "However, just because you have n calls total doesn’t mean it takes O(n) space."
},
{
"code": null,
"e": 36033,
"s": 36004,
"text": "Look at the below function :"
},
{
"code": null,
"e": 36356,
"s": 36033,
"text": "int addSequence (int n){\n int sum = 0;\n for (int i = 0; i < n; i++){\n sum += pairSum(i, i+1);\n }\n return sum;\n}\n\nint pairSum(int x, int y){\n return x + y;\n}\n\nThere will be roughly O(n) calls to pairSum. However, those \ncalls do not exist simultaneously on the call stack,\nso you only need O(1) space."
},
{
"code": null,
"e": 36532,
"s": 36356,
"text": "Note: It’s necessary to mention that space complexity depends on a variety of things such as the programming language, the compiler, or even the machine running the algorithm."
},
{
"code": null,
"e": 36658,
"s": 36532,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 36680,
"s": 36658,
"text": "tripathipriyanshu1998"
},
{
"code": null,
"e": 36693,
"s": 36680,
"text": "hritikrommie"
},
{
"code": null,
"e": 36706,
"s": 36693,
"text": "filipprayden"
},
{
"code": null,
"e": 36715,
"s": 36706,
"text": "Analysis"
},
{
"code": null,
"e": 36813,
"s": 36715,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36864,
"s": 36813,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 36901,
"s": 36864,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 36948,
"s": 36901,
"text": "Practice Questions on Time Complexity Analysis"
},
{
"code": null,
"e": 37031,
"s": 36948,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 37066,
"s": 37031,
"text": "Time Complexity of building a heap"
},
{
"code": null,
"e": 37107,
"s": 37066,
"text": "Analysis of different sorting techniques"
},
{
"code": null,
"e": 37146,
"s": 37107,
"text": "NP-Completeness | Set 1 (Introduction)"
},
{
"code": null,
"e": 37186,
"s": 37146,
"text": "Analysis of Algorithms | Big-O analysis"
}
] |
In-place Operations in PyTorch. What are they and why avoid them | by Alexandra Deis | Towards Data Science
|
Today’s advanced deep neural networks have millions of trainable parameters (for example, see the comparison in this paper) and trying to train them on free GPU’s like Kaggle or Google Colab often leads to running out of memory on GPU. There are several simple ways to reduce the GPU memory occupied by the model, for example:
Consider changing the architecture of the model or using the type of model with fewer trainable parameters (for example, choose DenseNet-121 over DenseNet-169). This approach can affect the model’s performance metrics.
Reduce the batch size or manually set the number of data loader workers. In this case, it takes longer for the model to train.
Using in-place operations in neural networks may help to avoid the downsides of approaches mentioned above while saving some GPU memory. However, it is not recommended to use in-place operations for several reasons.
In this article I would like to:
Describe what are the in-place operations and demonstrate how they might help to save the GPU memory.
Tell why we should avoid the in-place operations or use them with great caution.
“In-place operation is an operation that directly changes the content of a given linear algebra, vector, matrices (Tensor) without making a copy.” — The definition is taken from this Python tutorial.
According to the definition, in-place operations don’t make a copy of the input. That is why they can help to reduce memory usage when operating with high-dimensional data.
I want to demonstrate how in-place operations help to consume less GPU memory. To do this, I am going to measure allocated memory for both out-of-place ReLU and in-place ReLU from PyTorch, with this simple function:
Call the function to measure the allocated memory for the out-of-place ReLU:
I receive the output like this:
Allocated memory: 382.0Allocated max memory: 382.0
Then call the in-place ReLU as follows:
The output I receive is like:
Allocated memory: 0.0Allocated max memory: 0.0
Looks like using in-place operations helps us to save some GPU memory. However, we should be extremely cautious when using in-place operations and check twice. In the next section, I am going to tell you why.
The major downside of in-place operations is the fact that they might overwrite values required to compute gradients, which means breaking the training procedure of the model. That is what the official PyTorch autograd documentation says:
Supporting in-place operations in autograd is a hard matter, and we discourage their use in most cases. Autograd’s aggressive buffer freeing and reuse makes it very efficient and there are very few occasions when in-place operations actually lower memory usage by any significant amount. Unless you’re operating under heavy memory pressure, you might never need to use them.
There are two main reasons that limit the applicability of in-place operations:
1. In-place operations can potentially overwrite values required to compute gradients.
2. Every in-place operation actually requires the implementation to rewrite the computational graph. Out-of-place versions simply allocate new objects and keep references to the old graph, while in-place operations, require changing the creator of all inputs to the Function representing this operation.
The other reason for being careful with in-place operations is that their implementation is exceptionally tricky. That is why I would recommend using PyTorch standard in-place operations (like in-place ReLU above) instead of implementing one manually.
Let’s see an example of SiLU (or Swish-1) activation function. This is the out-of-place implementation of SiLU:
Let’s try to implement in-place SiLU using torch.sigmoid_ in-place function:
The code above incorrectly implements the in-place SiLU. We can make sure of that bu merely comparing the values returned by both functions. Actually, the function silu_inplace_1 returns sigmoid(input) * sigmoid(input)! The working example of the in-place implementation of SiLU using torch.sigmoid_ would be:
This small example demonstrates why we should be cautious and check twice when using in-place operations.
In this article:
I described the in-place operations and their purpose. Demonstrated how in-place operations help to consume less GPU memory.
I described the significant downsides of in-place operations. One should be very careful about using them and check the result twice.
|
[
{
"code": null,
"e": 499,
"s": 172,
"text": "Today’s advanced deep neural networks have millions of trainable parameters (for example, see the comparison in this paper) and trying to train them on free GPU’s like Kaggle or Google Colab often leads to running out of memory on GPU. There are several simple ways to reduce the GPU memory occupied by the model, for example:"
},
{
"code": null,
"e": 718,
"s": 499,
"text": "Consider changing the architecture of the model or using the type of model with fewer trainable parameters (for example, choose DenseNet-121 over DenseNet-169). This approach can affect the model’s performance metrics."
},
{
"code": null,
"e": 845,
"s": 718,
"text": "Reduce the batch size or manually set the number of data loader workers. In this case, it takes longer for the model to train."
},
{
"code": null,
"e": 1061,
"s": 845,
"text": "Using in-place operations in neural networks may help to avoid the downsides of approaches mentioned above while saving some GPU memory. However, it is not recommended to use in-place operations for several reasons."
},
{
"code": null,
"e": 1094,
"s": 1061,
"text": "In this article I would like to:"
},
{
"code": null,
"e": 1196,
"s": 1094,
"text": "Describe what are the in-place operations and demonstrate how they might help to save the GPU memory."
},
{
"code": null,
"e": 1277,
"s": 1196,
"text": "Tell why we should avoid the in-place operations or use them with great caution."
},
{
"code": null,
"e": 1477,
"s": 1277,
"text": "“In-place operation is an operation that directly changes the content of a given linear algebra, vector, matrices (Tensor) without making a copy.” — The definition is taken from this Python tutorial."
},
{
"code": null,
"e": 1650,
"s": 1477,
"text": "According to the definition, in-place operations don’t make a copy of the input. That is why they can help to reduce memory usage when operating with high-dimensional data."
},
{
"code": null,
"e": 1866,
"s": 1650,
"text": "I want to demonstrate how in-place operations help to consume less GPU memory. To do this, I am going to measure allocated memory for both out-of-place ReLU and in-place ReLU from PyTorch, with this simple function:"
},
{
"code": null,
"e": 1943,
"s": 1866,
"text": "Call the function to measure the allocated memory for the out-of-place ReLU:"
},
{
"code": null,
"e": 1975,
"s": 1943,
"text": "I receive the output like this:"
},
{
"code": null,
"e": 2026,
"s": 1975,
"text": "Allocated memory: 382.0Allocated max memory: 382.0"
},
{
"code": null,
"e": 2066,
"s": 2026,
"text": "Then call the in-place ReLU as follows:"
},
{
"code": null,
"e": 2096,
"s": 2066,
"text": "The output I receive is like:"
},
{
"code": null,
"e": 2143,
"s": 2096,
"text": "Allocated memory: 0.0Allocated max memory: 0.0"
},
{
"code": null,
"e": 2352,
"s": 2143,
"text": "Looks like using in-place operations helps us to save some GPU memory. However, we should be extremely cautious when using in-place operations and check twice. In the next section, I am going to tell you why."
},
{
"code": null,
"e": 2591,
"s": 2352,
"text": "The major downside of in-place operations is the fact that they might overwrite values required to compute gradients, which means breaking the training procedure of the model. That is what the official PyTorch autograd documentation says:"
},
{
"code": null,
"e": 2966,
"s": 2591,
"text": "Supporting in-place operations in autograd is a hard matter, and we discourage their use in most cases. Autograd’s aggressive buffer freeing and reuse makes it very efficient and there are very few occasions when in-place operations actually lower memory usage by any significant amount. Unless you’re operating under heavy memory pressure, you might never need to use them."
},
{
"code": null,
"e": 3046,
"s": 2966,
"text": "There are two main reasons that limit the applicability of in-place operations:"
},
{
"code": null,
"e": 3133,
"s": 3046,
"text": "1. In-place operations can potentially overwrite values required to compute gradients."
},
{
"code": null,
"e": 3437,
"s": 3133,
"text": "2. Every in-place operation actually requires the implementation to rewrite the computational graph. Out-of-place versions simply allocate new objects and keep references to the old graph, while in-place operations, require changing the creator of all inputs to the Function representing this operation."
},
{
"code": null,
"e": 3689,
"s": 3437,
"text": "The other reason for being careful with in-place operations is that their implementation is exceptionally tricky. That is why I would recommend using PyTorch standard in-place operations (like in-place ReLU above) instead of implementing one manually."
},
{
"code": null,
"e": 3801,
"s": 3689,
"text": "Let’s see an example of SiLU (or Swish-1) activation function. This is the out-of-place implementation of SiLU:"
},
{
"code": null,
"e": 3878,
"s": 3801,
"text": "Let’s try to implement in-place SiLU using torch.sigmoid_ in-place function:"
},
{
"code": null,
"e": 4188,
"s": 3878,
"text": "The code above incorrectly implements the in-place SiLU. We can make sure of that bu merely comparing the values returned by both functions. Actually, the function silu_inplace_1 returns sigmoid(input) * sigmoid(input)! The working example of the in-place implementation of SiLU using torch.sigmoid_ would be:"
},
{
"code": null,
"e": 4294,
"s": 4188,
"text": "This small example demonstrates why we should be cautious and check twice when using in-place operations."
},
{
"code": null,
"e": 4311,
"s": 4294,
"text": "In this article:"
},
{
"code": null,
"e": 4436,
"s": 4311,
"text": "I described the in-place operations and their purpose. Demonstrated how in-place operations help to consume less GPU memory."
}
] |
Convert ArrayList to Comma Separated String in Java - GeeksforGeeks
|
18 Nov, 2021
ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. In order to convert ArrayList to a comma-separated String, these are the approaches available in Java as listed and proposed below as follows:
Earlier before Java 8 there were only standard methods available in order for this conversion but with the introduction to the concept of Streams and Lambda, new methods do arise into play of which are all listed below:
Using append() method of StringBuilderUsing toString() methodUsing Apache Commons StringUtils classUsing Stream APIUsing String join() method of String class
Using append() method of StringBuilder
Using toString() method
Using Apache Commons StringUtils class
Using Stream API
Using String join() method of String class
Let us discuss each of the above methods proposed to deeper depth alongside programs to get a deep-dive understanding as follows:
StringBuilder in java represents a mutable sequence of characters. In the below example, we used StringBuilder’s append() method. The append method is used to concatenate or add a new set of characters in the last position of the existing string.
Syntax:
public StringBuilder append(char a)
Parameter: The method accepts a single parameter a which is the Char value whose string representation is to be appended.
Return Value: The method returns a string object after the append operation is performed.
Example:
Java
// Java program to Convert ArrayList to// Comma Separated String// Using append() method of StringBuilder // Importing required classesimport java.util.ArrayList; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of string type ArrayList<String> geeklist = new ArrayList<String>(); // Adding elements to ArrayList // using add() method geeklist.add("Hey"); geeklist.add("Geek"); geeklist.add("Welcome"); geeklist.add("to"); geeklist.add("geeksforgeeks"); geeklist.add("!"); StringBuilder str = new StringBuilder(""); // Traversing the ArrayList for (String eachstring : geeklist) { // Each element in ArrayList is appended // followed by comma str.append(eachstring).append(","); } // StringBuffer to String conversion String commaseparatedlist = str.toString(); // Condition check to remove the last comma if (commaseparatedlist.length() > 0) commaseparatedlist = commaseparatedlist.substring( 0, commaseparatedlist.length() - 1); // Printing the comma separated string System.out.println(commaseparatedlist); }}
Hey,Geek,Welcome,to,geeksforgeeks,!
toString() is an inbuilt method that returns the value given to it in string format. The below code uses the toString() method to convert ArrayList to a String. The method returns the single string on which the replace method is applied and specified characters are replaced (in this case brackets and spaces).
Syntax:
arraylist.toString()
// arraylist is an object of the ArrayList class
Return Value: It returns a string representation of the ArrayList
Example:
Java
// Java Program to Convert ArrayList to// Comma Separated String// Using toString() method // Importing required classesimport java.util.ArrayList; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of string type ArrayList<String> geekcourses = new ArrayList<String>(); // Adding elements to above empty ArrayList // using add() method geekcourses.add("Data Structures"); geekcourses.add("Algorithms"); geekcourses.add("Operating System"); geekcourses.add("Computer Networks"); geekcourses.add("Machine Learning"); geekcourses.add("Databases"); // Note: toString() method returns the output as // [Data Structure,Algorithms,...] // In order to replace '[', ']' and spaces with // empty strings to get comma separated values String commaseparatedlist = geekcourses.toString(); commaseparatedlist = commaseparatedlist.replace("[", "") .replace("]", "") .replace(" ", ""); // Printing the comma separated string System.out.println(commaseparatedlist); }}
DataStructures,Algorithms,OperatingSystem,ComputerNetworks,MachineLearning,Databases
Apache Commons library has a StringUtils class that provides a utility function for the string. The join method is used to convert ArrayList to comma-separated strings.
Example:
Java
// Java program to Convert ArrayList to// Comma Separated String// Using Apache Commons StringUtils class // Importing required classesimport java.util.ArrayList;import org.apache.commons.collections4.CollectionUtils; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of string type ArrayList<String> geekcourses = new ArrayList<String>(); // Adding elements to ArrayList // using add() method geekcourses.add("Data Structures"); geekcourses.add("Algorithms"); geekcourses.add("Operating System"); geekcourses.add("Computer Networks"); geekcourses.add("Machine Learning"); geekcourses.add("Databases"); // Mote: join() method used returns a single string // along with defined separator in every iteration String commalist = StringUtils.join(geekcourses, ","); // Printing the comma separated string System.out.println(commalist); }}
Output:
OutputDataStructures,Algorithms,OperatingSystem,ComputerNetworks,MachineLearning,Databases
Stream API was introduced in Java 8 and is used to process collections of objects. The joining() method of Collectors Class, in Java, is used to join various elements of a character or string array into a single string object.
Example
Java
// Java Program to Convert ArrayList to// Comma Separated String// Using Stream API // Importing required classesimport java.util.*;import java.util.stream.Collectors; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of string type ArrayList<String> geeklist = new ArrayList<String>(); // Adding elements to above ArrayList // using add() method geeklist.add("welcome"); geeklist.add("to"); geeklist.add("geeks"); geeklist.add("for"); geeklist.add("geeks"); // collect() method returns the result of the // intermediate operations performed on the stream String str = geeklist.stream().collect( Collectors.joining(",")); // Printing the comma separated string System.out.println(str); }}
welcome,to,geeks,for,geeks
We can convert ArrayList to a comma-separated String using StringJoiner which is a class in java.util package which is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. The join() method of the String class can be used to construct the same.
Example
Java
// Java program to Convert ArrayList to// Comma Separated String// Using String join() method // Importing required classesimport java.util.*;import java.util.stream.Collectors; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of string type ArrayList<String> geeklist = new ArrayList<String>(); // Adding elements to ArrayList // using add() method geeklist.add("welcome"); geeklist.add("to"); geeklist.add("geeks"); geeklist.add("for"); geeklist.add("geeks"); // Note: String.join() is used with a delimiter // comma along with the list String str = String.join(",", geeklist); // Printing the comma separated string System.out.println(str); }}
welcome,to,geeks,for,geeks
solankimayank
sweetyty
Java-ArrayList
Java-Collections
Java-String-Programs
Picked
Java
Java Programs
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Generics in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n18 Nov, 2021"
},
{
"code": null,
"e": 24216,
"s": 23948,
"text": "ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. In order to convert ArrayList to a comma-separated String, these are the approaches available in Java as listed and proposed below as follows:"
},
{
"code": null,
"e": 24438,
"s": 24216,
"text": "Earlier before Java 8 there were only standard methods available in order for this conversion but with the introduction to the concept of Streams and Lambda, new methods do arise into play of which are all listed below: "
},
{
"code": null,
"e": 24596,
"s": 24438,
"text": "Using append() method of StringBuilderUsing toString() methodUsing Apache Commons StringUtils classUsing Stream APIUsing String join() method of String class"
},
{
"code": null,
"e": 24635,
"s": 24596,
"text": "Using append() method of StringBuilder"
},
{
"code": null,
"e": 24659,
"s": 24635,
"text": "Using toString() method"
},
{
"code": null,
"e": 24698,
"s": 24659,
"text": "Using Apache Commons StringUtils class"
},
{
"code": null,
"e": 24715,
"s": 24698,
"text": "Using Stream API"
},
{
"code": null,
"e": 24758,
"s": 24715,
"text": "Using String join() method of String class"
},
{
"code": null,
"e": 24889,
"s": 24758,
"text": "Let us discuss each of the above methods proposed to deeper depth alongside programs to get a deep-dive understanding as follows:"
},
{
"code": null,
"e": 25136,
"s": 24889,
"text": "StringBuilder in java represents a mutable sequence of characters. In the below example, we used StringBuilder’s append() method. The append method is used to concatenate or add a new set of characters in the last position of the existing string."
},
{
"code": null,
"e": 25144,
"s": 25136,
"text": "Syntax:"
},
{
"code": null,
"e": 25180,
"s": 25144,
"text": "public StringBuilder append(char a)"
},
{
"code": null,
"e": 25302,
"s": 25180,
"text": "Parameter: The method accepts a single parameter a which is the Char value whose string representation is to be appended."
},
{
"code": null,
"e": 25392,
"s": 25302,
"text": "Return Value: The method returns a string object after the append operation is performed."
},
{
"code": null,
"e": 25401,
"s": 25392,
"text": "Example:"
},
{
"code": null,
"e": 25406,
"s": 25401,
"text": "Java"
},
{
"code": "// Java program to Convert ArrayList to// Comma Separated String// Using append() method of StringBuilder // Importing required classesimport java.util.ArrayList; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of string type ArrayList<String> geeklist = new ArrayList<String>(); // Adding elements to ArrayList // using add() method geeklist.add(\"Hey\"); geeklist.add(\"Geek\"); geeklist.add(\"Welcome\"); geeklist.add(\"to\"); geeklist.add(\"geeksforgeeks\"); geeklist.add(\"!\"); StringBuilder str = new StringBuilder(\"\"); // Traversing the ArrayList for (String eachstring : geeklist) { // Each element in ArrayList is appended // followed by comma str.append(eachstring).append(\",\"); } // StringBuffer to String conversion String commaseparatedlist = str.toString(); // Condition check to remove the last comma if (commaseparatedlist.length() > 0) commaseparatedlist = commaseparatedlist.substring( 0, commaseparatedlist.length() - 1); // Printing the comma separated string System.out.println(commaseparatedlist); }}",
"e": 26756,
"s": 25406,
"text": null
},
{
"code": null,
"e": 26792,
"s": 26756,
"text": "Hey,Geek,Welcome,to,geeksforgeeks,!"
},
{
"code": null,
"e": 27103,
"s": 26792,
"text": "toString() is an inbuilt method that returns the value given to it in string format. The below code uses the toString() method to convert ArrayList to a String. The method returns the single string on which the replace method is applied and specified characters are replaced (in this case brackets and spaces)."
},
{
"code": null,
"e": 27111,
"s": 27103,
"text": "Syntax:"
},
{
"code": null,
"e": 27181,
"s": 27111,
"text": "arraylist.toString()\n// arraylist is an object of the ArrayList class"
},
{
"code": null,
"e": 27247,
"s": 27181,
"text": "Return Value: It returns a string representation of the ArrayList"
},
{
"code": null,
"e": 27256,
"s": 27247,
"text": "Example:"
},
{
"code": null,
"e": 27261,
"s": 27256,
"text": "Java"
},
{
"code": "// Java Program to Convert ArrayList to// Comma Separated String// Using toString() method // Importing required classesimport java.util.ArrayList; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of string type ArrayList<String> geekcourses = new ArrayList<String>(); // Adding elements to above empty ArrayList // using add() method geekcourses.add(\"Data Structures\"); geekcourses.add(\"Algorithms\"); geekcourses.add(\"Operating System\"); geekcourses.add(\"Computer Networks\"); geekcourses.add(\"Machine Learning\"); geekcourses.add(\"Databases\"); // Note: toString() method returns the output as // [Data Structure,Algorithms,...] // In order to replace '[', ']' and spaces with // empty strings to get comma separated values String commaseparatedlist = geekcourses.toString(); commaseparatedlist = commaseparatedlist.replace(\"[\", \"\") .replace(\"]\", \"\") .replace(\" \", \"\"); // Printing the comma separated string System.out.println(commaseparatedlist); }}",
"e": 28489,
"s": 27261,
"text": null
},
{
"code": null,
"e": 28574,
"s": 28489,
"text": "DataStructures,Algorithms,OperatingSystem,ComputerNetworks,MachineLearning,Databases"
},
{
"code": null,
"e": 28743,
"s": 28574,
"text": "Apache Commons library has a StringUtils class that provides a utility function for the string. The join method is used to convert ArrayList to comma-separated strings."
},
{
"code": null,
"e": 28752,
"s": 28743,
"text": "Example:"
},
{
"code": null,
"e": 28757,
"s": 28752,
"text": "Java"
},
{
"code": "// Java program to Convert ArrayList to// Comma Separated String// Using Apache Commons StringUtils class // Importing required classesimport java.util.ArrayList;import org.apache.commons.collections4.CollectionUtils; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of string type ArrayList<String> geekcourses = new ArrayList<String>(); // Adding elements to ArrayList // using add() method geekcourses.add(\"Data Structures\"); geekcourses.add(\"Algorithms\"); geekcourses.add(\"Operating System\"); geekcourses.add(\"Computer Networks\"); geekcourses.add(\"Machine Learning\"); geekcourses.add(\"Databases\"); // Mote: join() method used returns a single string // along with defined separator in every iteration String commalist = StringUtils.join(geekcourses, \",\"); // Printing the comma separated string System.out.println(commalist); }}",
"e": 29811,
"s": 28757,
"text": null
},
{
"code": null,
"e": 29819,
"s": 29811,
"text": "Output:"
},
{
"code": null,
"e": 29910,
"s": 29819,
"text": "OutputDataStructures,Algorithms,OperatingSystem,ComputerNetworks,MachineLearning,Databases"
},
{
"code": null,
"e": 30137,
"s": 29910,
"text": "Stream API was introduced in Java 8 and is used to process collections of objects. The joining() method of Collectors Class, in Java, is used to join various elements of a character or string array into a single string object."
},
{
"code": null,
"e": 30145,
"s": 30137,
"text": "Example"
},
{
"code": null,
"e": 30150,
"s": 30145,
"text": "Java"
},
{
"code": "// Java Program to Convert ArrayList to// Comma Separated String// Using Stream API // Importing required classesimport java.util.*;import java.util.stream.Collectors; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of string type ArrayList<String> geeklist = new ArrayList<String>(); // Adding elements to above ArrayList // using add() method geeklist.add(\"welcome\"); geeklist.add(\"to\"); geeklist.add(\"geeks\"); geeklist.add(\"for\"); geeklist.add(\"geeks\"); // collect() method returns the result of the // intermediate operations performed on the stream String str = geeklist.stream().collect( Collectors.joining(\",\")); // Printing the comma separated string System.out.println(str); }}",
"e": 31051,
"s": 30150,
"text": null
},
{
"code": null,
"e": 31078,
"s": 31051,
"text": "welcome,to,geeks,for,geeks"
},
{
"code": null,
"e": 31429,
"s": 31078,
"text": "We can convert ArrayList to a comma-separated String using StringJoiner which is a class in java.util package which is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. The join() method of the String class can be used to construct the same."
},
{
"code": null,
"e": 31437,
"s": 31429,
"text": "Example"
},
{
"code": null,
"e": 31442,
"s": 31437,
"text": "Java"
},
{
"code": "// Java program to Convert ArrayList to// Comma Separated String// Using String join() method // Importing required classesimport java.util.*;import java.util.stream.Collectors; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of string type ArrayList<String> geeklist = new ArrayList<String>(); // Adding elements to ArrayList // using add() method geeklist.add(\"welcome\"); geeklist.add(\"to\"); geeklist.add(\"geeks\"); geeklist.add(\"for\"); geeklist.add(\"geeks\"); // Note: String.join() is used with a delimiter // comma along with the list String str = String.join(\",\", geeklist); // Printing the comma separated string System.out.println(str); }}",
"e": 32291,
"s": 31442,
"text": null
},
{
"code": null,
"e": 32318,
"s": 32291,
"text": "welcome,to,geeks,for,geeks"
},
{
"code": null,
"e": 32332,
"s": 32318,
"text": "solankimayank"
},
{
"code": null,
"e": 32341,
"s": 32332,
"text": "sweetyty"
},
{
"code": null,
"e": 32356,
"s": 32341,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 32373,
"s": 32356,
"text": "Java-Collections"
},
{
"code": null,
"e": 32394,
"s": 32373,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 32401,
"s": 32394,
"text": "Picked"
},
{
"code": null,
"e": 32406,
"s": 32401,
"text": "Java"
},
{
"code": null,
"e": 32420,
"s": 32406,
"text": "Java Programs"
},
{
"code": null,
"e": 32425,
"s": 32420,
"text": "Java"
},
{
"code": null,
"e": 32442,
"s": 32425,
"text": "Java-Collections"
},
{
"code": null,
"e": 32540,
"s": 32442,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32555,
"s": 32540,
"text": "Stream In Java"
},
{
"code": null,
"e": 32601,
"s": 32555,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 32622,
"s": 32601,
"text": "Constructors in Java"
},
{
"code": null,
"e": 32641,
"s": 32622,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 32658,
"s": 32641,
"text": "Generics in Java"
},
{
"code": null,
"e": 32702,
"s": 32658,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 32728,
"s": 32702,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 32762,
"s": 32728,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 32809,
"s": 32762,
"text": "Implementing a Linked List in Java using Class"
}
] |
Python program to check if the given number is a Disarium Number
|
When it is required to check if a given nmber is a disarium number, the sum of digits powered to their respective position is computed. Before this, the number of digits present in the number is determined.
A Disarium Number is the one where the sum of its digits to the power of their respective position is equal to the original number itself.
Below is a demonstration for the same −
Live Demo
def length_calculation(num_val):
length = 0
while(num_val != 0):
length = length + 1
num_val = num_val//10
return length
my_num = 192
remaining = sum_val = 0
len_val = length_calculation(my_num)
print("A copy of the original number is being made...")
num_val = my_num
while(my_num > 0):
remaining = my_num%10
sum_val = sum_val + int(remaining**len_val)
my_num = my_num//10
len_val = len_val - 1
if(sum_val == num_val):
print(str(num_val) + " is a disarium number !")
else:
print(str(num_val) + " isn't a disarium number")
A copy of the original number is being made...
192 isn't a disarium number
A method named ‘length_calculation’ is defined, that calculates the number of digits in the number.
It computes the floor division of the number and returns the length of the number.
The number is defined, and is displayed on the console.
It uses the modulus operation to get the remainder, and adds it to a sum variable.
The power of the position is multiplied with the number itself.
This is compared with the number.
If it is equal, it means it is a Harshad number, otherwise it is not.
|
[
{
"code": null,
"e": 1269,
"s": 1062,
"text": "When it is required to check if a given nmber is a disarium number, the sum of digits powered to their respective position is computed. Before this, the number of digits present in the number is determined."
},
{
"code": null,
"e": 1408,
"s": 1269,
"text": "A Disarium Number is the one where the sum of its digits to the power of their respective position is equal to the original number itself."
},
{
"code": null,
"e": 1448,
"s": 1408,
"text": "Below is a demonstration for the same −"
},
{
"code": null,
"e": 1459,
"s": 1448,
"text": " Live Demo"
},
{
"code": null,
"e": 2020,
"s": 1459,
"text": "def length_calculation(num_val):\n length = 0\n while(num_val != 0):\n length = length + 1\n num_val = num_val//10\n return length\nmy_num = 192\nremaining = sum_val = 0\nlen_val = length_calculation(my_num)\nprint(\"A copy of the original number is being made...\")\nnum_val = my_num\nwhile(my_num > 0):\n remaining = my_num%10\n sum_val = sum_val + int(remaining**len_val)\n my_num = my_num//10\n len_val = len_val - 1\nif(sum_val == num_val):\n print(str(num_val) + \" is a disarium number !\")\nelse:\n print(str(num_val) + \" isn't a disarium number\")"
},
{
"code": null,
"e": 2095,
"s": 2020,
"text": "A copy of the original number is being made...\n192 isn't a disarium number"
},
{
"code": null,
"e": 2195,
"s": 2095,
"text": "A method named ‘length_calculation’ is defined, that calculates the number of digits in the number."
},
{
"code": null,
"e": 2278,
"s": 2195,
"text": "It computes the floor division of the number and returns the length of the number."
},
{
"code": null,
"e": 2334,
"s": 2278,
"text": "The number is defined, and is displayed on the console."
},
{
"code": null,
"e": 2417,
"s": 2334,
"text": "It uses the modulus operation to get the remainder, and adds it to a sum variable."
},
{
"code": null,
"e": 2481,
"s": 2417,
"text": "The power of the position is multiplied with the number itself."
},
{
"code": null,
"e": 2515,
"s": 2481,
"text": "This is compared with the number."
},
{
"code": null,
"e": 2585,
"s": 2515,
"text": "If it is equal, it means it is a Harshad number, otherwise it is not."
}
] |
How do we access command line arguments in Python?
|
Command line is the place where executable commands are given to operating system. A Python script can be executed by writing its name in front of python executable in the command line.
C:\users\acer>python test.py
If you want some data elements to be passed to Python script for its processing, these elements are written as space delimited values in continuation to name of script. This list of space delimited values are called command line arguments.
C:\users\acer>python test.py Hello TutorialsPoint
Items separated by space are stored in a special List object called argv[]. It is defined in sys module of Python distribution.
In above example, the List object would contain:
sys.argv[]=[‘test.py’, ‘Hello’, ‘TutorialsPoint’]
In the program access these arguments by
import sys
print ("first command line argument: ",sys.argv[1])
print ("second command line argument: ",sys.argv[2])
|
[
{
"code": null,
"e": 1248,
"s": 1062,
"text": "Command line is the place where executable commands are given to operating system. A Python script can be executed by writing its name in front of python executable in the command line."
},
{
"code": null,
"e": 1277,
"s": 1248,
"text": "C:\\users\\acer>python test.py"
},
{
"code": null,
"e": 1517,
"s": 1277,
"text": "If you want some data elements to be passed to Python script for its processing, these elements are written as space delimited values in continuation to name of script. This list of space delimited values are called command line arguments."
},
{
"code": null,
"e": 1567,
"s": 1517,
"text": "C:\\users\\acer>python test.py Hello TutorialsPoint"
},
{
"code": null,
"e": 1695,
"s": 1567,
"text": "Items separated by space are stored in a special List object called argv[]. It is defined in sys module of Python distribution."
},
{
"code": null,
"e": 1744,
"s": 1695,
"text": "In above example, the List object would contain:"
},
{
"code": null,
"e": 1794,
"s": 1744,
"text": "sys.argv[]=[‘test.py’, ‘Hello’, ‘TutorialsPoint’]"
},
{
"code": null,
"e": 1835,
"s": 1794,
"text": "In the program access these arguments by"
},
{
"code": null,
"e": 1952,
"s": 1835,
"text": "import sys\nprint (\"first command line argument: \",sys.argv[1])\n print (\"second command line argument: \",sys.argv[2])"
}
] |
Topic Modeling In NLP. With a focus on Latent Dirichlet... | by Arun Jagota | Towards Data Science
|
In natural language processing, the term topic means a set of words that “go together”. These are the words that come to mind when thinking of this topic. Take sports. Some such words are athlete, soccer, and stadium.
A topic model is one that automatically discovers topics occurring in a collection of documents. A trained model may then be used to discern which of these topics occur in new documents. The model can also pick out which portions of a document cover which topics.
Consider Wikipedia. It has millions of documents covering hundreds of thousands of topics. Wouldn’t it be great if these could be discovered automatically? Plus a finer map of which documents cover which topics. These would be useful adjuncts for people seeking to explore Wikipedia.
We could also discover emerging topics, as documents get written about them. In some settings (such as news) where new documents are constantly being produced and recency matters, this would help us detect trending topics.
This post covers a statistically powerful and widely used approach to this problem.
Latent Dirichlet Allocation
This approach involves building explicit statistical models of topics and documents.
A topic is modeled as a probability distribution over a fixed set of words (the lexicon). This formalizes “the set of words that come to mind when referring to this topic”. A document is modeled as a probability distribution over a fixed set of topics. This reveals the topics the document covers.
The aim of learning is to discover, from a corpus of documents, good word distributions of the various topics, as well as good topic proportions in the various documents. The number of topics is a parameter to this learning.
Generating A Document
At this stage, it will help to describe how to generate a synthetic document from a learned model. This will reveal key aspects of how this model operates that we haven’t delved into yet.
First, we’ll pick the topics this document will cover. One way to do this is to first pick a random document from our corpus, then set the new document’s topic proportions to those of the seed document.
Next, we’ll set the document length, call it n.
Next, we will repeat the following n times:
sample a topic from the document’s topic proportionssample a word from the chosen topic’s words-distribution
This will emit a sequence of n words. These words will come annotated with the topics they were sampled from.
The resulting document is gibberish. A bag of words sampled from a mix of topics. That’s not a problem — it wasn’t meant to be read. It does reveal which words were generated from which topics, which can be insightful.
Example
Lexicon: {athlete, football, soccer, tennis, computer, smartphone, laptop, printer,Intel, Apple, Google}Num Topics : 3Topic 1: {athlete, football, soccer, tennis}Topic 2: {computer, smartphone, laptop, printer}Topic 3: {Intel, Apple, Google}Topic proportions in a document: { 2 ⇒ 70%, 3 ⇒ 30% }
In the above, we’ve described a topic as a set of words. We interpret this as: all the words in the set are equiprobable; the remaining words in the lexicon have zero probability.
Let’s see a 4-word generated document.
Topic: 2 3 2 2Word: laptop Intel smartphone computer
Topic 3’s proportion in this document (25%) is close to its proportion (30%) in its sampling distribution.
Learning
As usual, this is where things get especially interesting.
First, let’s remind ourselves of the aim of learning. It is to discover, from a corpus of documents, the word distributions of the various topics, and the topic proportions in the various documents. In short, what words describe which topic, and which topics are covered in which document.
The algorithm we’ll describe is in wide use. It is also not hard to understand. It is a form of Gibbs Sampling.
This algorithm works by initially assigning the topics to the various words in the corpus somehow, then iteratively improving these assignments. During its operation, the algorithm keeps track of certain statistics on the current assignments. These statistics help the algorithm in its subsequent learning. When the algorithm terminates, it is easy to “read off” the per-topic word distributions and the per-document topic proportions from the final topic assignments.
Let’s start by describing the statistics mentioned in the previous paragraph. These take the form of two matrices of counts: topic_word and doc_topic. Both are derived from the current assignment of topics to the words in the corpus. topic_word(t,w) counts the number of occurrences of topic t for word w. doc_topic(d,t) counts the number of occurrences of topic t in document d.
Let’s see a numeric example to make sure we got it right. Below we see a two-document corpus along with an assignment of topics to its words. The lexicon is A, B, C.
Doc 1’s words: A B A C A Doc 2’s words: B C C BDoc 1’s topics: 1 1 1 2 2 Doc 2’s topics: 2 2 2 2
Actually let’s first use this opportunity to muse about some peculiarities we see. In doc 1, notice that A is assigned sometimes to topic 1 and sometimes to topic 2. This is plausible if word A has a high probability in both topics. In doc 2, notice that B is consistently assigned to topic 2. This is plausible if Doc 2 covers only topic 2, and B has a positive probability in topic 2’s distribution.
Okay, now to the two matrices of counts.
topic_word: doc_topic: A B C 1 21 2 1 0 d1 3 22 1 2 3 d2 0 4
We’ve bolded some entries that are a bit striking. Perhaps doc2 prefers topic 2. Perhaps topic 2 prefers word C.
Ok, let’s start explaining the learning. The first step is to label the words in the corpus with randomly-sampled topics. This sounds easy enough. Actually there is a bit more to it. Instead of hard-coding this random-sampling, it is better to sample off suitable prior distributions. This gives us a potentially powerful mechanism to inject domain knowledge or results from external text analyses.
This priors-based mechanism works as follows. First, we make copies of the two matrices we introduced earlier. Call them prior_topic_word and prior_doc_topic respectively. As before, the entries in these matrices are counts. These counts capture our prior beliefs.
These prior matrices influence the initial assignment of topics. As learning progresses, this influence diminishes, albeit not to zero.
How exactly do we sample the initial assignment of topics from these counts? First, we calculate
P(w|t) = prior_topic_word(t,w)/sum_w’ (prior_topic_word(t,w’))P(t|d) = prior_doc_topic(t,d)/sum_t’ (prior_doc_topic(t’,d)
P(w|t) is just the fraction of the assignments of topic t whose word is w. P(t|d) is just the fraction of the words in document d whose assigned topic is t.
Next, we sample the assignments from these. More specifically, we sample the topic for word w in document d from a distribution whose numerator is P(w|t)P(t|d).
This may be understood as follows. P(w|t)P(t|d) is exactly the probability of generating word w in document d in our generative model. Viewed as a function of t, it captures the likelihood that t was used during this process.
Now let’s discuss setting the values of these counts in the two prior matrices. For our purposes here, all we care about is that no topic be preferred over another. Such preferences would be unwanted biases. We can achieve this by setting all the counts in each matrix to the same positive number. 1 is the simplest choice. Occam’s razor reasoning.
prior_topic_word(t,w)=1 for every topic t and word wprior_doc_topic(d,t)=1 for every document d and topic t
Okay, so the topic assignments will be sampled from these counts and come out uniformly random.
Subsequent to this initial assignment, we will repeatedly do the following in the hopes of improving the assignment and consequently, our models learned from it:
1. Pick a word w from a document d in the corpus2. Sample a topic t’ from the distribution whose numerator is Q(w|t)Q(t|d)3. Set w’s topic in d to t’.
What is Q(w|t)? It is our current belief in the likelihood of generating the word w from topic t. In fact, good values of Q(w|t) are what we seek. These will form the final topic-specific words-distributions.
Before starting learning, we captured whatever prior beliefs we had about this distribution into P(w|t). As learning progresses, P(w|t) starts getting revised into the posterior belief Q(w|t).
Q(t|d)’s explanation is similar. Our prior beliefs about the per-document topic proportions go into P(t|d). As learning progresses, these get revised into Q(t|d).
How are Q(w|t) and Q(t|d) computed? Consider the assignment of topics to the various words in the corpus at any point during learning. From this assignment of topics, we can calculate the counts in the topic_word and the doc_topic matrices. Next, we do the following
posterior_topic_word = topic_word + prior_topic_wordposterior_doc_topic = doc_topic + prior_doc_topic
Note that the ‘+’ is matrix addition. From the posterior versions of the count matrices, we may compute Q(w|t) and Q(t|d). Just as we computed P(w|t) and P(t|d) from the prior versions.
Some Intuition
How do we know that this iterative process actually improves the topic assignments? We won’t give a proof. Instead, some intuition.
First note that the overall quality of an assignment of topics to the words in the corpus may be obtained by multiplying out the various Q(w|t)Q(t|d) terms, over all word occurrences w in the corpus. Here d denotes the document in which w appears, and t the topic assigned to that occurrence.
Next, we’ll reveal that the score function has certain desirable characteristics.
This Score Function Favors Topic Specificity
By “topic specificity” we mean that Q(w|t) is concentrated on only a few topics. This is a desired property of those words that strongly correlate with specific topics. Let’s elaborate. Consider a diverse corpus such as Wikipedia. Say our aim is to discover the wide variety of topics it covers. Consider the word cat. Its topic specificity is high, i.e. it conjures up only a few of these topics. As it should. So the score function’s bias towards favoring topic specificity is a good thing.
That said, not every word should be topic-specific. For example the. Later we’ll discuss a separate mechanism that will counteract topic specificity in such cases. First, let’s explain the topic-specificity bias. We’ll call topic-specific words informative.
Consider n >> 1 occurrences of the same word w in the corpus, perhaps spread across many documents. Let T1 and T2 be two different topic assignments to these n occurrences. All the topics in T1 are distinct. Call this set {1,2,3,...,n}. All the topics in T2 are the same, the one that maximizes Q(w|t). Call this topic tmax. T1’s likelihood under Q(w|t) is Q(w|1)Q(w|2)*...*Q(w|n). T2’s likelihood under Q(w|t) is Q(w|tmax)^n. T2’s likelihood can be way higher than T1’s when w is informative and n is not too small.
This analysis may be summarized as
The score function encourages informative words to stay on topic
This Score Function Favors Document Specificity
By “document specificity” we mean that the document covers only a few topics. Documents tend to be specific. The question is whether the score function (and consequently the learning algorithm) exploits this tendency to do its job better. The answer is yes. As explained below.
Consider a document d on n words. Let T1 and T2 be two different topic assignments to its words. All the topics in T1 are distinct. Call this set {1,2,3,...,n}. All the topics in T2 are the same, this time the one with the highest proportion in d. Call it tmax. T1’s likelihood under Q(t|d) is Q(1|d)Q(2|d)*...*Q(n|d). T2’s likelihood under Q(t|d) is Q(tmax|d)^n. Clearly T2 can be way higher, especially for large documents.
This analysis may be summarized as
The score function encourages documents to stay on topic
These Influences Sometimes Compete!
Consider an especially common word: the. Reasonably assume it appears in almost all documents. Topic consistency favors all these occurrences being assigned the same topic. Document specificity protests, as this would force all these documents to cover this one topic.
Let’s imagine how this might play out. Topic consistency might back off its grip for such words. Their assigned topics might just “go with the flow”, taking on the identity of whichever topic is being covered in the neighborhood. Sure, the topic consistency component of the likelihood of these assignments might decrease. The document specificity portion, on the other hand, would increase.
More On The Learning Algorithm
We’ve seen that the score function is biased in good ways. This is only helpful if the learning algorithm exploits them well. So let’s pivot to discussing the algorithm a bit more.
We’ll start by noting that the algorithm works by locally optimizing the global topic assignment quality score. This alone suggests it is paying attention to the biases.
Next, we’ll run through an iteration or two in a simple example. This will help the reader get a better feel for its “local optimizing” behavior. It’s more nuanced than some might imagine.
Example
We’ll set the lexicon to {A, B}. Our corpus will have two documents, AAA (d1) and BBB (d2). (While these may sound silly, this exercise will be instructive.) We’ll aim to fit two topics to the corpus.
Let’s set all the prior counts to 0.0000001. It will still produce initial assignments that are uniformly random, though simplify our numeric calculations.
Say the following is the initial assignment
d1 d2AAA BBB121 122
The learned model from this assignment is
Q(A|1) = 2⁄3 , Q(B|1) = 1⁄3 // these sum to 1Q(A|2) = 1⁄3 , Q(B|2) = 2⁄3 // these sum to 1Q(1|d1) = 2⁄3 , Q(2|d1)= 1⁄3 // these sum to 1Q(1|d2) = 1⁄3, Q(2|d2) = 2⁄3 // these sum to 1
Now imagine picking a word from d1 and resampling its topic. (We could have chosen d2 instead but the reasoning is similar.) There are three possible outcomes: 121 → 121, 121 → 111, 121 → 122 or 221. The third one is effectively where we started with: swap the topic names and rearrange the order. So the first and the third outcome effectively put us back in the same state. So let’s zoom in on the second one: 121 → 111. The probability of this transition is positive. (In fact quite high as the switch from 2 → 1 improves both the topic likelihood component and also the document likelihood component.) So if we keep repeating this process at some point all of d1 will be assigned the same topic t (=1 or 2).
Next, we reestimate the various parameters of the model from this assignment t to d1. Q(t|d1) is now 1. Q(A|t) may well be higher than Q(A|1) was when we began this process. We have arrived at a “happy state” from which it is difficult to escape.
Variants
Now let’s look at some variants of this algorithm. These involve modifying step 2 below.
1. Pick a word w from a document d in the corpus2. Sample a topic t’ from the distribution whose numerator is Q(w|t)Q(t|d)3. Set w’s topic in d to t’.
We can replace step 2 by “set t’ to the topic that maximizes Q(w|t)Q(t|d)”. This is called maximum likelihood estimation. In our setting, this yields a greedy algorithm.
This variant is attractive in its simplicity and may converge quicker. However, it is more susceptible to getting trapped in suboptimal local optima.
Our next variant introduces a parameter called temperature, which may be varied to span behaviors ranging from the Gibbs sampler to the greedy algorithm. Therein lies this algorithm’s appeal. It does open up a new issue though: how to set the temperature.
Setting temperature aside, let’s see how it works. Consider the word w whose current topic t is being considered for re-assignment. For every topic t’ we evaluate
delta(t’) = — [ log Q(w|t’)Q(t’|d) — log Q(w|t)Q(t|d) ]
We won’t explain why the log here. We will note that delta(t’) being less than 0 corresponds to t’ being a better fit than t in this situation. A switch from t to t’ may be viewed as an energy-reducing (or hill-descending) move.
What happens next? We’ll describe it qualitatively. So now we know delta(t’) for the various values of t’, including t. From these delta-values, the algorithm defines a suitable probability distribution over the topics. This distribution is parameterized by temperature.
At high temperature, even “up-hill moves”, i.e. moves to topics whose delta-values are positive are permitted. Such moves, while regressing on the current topic assignment, can help escape local energy minima.
At low temperature, the distribution favors moves whose delta-values are negative. In the zero temperature extreme, this yields greedy behavior.
Richer Priors
To this point, we’ve been set prior counts to 1. Here we consider richer settings.
Previously we noted that it is desirable for certain words to be topic-specific. Can we find such words and capture their topic-specificity preference into the prior counts? This could speed up subsequent learning.
Here is a sensible way to do this. First, we’ll set all the prior counts to 1. Next, for each word w, we’ll compute n-n(w). Here n is the total number of documents in the corpus and n(w) the number of documents in which word w appears. Think of n-n(w) as a sort-of “inverse document frequency” of w. Next, we will do the following independently for each of the words. We will pick a topic t randomly from the universe of topics. We’ll add n-n(w) to the prior count word_topic(t,w).
The idea is to map uncommon words to specific topics. Since the topic choices are random, different words will likely map to different topics.
Is this prior overly biased? We can easily soften it should we feel that is the case. There are a number of possibilities. One is to replace n-n(w) by log n — log n(w). A second is to sample more than one topic (albeit not many) when amplifying a word’s prior count.
Other Modeling Enhancements
What are other areas to consider for improving the model? First, let’s spell out its assumptions:
1. The topics a document covers are sampled independently. They are not checked for compatibility.2. Word proximity in a document is not considered.3. The hierarchical structure among topics is not modeled.
Let’s say a bit about each. Topic compatibility can be important. A document is more likely to cover tech companies & computers than tech companies & sports. Word proximity also matters. Two words that repeatedly occur near each other are more likely to be on the same topic than those that appear thousands of words apart. Topic hierarchies model documents better. A common writing pattern is for a document to cover a broad topic together with its various subtopics.
Below we describe how to address these issues. The relaxations may improve the accuracy of the model in some use cases, though at the potential cost of increasing its complexity or learnability. They also offer opportunities to inject domain knowledge. Plus in some ways even help with the learning!
Exactly how this plays out depends heavily on the use case.
Topic Compatibilities
This involves adding a Markov model to the mix. Its states are the topics. Its transitions model compatibility among topics in the corpus.
How is this model used when sampling a word’s topic in a document? We need to extend Q(t|d) suitably. This extension is easiest described by imagining sampling topics from it.
This sampling may be viewed as a random walk on the Markov model with perhaps occasional restarts. We start the walk by choosing a topic sampled from Q(t|d). Next, we do the following. Most of the time we walk a transition from this topic’s state with the probability that is on that transition. Occasionally we re-sample from Q(t|d), i.e., jump to a new topic.
This random walk induces a new distribution, call it Q’(t|d, M) which is influenced by both the Markov model M and Q(t|d). The Markov model is a corpus-level construct. The use of Q(t|d) customizes its behavior to the document d.
How are the parameters of the Markov model learned? This is easier to explain. Our learning algorithm to this point already works at the level of assigning topics to individual words in the documents of the corpus. The Markov model’s parameters are fully determined by this assignment.
Specifically, for every pair s, t of topic assignments in a document, we increment counts on the arcs s → t and t → s unless s equals t in which case only once.
So as topic assignments improve, the parameters of the topic-compatibility model also improve. The two act synergistically.
Let’s look at this synergy in a wider scope. As we see more and more documents on the same two topics, the Markov model starts learning that these topics are compatible. This improved learning leads to improved topic assignments elsewhere.
Word Proximity
This can be incorporated by extending Q(w|t) suitably. Specifically, let the choice of t be influenced not only from w but also from words near w.
Let’s formalize this. Let W(d) = w(-d),...,w,...,w(+d) denote the sequence of words of length 2d+1 centered at w. Here d is a nonnegative integer. Next, we extend Q(w|t) to Q(W(d)|t).
Does this complicate our model from the learning perspective? With a suitable assumption, fortunately not. We assume the words in W(d) are conditionally independent given t. Under this assumption we get
Q(W(d)|t) = Q(w(-d)|t)*...*Q(w|t)*...*Q(w(+d)|t)
The RHS terms involving t are all of the same forms as before. So learning needs no change!
The assumption notwithstanding, we get the benefits that come with using context. Chief among them is that the topic assigned to the central word w may be determined more accurately, as now we have more context. Another helpful characteristic, especially early on in the learning, is that we get some topic continuity. As we slide the window W(d) one word at a time, the assigned topic is less likely to change since the context hasn’t changed much. Compared to W(0).
Topics Hierarchy
This is an advanced topic. Our coverage here is partial.
Here is the key observation. Comparing the word distributions of two topics can help assess whether or not one is a descendant of the other. The descendant’s keywords will tend towards being a subset of the ancestor’s.
Using this notion, we can (re)learn a hierarchy on the topics any time we want during the learning process. Even a rough learned hierarchy can be better than none.
As we did for topic compatibility, we can extend our Q(t|d) models to take the learned hierarchy into account. As there, this extension is easiest described by imagining sampling topics for a specific document from it.
This sampling is a random walk on the hierarchy with perhaps occasional restarts. We start the walk by choosing a topic sampled from Q(t|d). Next, we do the following. Most of the time we walk to a child from this topic. Occasionally we resample from Q(t|d), i.e., jump to a topic somewhere else in the hierarchy.
This random walk induces a new distribution, call it Q’(t|d, H) which is influenced by both the topic hierarchy H and Q(t|d). The topic hierarchy is a corpus-level construct. The use of Q(t|d) customizes its behavior to the document d.
Enhancements That Improve Readability
The readability of a document is not the primary aim of LDA. Nonetheless, the modeling framework presents opportunities to inject mechanisms that improve it. So let’s take advantage of this.
Let’s start by surfacing the issues.
1. Topic continuity is not maintained. Neighboring words can jump from topic to topic.2. Topic coherence is not maintained. A topic spews out its words independently.
Topic continuity
We can maintain topic continuity by adding a Markov model with two states: continue and switch. Continue to continue the current topic, switch to switch to a new one. The arc from continue to itself should have a high probability. The arc from switch to continue should have a near-1 probability as we almost surely want to continue following a switch.
The probabilities on this model are easy to learn from the topic assignments. Buried in them are the continue and switch events. Such learning dovetails with the learning of the topic assignments, iteratively benefiting each other.
Leveraging word proximity in documents also helps maintain topic continuity. The reason we chose to cover the approach of this section as well is that it is far simpler to implement than word proximity.
This Also Benefits Learning
Readability aside, injecting the topic continuity mechanism also potentially improves the quality of the learned assignments. In effect, it acts as a smoothness regularizer, disfavoring outliers.
Here is an example, an extension of one we used earlier. Consider the word the, which we assumed occurs in almost all documents in the corpus. Previously we explained why we would like the topic assigned to a particular occurrence of the to “go with the flow” of the topic in its neighborhood. The topic continuity mechanism adds more weight to this preference, as it explicitly favors “go with the flow”.
Topic Coherence
We can maintain topic coherence by relaxing the bag-of-words assumption. Instead, use a first-order Markov model that models the influence of the current word on the next one. Each topic has its own Markov model.
The per-topic Markov models are easy to (re)learn from the current topic assignment in the corpus.
Further Reading
David M. Blei. Probabilistic Topic Models. Communications of the ACM. 2012 http://www.cs.columbia.edu/~blei/papers/Blei2012.pdf
David M. Blei, Andrew Ng, Michael Jordan. Latent Dirichlet allocation. JMLR (3) 2003 pp. 993–1022.
Tom Griffiths. Gibbs sampling in the generative model of Latent Dirichlet Allocation.https://people.cs.umass.edu/~wallach/courses/s11/cmpsci791ss/readings/griffiths02gibbs.pdf
|
[
{
"code": null,
"e": 264,
"s": 46,
"text": "In natural language processing, the term topic means a set of words that “go together”. These are the words that come to mind when thinking of this topic. Take sports. Some such words are athlete, soccer, and stadium."
},
{
"code": null,
"e": 528,
"s": 264,
"text": "A topic model is one that automatically discovers topics occurring in a collection of documents. A trained model may then be used to discern which of these topics occur in new documents. The model can also pick out which portions of a document cover which topics."
},
{
"code": null,
"e": 812,
"s": 528,
"text": "Consider Wikipedia. It has millions of documents covering hundreds of thousands of topics. Wouldn’t it be great if these could be discovered automatically? Plus a finer map of which documents cover which topics. These would be useful adjuncts for people seeking to explore Wikipedia."
},
{
"code": null,
"e": 1035,
"s": 812,
"text": "We could also discover emerging topics, as documents get written about them. In some settings (such as news) where new documents are constantly being produced and recency matters, this would help us detect trending topics."
},
{
"code": null,
"e": 1119,
"s": 1035,
"text": "This post covers a statistically powerful and widely used approach to this problem."
},
{
"code": null,
"e": 1147,
"s": 1119,
"text": "Latent Dirichlet Allocation"
},
{
"code": null,
"e": 1232,
"s": 1147,
"text": "This approach involves building explicit statistical models of topics and documents."
},
{
"code": null,
"e": 1530,
"s": 1232,
"text": "A topic is modeled as a probability distribution over a fixed set of words (the lexicon). This formalizes “the set of words that come to mind when referring to this topic”. A document is modeled as a probability distribution over a fixed set of topics. This reveals the topics the document covers."
},
{
"code": null,
"e": 1755,
"s": 1530,
"text": "The aim of learning is to discover, from a corpus of documents, good word distributions of the various topics, as well as good topic proportions in the various documents. The number of topics is a parameter to this learning."
},
{
"code": null,
"e": 1777,
"s": 1755,
"text": "Generating A Document"
},
{
"code": null,
"e": 1965,
"s": 1777,
"text": "At this stage, it will help to describe how to generate a synthetic document from a learned model. This will reveal key aspects of how this model operates that we haven’t delved into yet."
},
{
"code": null,
"e": 2168,
"s": 1965,
"text": "First, we’ll pick the topics this document will cover. One way to do this is to first pick a random document from our corpus, then set the new document’s topic proportions to those of the seed document."
},
{
"code": null,
"e": 2216,
"s": 2168,
"text": "Next, we’ll set the document length, call it n."
},
{
"code": null,
"e": 2260,
"s": 2216,
"text": "Next, we will repeat the following n times:"
},
{
"code": null,
"e": 2369,
"s": 2260,
"text": "sample a topic from the document’s topic proportionssample a word from the chosen topic’s words-distribution"
},
{
"code": null,
"e": 2479,
"s": 2369,
"text": "This will emit a sequence of n words. These words will come annotated with the topics they were sampled from."
},
{
"code": null,
"e": 2698,
"s": 2479,
"text": "The resulting document is gibberish. A bag of words sampled from a mix of topics. That’s not a problem — it wasn’t meant to be read. It does reveal which words were generated from which topics, which can be insightful."
},
{
"code": null,
"e": 2706,
"s": 2698,
"text": "Example"
},
{
"code": null,
"e": 3001,
"s": 2706,
"text": "Lexicon: {athlete, football, soccer, tennis, computer, smartphone, laptop, printer,Intel, Apple, Google}Num Topics : 3Topic 1: {athlete, football, soccer, tennis}Topic 2: {computer, smartphone, laptop, printer}Topic 3: {Intel, Apple, Google}Topic proportions in a document: { 2 ⇒ 70%, 3 ⇒ 30% }"
},
{
"code": null,
"e": 3181,
"s": 3001,
"text": "In the above, we’ve described a topic as a set of words. We interpret this as: all the words in the set are equiprobable; the remaining words in the lexicon have zero probability."
},
{
"code": null,
"e": 3220,
"s": 3181,
"text": "Let’s see a 4-word generated document."
},
{
"code": null,
"e": 3294,
"s": 3220,
"text": "Topic: 2 3 2 2Word: laptop Intel smartphone computer"
},
{
"code": null,
"e": 3401,
"s": 3294,
"text": "Topic 3’s proportion in this document (25%) is close to its proportion (30%) in its sampling distribution."
},
{
"code": null,
"e": 3410,
"s": 3401,
"text": "Learning"
},
{
"code": null,
"e": 3469,
"s": 3410,
"text": "As usual, this is where things get especially interesting."
},
{
"code": null,
"e": 3759,
"s": 3469,
"text": "First, let’s remind ourselves of the aim of learning. It is to discover, from a corpus of documents, the word distributions of the various topics, and the topic proportions in the various documents. In short, what words describe which topic, and which topics are covered in which document."
},
{
"code": null,
"e": 3871,
"s": 3759,
"text": "The algorithm we’ll describe is in wide use. It is also not hard to understand. It is a form of Gibbs Sampling."
},
{
"code": null,
"e": 4340,
"s": 3871,
"text": "This algorithm works by initially assigning the topics to the various words in the corpus somehow, then iteratively improving these assignments. During its operation, the algorithm keeps track of certain statistics on the current assignments. These statistics help the algorithm in its subsequent learning. When the algorithm terminates, it is easy to “read off” the per-topic word distributions and the per-document topic proportions from the final topic assignments."
},
{
"code": null,
"e": 4720,
"s": 4340,
"text": "Let’s start by describing the statistics mentioned in the previous paragraph. These take the form of two matrices of counts: topic_word and doc_topic. Both are derived from the current assignment of topics to the words in the corpus. topic_word(t,w) counts the number of occurrences of topic t for word w. doc_topic(d,t) counts the number of occurrences of topic t in document d."
},
{
"code": null,
"e": 4886,
"s": 4720,
"text": "Let’s see a numeric example to make sure we got it right. Below we see a two-document corpus along with an assignment of topics to its words. The lexicon is A, B, C."
},
{
"code": null,
"e": 4999,
"s": 4886,
"text": "Doc 1’s words: A B A C A Doc 2’s words: B C C BDoc 1’s topics: 1 1 1 2 2 Doc 2’s topics: 2 2 2 2"
},
{
"code": null,
"e": 5401,
"s": 4999,
"text": "Actually let’s first use this opportunity to muse about some peculiarities we see. In doc 1, notice that A is assigned sometimes to topic 1 and sometimes to topic 2. This is plausible if word A has a high probability in both topics. In doc 2, notice that B is consistently assigned to topic 2. This is plausible if Doc 2 covers only topic 2, and B has a positive probability in topic 2’s distribution."
},
{
"code": null,
"e": 5442,
"s": 5401,
"text": "Okay, now to the two matrices of counts."
},
{
"code": null,
"e": 5565,
"s": 5442,
"text": "topic_word: doc_topic: A B C 1 21 2 1 0 d1 3 22 1 2 3 d2 0 4"
},
{
"code": null,
"e": 5678,
"s": 5565,
"text": "We’ve bolded some entries that are a bit striking. Perhaps doc2 prefers topic 2. Perhaps topic 2 prefers word C."
},
{
"code": null,
"e": 6077,
"s": 5678,
"text": "Ok, let’s start explaining the learning. The first step is to label the words in the corpus with randomly-sampled topics. This sounds easy enough. Actually there is a bit more to it. Instead of hard-coding this random-sampling, it is better to sample off suitable prior distributions. This gives us a potentially powerful mechanism to inject domain knowledge or results from external text analyses."
},
{
"code": null,
"e": 6342,
"s": 6077,
"text": "This priors-based mechanism works as follows. First, we make copies of the two matrices we introduced earlier. Call them prior_topic_word and prior_doc_topic respectively. As before, the entries in these matrices are counts. These counts capture our prior beliefs."
},
{
"code": null,
"e": 6478,
"s": 6342,
"text": "These prior matrices influence the initial assignment of topics. As learning progresses, this influence diminishes, albeit not to zero."
},
{
"code": null,
"e": 6575,
"s": 6478,
"text": "How exactly do we sample the initial assignment of topics from these counts? First, we calculate"
},
{
"code": null,
"e": 6697,
"s": 6575,
"text": "P(w|t) = prior_topic_word(t,w)/sum_w’ (prior_topic_word(t,w’))P(t|d) = prior_doc_topic(t,d)/sum_t’ (prior_doc_topic(t’,d)"
},
{
"code": null,
"e": 6854,
"s": 6697,
"text": "P(w|t) is just the fraction of the assignments of topic t whose word is w. P(t|d) is just the fraction of the words in document d whose assigned topic is t."
},
{
"code": null,
"e": 7015,
"s": 6854,
"text": "Next, we sample the assignments from these. More specifically, we sample the topic for word w in document d from a distribution whose numerator is P(w|t)P(t|d)."
},
{
"code": null,
"e": 7241,
"s": 7015,
"text": "This may be understood as follows. P(w|t)P(t|d) is exactly the probability of generating word w in document d in our generative model. Viewed as a function of t, it captures the likelihood that t was used during this process."
},
{
"code": null,
"e": 7590,
"s": 7241,
"text": "Now let’s discuss setting the values of these counts in the two prior matrices. For our purposes here, all we care about is that no topic be preferred over another. Such preferences would be unwanted biases. We can achieve this by setting all the counts in each matrix to the same positive number. 1 is the simplest choice. Occam’s razor reasoning."
},
{
"code": null,
"e": 7698,
"s": 7590,
"text": "prior_topic_word(t,w)=1 for every topic t and word wprior_doc_topic(d,t)=1 for every document d and topic t"
},
{
"code": null,
"e": 7794,
"s": 7698,
"text": "Okay, so the topic assignments will be sampled from these counts and come out uniformly random."
},
{
"code": null,
"e": 7956,
"s": 7794,
"text": "Subsequent to this initial assignment, we will repeatedly do the following in the hopes of improving the assignment and consequently, our models learned from it:"
},
{
"code": null,
"e": 8110,
"s": 7956,
"text": "1. Pick a word w from a document d in the corpus2. Sample a topic t’ from the distribution whose numerator is Q(w|t)Q(t|d)3. Set w’s topic in d to t’."
},
{
"code": null,
"e": 8319,
"s": 8110,
"text": "What is Q(w|t)? It is our current belief in the likelihood of generating the word w from topic t. In fact, good values of Q(w|t) are what we seek. These will form the final topic-specific words-distributions."
},
{
"code": null,
"e": 8512,
"s": 8319,
"text": "Before starting learning, we captured whatever prior beliefs we had about this distribution into P(w|t). As learning progresses, P(w|t) starts getting revised into the posterior belief Q(w|t)."
},
{
"code": null,
"e": 8675,
"s": 8512,
"text": "Q(t|d)’s explanation is similar. Our prior beliefs about the per-document topic proportions go into P(t|d). As learning progresses, these get revised into Q(t|d)."
},
{
"code": null,
"e": 8942,
"s": 8675,
"text": "How are Q(w|t) and Q(t|d) computed? Consider the assignment of topics to the various words in the corpus at any point during learning. From this assignment of topics, we can calculate the counts in the topic_word and the doc_topic matrices. Next, we do the following"
},
{
"code": null,
"e": 9046,
"s": 8942,
"text": "posterior_topic_word = topic_word + prior_topic_wordposterior_doc_topic = doc_topic + prior_doc_topic"
},
{
"code": null,
"e": 9232,
"s": 9046,
"text": "Note that the ‘+’ is matrix addition. From the posterior versions of the count matrices, we may compute Q(w|t) and Q(t|d). Just as we computed P(w|t) and P(t|d) from the prior versions."
},
{
"code": null,
"e": 9247,
"s": 9232,
"text": "Some Intuition"
},
{
"code": null,
"e": 9379,
"s": 9247,
"text": "How do we know that this iterative process actually improves the topic assignments? We won’t give a proof. Instead, some intuition."
},
{
"code": null,
"e": 9672,
"s": 9379,
"text": "First note that the overall quality of an assignment of topics to the words in the corpus may be obtained by multiplying out the various Q(w|t)Q(t|d) terms, over all word occurrences w in the corpus. Here d denotes the document in which w appears, and t the topic assigned to that occurrence."
},
{
"code": null,
"e": 9754,
"s": 9672,
"text": "Next, we’ll reveal that the score function has certain desirable characteristics."
},
{
"code": null,
"e": 9799,
"s": 9754,
"text": "This Score Function Favors Topic Specificity"
},
{
"code": null,
"e": 10292,
"s": 9799,
"text": "By “topic specificity” we mean that Q(w|t) is concentrated on only a few topics. This is a desired property of those words that strongly correlate with specific topics. Let’s elaborate. Consider a diverse corpus such as Wikipedia. Say our aim is to discover the wide variety of topics it covers. Consider the word cat. Its topic specificity is high, i.e. it conjures up only a few of these topics. As it should. So the score function’s bias towards favoring topic specificity is a good thing."
},
{
"code": null,
"e": 10550,
"s": 10292,
"text": "That said, not every word should be topic-specific. For example the. Later we’ll discuss a separate mechanism that will counteract topic specificity in such cases. First, let’s explain the topic-specificity bias. We’ll call topic-specific words informative."
},
{
"code": null,
"e": 11067,
"s": 10550,
"text": "Consider n >> 1 occurrences of the same word w in the corpus, perhaps spread across many documents. Let T1 and T2 be two different topic assignments to these n occurrences. All the topics in T1 are distinct. Call this set {1,2,3,...,n}. All the topics in T2 are the same, the one that maximizes Q(w|t). Call this topic tmax. T1’s likelihood under Q(w|t) is Q(w|1)Q(w|2)*...*Q(w|n). T2’s likelihood under Q(w|t) is Q(w|tmax)^n. T2’s likelihood can be way higher than T1’s when w is informative and n is not too small."
},
{
"code": null,
"e": 11102,
"s": 11067,
"text": "This analysis may be summarized as"
},
{
"code": null,
"e": 11167,
"s": 11102,
"text": "The score function encourages informative words to stay on topic"
},
{
"code": null,
"e": 11215,
"s": 11167,
"text": "This Score Function Favors Document Specificity"
},
{
"code": null,
"e": 11493,
"s": 11215,
"text": "By “document specificity” we mean that the document covers only a few topics. Documents tend to be specific. The question is whether the score function (and consequently the learning algorithm) exploits this tendency to do its job better. The answer is yes. As explained below."
},
{
"code": null,
"e": 11919,
"s": 11493,
"text": "Consider a document d on n words. Let T1 and T2 be two different topic assignments to its words. All the topics in T1 are distinct. Call this set {1,2,3,...,n}. All the topics in T2 are the same, this time the one with the highest proportion in d. Call it tmax. T1’s likelihood under Q(t|d) is Q(1|d)Q(2|d)*...*Q(n|d). T2’s likelihood under Q(t|d) is Q(tmax|d)^n. Clearly T2 can be way higher, especially for large documents."
},
{
"code": null,
"e": 11954,
"s": 11919,
"text": "This analysis may be summarized as"
},
{
"code": null,
"e": 12011,
"s": 11954,
"text": "The score function encourages documents to stay on topic"
},
{
"code": null,
"e": 12047,
"s": 12011,
"text": "These Influences Sometimes Compete!"
},
{
"code": null,
"e": 12316,
"s": 12047,
"text": "Consider an especially common word: the. Reasonably assume it appears in almost all documents. Topic consistency favors all these occurrences being assigned the same topic. Document specificity protests, as this would force all these documents to cover this one topic."
},
{
"code": null,
"e": 12708,
"s": 12316,
"text": "Let’s imagine how this might play out. Topic consistency might back off its grip for such words. Their assigned topics might just “go with the flow”, taking on the identity of whichever topic is being covered in the neighborhood. Sure, the topic consistency component of the likelihood of these assignments might decrease. The document specificity portion, on the other hand, would increase."
},
{
"code": null,
"e": 12739,
"s": 12708,
"text": "More On The Learning Algorithm"
},
{
"code": null,
"e": 12920,
"s": 12739,
"text": "We’ve seen that the score function is biased in good ways. This is only helpful if the learning algorithm exploits them well. So let’s pivot to discussing the algorithm a bit more."
},
{
"code": null,
"e": 13090,
"s": 12920,
"text": "We’ll start by noting that the algorithm works by locally optimizing the global topic assignment quality score. This alone suggests it is paying attention to the biases."
},
{
"code": null,
"e": 13279,
"s": 13090,
"text": "Next, we’ll run through an iteration or two in a simple example. This will help the reader get a better feel for its “local optimizing” behavior. It’s more nuanced than some might imagine."
},
{
"code": null,
"e": 13287,
"s": 13279,
"text": "Example"
},
{
"code": null,
"e": 13488,
"s": 13287,
"text": "We’ll set the lexicon to {A, B}. Our corpus will have two documents, AAA (d1) and BBB (d2). (While these may sound silly, this exercise will be instructive.) We’ll aim to fit two topics to the corpus."
},
{
"code": null,
"e": 13644,
"s": 13488,
"text": "Let’s set all the prior counts to 0.0000001. It will still produce initial assignments that are uniformly random, though simplify our numeric calculations."
},
{
"code": null,
"e": 13688,
"s": 13644,
"text": "Say the following is the initial assignment"
},
{
"code": null,
"e": 13718,
"s": 13688,
"text": "d1 d2AAA BBB121 122"
},
{
"code": null,
"e": 13760,
"s": 13718,
"text": "The learned model from this assignment is"
},
{
"code": null,
"e": 13957,
"s": 13760,
"text": "Q(A|1) = 2⁄3 , Q(B|1) = 1⁄3 // these sum to 1Q(A|2) = 1⁄3 , Q(B|2) = 2⁄3 // these sum to 1Q(1|d1) = 2⁄3 , Q(2|d1)= 1⁄3 // these sum to 1Q(1|d2) = 1⁄3, Q(2|d2) = 2⁄3 // these sum to 1"
},
{
"code": null,
"e": 14669,
"s": 13957,
"text": "Now imagine picking a word from d1 and resampling its topic. (We could have chosen d2 instead but the reasoning is similar.) There are three possible outcomes: 121 → 121, 121 → 111, 121 → 122 or 221. The third one is effectively where we started with: swap the topic names and rearrange the order. So the first and the third outcome effectively put us back in the same state. So let’s zoom in on the second one: 121 → 111. The probability of this transition is positive. (In fact quite high as the switch from 2 → 1 improves both the topic likelihood component and also the document likelihood component.) So if we keep repeating this process at some point all of d1 will be assigned the same topic t (=1 or 2)."
},
{
"code": null,
"e": 14916,
"s": 14669,
"text": "Next, we reestimate the various parameters of the model from this assignment t to d1. Q(t|d1) is now 1. Q(A|t) may well be higher than Q(A|1) was when we began this process. We have arrived at a “happy state” from which it is difficult to escape."
},
{
"code": null,
"e": 14925,
"s": 14916,
"text": "Variants"
},
{
"code": null,
"e": 15014,
"s": 14925,
"text": "Now let’s look at some variants of this algorithm. These involve modifying step 2 below."
},
{
"code": null,
"e": 15168,
"s": 15014,
"text": "1. Pick a word w from a document d in the corpus2. Sample a topic t’ from the distribution whose numerator is Q(w|t)Q(t|d)3. Set w’s topic in d to t’."
},
{
"code": null,
"e": 15338,
"s": 15168,
"text": "We can replace step 2 by “set t’ to the topic that maximizes Q(w|t)Q(t|d)”. This is called maximum likelihood estimation. In our setting, this yields a greedy algorithm."
},
{
"code": null,
"e": 15488,
"s": 15338,
"text": "This variant is attractive in its simplicity and may converge quicker. However, it is more susceptible to getting trapped in suboptimal local optima."
},
{
"code": null,
"e": 15744,
"s": 15488,
"text": "Our next variant introduces a parameter called temperature, which may be varied to span behaviors ranging from the Gibbs sampler to the greedy algorithm. Therein lies this algorithm’s appeal. It does open up a new issue though: how to set the temperature."
},
{
"code": null,
"e": 15907,
"s": 15744,
"text": "Setting temperature aside, let’s see how it works. Consider the word w whose current topic t is being considered for re-assignment. For every topic t’ we evaluate"
},
{
"code": null,
"e": 15963,
"s": 15907,
"text": "delta(t’) = — [ log Q(w|t’)Q(t’|d) — log Q(w|t)Q(t|d) ]"
},
{
"code": null,
"e": 16192,
"s": 15963,
"text": "We won’t explain why the log here. We will note that delta(t’) being less than 0 corresponds to t’ being a better fit than t in this situation. A switch from t to t’ may be viewed as an energy-reducing (or hill-descending) move."
},
{
"code": null,
"e": 16463,
"s": 16192,
"text": "What happens next? We’ll describe it qualitatively. So now we know delta(t’) for the various values of t’, including t. From these delta-values, the algorithm defines a suitable probability distribution over the topics. This distribution is parameterized by temperature."
},
{
"code": null,
"e": 16673,
"s": 16463,
"text": "At high temperature, even “up-hill moves”, i.e. moves to topics whose delta-values are positive are permitted. Such moves, while regressing on the current topic assignment, can help escape local energy minima."
},
{
"code": null,
"e": 16818,
"s": 16673,
"text": "At low temperature, the distribution favors moves whose delta-values are negative. In the zero temperature extreme, this yields greedy behavior."
},
{
"code": null,
"e": 16832,
"s": 16818,
"text": "Richer Priors"
},
{
"code": null,
"e": 16915,
"s": 16832,
"text": "To this point, we’ve been set prior counts to 1. Here we consider richer settings."
},
{
"code": null,
"e": 17130,
"s": 16915,
"text": "Previously we noted that it is desirable for certain words to be topic-specific. Can we find such words and capture their topic-specificity preference into the prior counts? This could speed up subsequent learning."
},
{
"code": null,
"e": 17612,
"s": 17130,
"text": "Here is a sensible way to do this. First, we’ll set all the prior counts to 1. Next, for each word w, we’ll compute n-n(w). Here n is the total number of documents in the corpus and n(w) the number of documents in which word w appears. Think of n-n(w) as a sort-of “inverse document frequency” of w. Next, we will do the following independently for each of the words. We will pick a topic t randomly from the universe of topics. We’ll add n-n(w) to the prior count word_topic(t,w)."
},
{
"code": null,
"e": 17755,
"s": 17612,
"text": "The idea is to map uncommon words to specific topics. Since the topic choices are random, different words will likely map to different topics."
},
{
"code": null,
"e": 18022,
"s": 17755,
"text": "Is this prior overly biased? We can easily soften it should we feel that is the case. There are a number of possibilities. One is to replace n-n(w) by log n — log n(w). A second is to sample more than one topic (albeit not many) when amplifying a word’s prior count."
},
{
"code": null,
"e": 18050,
"s": 18022,
"text": "Other Modeling Enhancements"
},
{
"code": null,
"e": 18148,
"s": 18050,
"text": "What are other areas to consider for improving the model? First, let’s spell out its assumptions:"
},
{
"code": null,
"e": 18357,
"s": 18148,
"text": "1. The topics a document covers are sampled independently. They are not checked for compatibility.2. Word proximity in a document is not considered.3. The hierarchical structure among topics is not modeled."
},
{
"code": null,
"e": 18826,
"s": 18357,
"text": "Let’s say a bit about each. Topic compatibility can be important. A document is more likely to cover tech companies & computers than tech companies & sports. Word proximity also matters. Two words that repeatedly occur near each other are more likely to be on the same topic than those that appear thousands of words apart. Topic hierarchies model documents better. A common writing pattern is for a document to cover a broad topic together with its various subtopics."
},
{
"code": null,
"e": 19126,
"s": 18826,
"text": "Below we describe how to address these issues. The relaxations may improve the accuracy of the model in some use cases, though at the potential cost of increasing its complexity or learnability. They also offer opportunities to inject domain knowledge. Plus in some ways even help with the learning!"
},
{
"code": null,
"e": 19186,
"s": 19126,
"text": "Exactly how this plays out depends heavily on the use case."
},
{
"code": null,
"e": 19208,
"s": 19186,
"text": "Topic Compatibilities"
},
{
"code": null,
"e": 19347,
"s": 19208,
"text": "This involves adding a Markov model to the mix. Its states are the topics. Its transitions model compatibility among topics in the corpus."
},
{
"code": null,
"e": 19523,
"s": 19347,
"text": "How is this model used when sampling a word’s topic in a document? We need to extend Q(t|d) suitably. This extension is easiest described by imagining sampling topics from it."
},
{
"code": null,
"e": 19885,
"s": 19523,
"text": "This sampling may be viewed as a random walk on the Markov model with perhaps occasional restarts. We start the walk by choosing a topic sampled from Q(t|d). Next, we do the following. Most of the time we walk a transition from this topic’s state with the probability that is on that transition. Occasionally we re-sample from Q(t|d), i.e., jump to a new topic."
},
{
"code": null,
"e": 20115,
"s": 19885,
"text": "This random walk induces a new distribution, call it Q’(t|d, M) which is influenced by both the Markov model M and Q(t|d). The Markov model is a corpus-level construct. The use of Q(t|d) customizes its behavior to the document d."
},
{
"code": null,
"e": 20401,
"s": 20115,
"text": "How are the parameters of the Markov model learned? This is easier to explain. Our learning algorithm to this point already works at the level of assigning topics to individual words in the documents of the corpus. The Markov model’s parameters are fully determined by this assignment."
},
{
"code": null,
"e": 20562,
"s": 20401,
"text": "Specifically, for every pair s, t of topic assignments in a document, we increment counts on the arcs s → t and t → s unless s equals t in which case only once."
},
{
"code": null,
"e": 20686,
"s": 20562,
"text": "So as topic assignments improve, the parameters of the topic-compatibility model also improve. The two act synergistically."
},
{
"code": null,
"e": 20926,
"s": 20686,
"text": "Let’s look at this synergy in a wider scope. As we see more and more documents on the same two topics, the Markov model starts learning that these topics are compatible. This improved learning leads to improved topic assignments elsewhere."
},
{
"code": null,
"e": 20941,
"s": 20926,
"text": "Word Proximity"
},
{
"code": null,
"e": 21088,
"s": 20941,
"text": "This can be incorporated by extending Q(w|t) suitably. Specifically, let the choice of t be influenced not only from w but also from words near w."
},
{
"code": null,
"e": 21272,
"s": 21088,
"text": "Let’s formalize this. Let W(d) = w(-d),...,w,...,w(+d) denote the sequence of words of length 2d+1 centered at w. Here d is a nonnegative integer. Next, we extend Q(w|t) to Q(W(d)|t)."
},
{
"code": null,
"e": 21475,
"s": 21272,
"text": "Does this complicate our model from the learning perspective? With a suitable assumption, fortunately not. We assume the words in W(d) are conditionally independent given t. Under this assumption we get"
},
{
"code": null,
"e": 21524,
"s": 21475,
"text": "Q(W(d)|t) = Q(w(-d)|t)*...*Q(w|t)*...*Q(w(+d)|t)"
},
{
"code": null,
"e": 21616,
"s": 21524,
"text": "The RHS terms involving t are all of the same forms as before. So learning needs no change!"
},
{
"code": null,
"e": 22084,
"s": 21616,
"text": "The assumption notwithstanding, we get the benefits that come with using context. Chief among them is that the topic assigned to the central word w may be determined more accurately, as now we have more context. Another helpful characteristic, especially early on in the learning, is that we get some topic continuity. As we slide the window W(d) one word at a time, the assigned topic is less likely to change since the context hasn’t changed much. Compared to W(0)."
},
{
"code": null,
"e": 22101,
"s": 22084,
"text": "Topics Hierarchy"
},
{
"code": null,
"e": 22158,
"s": 22101,
"text": "This is an advanced topic. Our coverage here is partial."
},
{
"code": null,
"e": 22377,
"s": 22158,
"text": "Here is the key observation. Comparing the word distributions of two topics can help assess whether or not one is a descendant of the other. The descendant’s keywords will tend towards being a subset of the ancestor’s."
},
{
"code": null,
"e": 22541,
"s": 22377,
"text": "Using this notion, we can (re)learn a hierarchy on the topics any time we want during the learning process. Even a rough learned hierarchy can be better than none."
},
{
"code": null,
"e": 22760,
"s": 22541,
"text": "As we did for topic compatibility, we can extend our Q(t|d) models to take the learned hierarchy into account. As there, this extension is easiest described by imagining sampling topics for a specific document from it."
},
{
"code": null,
"e": 23074,
"s": 22760,
"text": "This sampling is a random walk on the hierarchy with perhaps occasional restarts. We start the walk by choosing a topic sampled from Q(t|d). Next, we do the following. Most of the time we walk to a child from this topic. Occasionally we resample from Q(t|d), i.e., jump to a topic somewhere else in the hierarchy."
},
{
"code": null,
"e": 23310,
"s": 23074,
"text": "This random walk induces a new distribution, call it Q’(t|d, H) which is influenced by both the topic hierarchy H and Q(t|d). The topic hierarchy is a corpus-level construct. The use of Q(t|d) customizes its behavior to the document d."
},
{
"code": null,
"e": 23348,
"s": 23310,
"text": "Enhancements That Improve Readability"
},
{
"code": null,
"e": 23539,
"s": 23348,
"text": "The readability of a document is not the primary aim of LDA. Nonetheless, the modeling framework presents opportunities to inject mechanisms that improve it. So let’s take advantage of this."
},
{
"code": null,
"e": 23576,
"s": 23539,
"text": "Let’s start by surfacing the issues."
},
{
"code": null,
"e": 23749,
"s": 23576,
"text": "1. Topic continuity is not maintained. Neighboring words can jump from topic to topic.2. Topic coherence is not maintained. A topic spews out its words independently."
},
{
"code": null,
"e": 23766,
"s": 23749,
"text": "Topic continuity"
},
{
"code": null,
"e": 24119,
"s": 23766,
"text": "We can maintain topic continuity by adding a Markov model with two states: continue and switch. Continue to continue the current topic, switch to switch to a new one. The arc from continue to itself should have a high probability. The arc from switch to continue should have a near-1 probability as we almost surely want to continue following a switch."
},
{
"code": null,
"e": 24351,
"s": 24119,
"text": "The probabilities on this model are easy to learn from the topic assignments. Buried in them are the continue and switch events. Such learning dovetails with the learning of the topic assignments, iteratively benefiting each other."
},
{
"code": null,
"e": 24554,
"s": 24351,
"text": "Leveraging word proximity in documents also helps maintain topic continuity. The reason we chose to cover the approach of this section as well is that it is far simpler to implement than word proximity."
},
{
"code": null,
"e": 24582,
"s": 24554,
"text": "This Also Benefits Learning"
},
{
"code": null,
"e": 24778,
"s": 24582,
"text": "Readability aside, injecting the topic continuity mechanism also potentially improves the quality of the learned assignments. In effect, it acts as a smoothness regularizer, disfavoring outliers."
},
{
"code": null,
"e": 25184,
"s": 24778,
"text": "Here is an example, an extension of one we used earlier. Consider the word the, which we assumed occurs in almost all documents in the corpus. Previously we explained why we would like the topic assigned to a particular occurrence of the to “go with the flow” of the topic in its neighborhood. The topic continuity mechanism adds more weight to this preference, as it explicitly favors “go with the flow”."
},
{
"code": null,
"e": 25200,
"s": 25184,
"text": "Topic Coherence"
},
{
"code": null,
"e": 25413,
"s": 25200,
"text": "We can maintain topic coherence by relaxing the bag-of-words assumption. Instead, use a first-order Markov model that models the influence of the current word on the next one. Each topic has its own Markov model."
},
{
"code": null,
"e": 25512,
"s": 25413,
"text": "The per-topic Markov models are easy to (re)learn from the current topic assignment in the corpus."
},
{
"code": null,
"e": 25528,
"s": 25512,
"text": "Further Reading"
},
{
"code": null,
"e": 25656,
"s": 25528,
"text": "David M. Blei. Probabilistic Topic Models. Communications of the ACM. 2012 http://www.cs.columbia.edu/~blei/papers/Blei2012.pdf"
},
{
"code": null,
"e": 25755,
"s": 25656,
"text": "David M. Blei, Andrew Ng, Michael Jordan. Latent Dirichlet allocation. JMLR (3) 2003 pp. 993–1022."
}
] |
C library function - setlocale()
|
The C library function char *setlocale(int category, const char *locale) sets or reads location dependent information.
Following is the declaration for setlocale() function.
char *setlocale(int category, const char *locale)
category − This is a named constant specifying the category of the functions affected by the locale setting.
LC_ALL for all of the below.
LC_COLLATE for string comparison. See strcoll().
LC_CTYPE for character classification and conversion. For example − strtoupper().
LC_MONETARY for monetary formatting for localeconv().
LC_NUMERIC for decimal separator for localeconv().
LC_TIME for date and time formatting with strftime().
LC_MESSAGES for system responses.
category − This is a named constant specifying the category of the functions affected by the locale setting.
LC_ALL for all of the below.
LC_ALL for all of the below.
LC_COLLATE for string comparison. See strcoll().
LC_COLLATE for string comparison. See strcoll().
LC_CTYPE for character classification and conversion. For example − strtoupper().
LC_CTYPE for character classification and conversion. For example − strtoupper().
LC_MONETARY for monetary formatting for localeconv().
LC_MONETARY for monetary formatting for localeconv().
LC_NUMERIC for decimal separator for localeconv().
LC_NUMERIC for decimal separator for localeconv().
LC_TIME for date and time formatting with strftime().
LC_TIME for date and time formatting with strftime().
LC_MESSAGES for system responses.
LC_MESSAGES for system responses.
locale − If locale is NULL or the empty string "", the locale names will be set from the values of environment variables with the same names as the above categories.
locale − If locale is NULL or the empty string "", the locale names will be set from the values of environment variables with the same names as the above categories.
A successful call to setlocale() returns an opaque string that corresponds to the locale set. The return value is NULL if the request cannot be honored.
The following example shows the usage of setlocale() function.
#include <locale.h>
#include <stdio.h>
#include <time.h>
int main () {
time_t currtime;
struct tm *timer;
char buffer[80];
time( &currtime );
timer = localtime( &currtime );
printf("Locale is: %s\n", setlocale(LC_ALL, "en_GB"));
strftime(buffer,80,"%c", timer );
printf("Date is: %s\n", buffer);
printf("Locale is: %s\n", setlocale(LC_ALL, "de_DE"));
strftime(buffer,80,"%c", timer );
printf("Date is: %s\n", buffer);
return(0);
}
Let us compile and run the above program that will produce the following result −
Locale is: en_GB
Date is: Fri 05 Dec 2014 10:35:02 UTC
Locale is: de_DE
Date is: Fr 05 Dez 2014 10:35:02 UTC
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2126,
"s": 2007,
"text": "The C library function char *setlocale(int category, const char *locale) sets or reads location dependent information."
},
{
"code": null,
"e": 2181,
"s": 2126,
"text": "Following is the declaration for setlocale() function."
},
{
"code": null,
"e": 2231,
"s": 2181,
"text": "char *setlocale(int category, const char *locale)"
},
{
"code": null,
"e": 2697,
"s": 2231,
"text": "category − This is a named constant specifying the category of the functions affected by the locale setting.\n\nLC_ALL for all of the below.\nLC_COLLATE for string comparison. See strcoll().\nLC_CTYPE for character classification and conversion. For example − strtoupper().\nLC_MONETARY for monetary formatting for localeconv().\nLC_NUMERIC for decimal separator for localeconv().\nLC_TIME for date and time formatting with strftime().\nLC_MESSAGES for system responses.\n\n"
},
{
"code": null,
"e": 2806,
"s": 2697,
"text": "category − This is a named constant specifying the category of the functions affected by the locale setting."
},
{
"code": null,
"e": 2835,
"s": 2806,
"text": "LC_ALL for all of the below."
},
{
"code": null,
"e": 2864,
"s": 2835,
"text": "LC_ALL for all of the below."
},
{
"code": null,
"e": 2913,
"s": 2864,
"text": "LC_COLLATE for string comparison. See strcoll()."
},
{
"code": null,
"e": 2962,
"s": 2913,
"text": "LC_COLLATE for string comparison. See strcoll()."
},
{
"code": null,
"e": 3044,
"s": 2962,
"text": "LC_CTYPE for character classification and conversion. For example − strtoupper()."
},
{
"code": null,
"e": 3126,
"s": 3044,
"text": "LC_CTYPE for character classification and conversion. For example − strtoupper()."
},
{
"code": null,
"e": 3180,
"s": 3126,
"text": "LC_MONETARY for monetary formatting for localeconv()."
},
{
"code": null,
"e": 3234,
"s": 3180,
"text": "LC_MONETARY for monetary formatting for localeconv()."
},
{
"code": null,
"e": 3285,
"s": 3234,
"text": "LC_NUMERIC for decimal separator for localeconv()."
},
{
"code": null,
"e": 3336,
"s": 3285,
"text": "LC_NUMERIC for decimal separator for localeconv()."
},
{
"code": null,
"e": 3391,
"s": 3336,
"text": "LC_TIME for date and time formatting with strftime()."
},
{
"code": null,
"e": 3446,
"s": 3391,
"text": "LC_TIME for date and time formatting with strftime()."
},
{
"code": null,
"e": 3480,
"s": 3446,
"text": "LC_MESSAGES for system responses."
},
{
"code": null,
"e": 3514,
"s": 3480,
"text": "LC_MESSAGES for system responses."
},
{
"code": null,
"e": 3680,
"s": 3514,
"text": "locale − If locale is NULL or the empty string \"\", the locale names will be set from the values of environment variables with the same names as the above categories."
},
{
"code": null,
"e": 3846,
"s": 3680,
"text": "locale − If locale is NULL or the empty string \"\", the locale names will be set from the values of environment variables with the same names as the above categories."
},
{
"code": null,
"e": 3999,
"s": 3846,
"text": "A successful call to setlocale() returns an opaque string that corresponds to the locale set. The return value is NULL if the request cannot be honored."
},
{
"code": null,
"e": 4062,
"s": 3999,
"text": "The following example shows the usage of setlocale() function."
},
{
"code": null,
"e": 4537,
"s": 4062,
"text": "#include <locale.h>\n#include <stdio.h>\n#include <time.h>\n\nint main () {\n time_t currtime;\n struct tm *timer;\n char buffer[80];\n\n time( &currtime );\n timer = localtime( &currtime );\n\n printf(\"Locale is: %s\\n\", setlocale(LC_ALL, \"en_GB\"));\n strftime(buffer,80,\"%c\", timer );\n printf(\"Date is: %s\\n\", buffer);\n\n \n printf(\"Locale is: %s\\n\", setlocale(LC_ALL, \"de_DE\"));\n strftime(buffer,80,\"%c\", timer );\n printf(\"Date is: %s\\n\", buffer);\n\n return(0);\n}"
},
{
"code": null,
"e": 4619,
"s": 4537,
"text": "Let us compile and run the above program that will produce the following result −"
},
{
"code": null,
"e": 4888,
"s": 4619,
"text": "Locale is: en_GB \nDate is: Fri 05 Dec 2014 10:35:02 UTC \nLocale is: de_DE \nDate is: Fr 05 Dez 2014 10:35:02 UTC\n"
},
{
"code": null,
"e": 4921,
"s": 4888,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4936,
"s": 4921,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4971,
"s": 4936,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4986,
"s": 4971,
"text": " Nishant Malik"
},
{
"code": null,
"e": 5021,
"s": 4986,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5035,
"s": 5021,
"text": " Asif Hussain"
},
{
"code": null,
"e": 5068,
"s": 5035,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5086,
"s": 5068,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 5121,
"s": 5086,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5140,
"s": 5121,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 5173,
"s": 5140,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5185,
"s": 5173,
"text": " Amit Diwan"
},
{
"code": null,
"e": 5192,
"s": 5185,
"text": " Print"
},
{
"code": null,
"e": 5203,
"s": 5192,
"text": " Add Notes"
}
] |
Data Structures | Balanced Binary Search Trees | Question 5 - GeeksforGeeks
|
28 Jun, 2021
Consider the following AVL tree.
60
/ \
20 100
/ \
80 120
Which of the following is updated AVL tree after insertion of 70
A
70
/ \
60 100
/ / \
20 80 120
B
100
/ \
60 120
/ \ /
20 70 80
C
80
/ \
60 100
/ \ \
20 70 120
D
80
/ \
60 100
/ / \
20 70 120
(A) A(B) B(C) C(D) DAnswer: (C)Explanation: Refer following for steps used in AVL insertion.
AVL Tree | Set 1 (Insertion)
After insertion of 70, tree becomes following
60
/ \
20 100
/ \
80 120
/
70
We start from 50 and travel up. We keep travelling up till we find an unbalanced node. In above case, we reach the node 60 and see 60 got unbalanced after insertion and this is Right Left Case. So we need to apply two rotations
60 60 80
/ \ Right Rotate(100) / \ Left Rotate(60) / \
20 100 -----------------> 20 80 ---------------> 60 100
/ \ / \ / \ \
80 120 70 100 20 70 120
/ \
70 120
Quiz of this Question
Balanced Binary Search Trees
Data Structures
Data Structures-Balanced Binary Search Trees
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C program to implement Adjacency Matrix of a given Graph
Advantages and Disadvantages of Linked List
Difference between Singly linked list and Doubly linked list
Introduction to Data Structures | 10 most commonly used Data Structures
FIFO vs LIFO approach in Programming
Multilevel Linked List
Advantages of vector over array in C++
Bit manipulation | Swap Endianness of a number
Difference between data type and data structure
Program to create Custom Vector Class in C++
|
[
{
"code": null,
"e": 25182,
"s": 25154,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25215,
"s": 25182,
"text": "Consider the following AVL tree."
},
{
"code": null,
"e": 25301,
"s": 25215,
"text": " 60\n / \\ \n 20 100\n / \\\n 80 120 \n"
},
{
"code": null,
"e": 25366,
"s": 25301,
"text": "Which of the following is updated AVL tree after insertion of 70"
},
{
"code": null,
"e": 25691,
"s": 25366,
"text": "A\n 70\n / \\ \n 60 100\n / / \\\n 20 80 120 \n\nB\n 100\n / \\ \n 60 120\n / \\ / \n 20 70 80 \n\n\nC\n 80\n / \\ \n 60 100\n / \\ \\\n 20 70 120\n\nD\n 80\n / \\ \n 60 100\n / / \\\n 20 70 120 "
},
{
"code": null,
"e": 25784,
"s": 25691,
"text": "(A) A(B) B(C) C(D) DAnswer: (C)Explanation: Refer following for steps used in AVL insertion."
},
{
"code": null,
"e": 25813,
"s": 25784,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 25965,
"s": 25813,
"text": "After insertion of 70, tree becomes following\n 60\n / \\ \n 20 100\n / \\\n 80 120 \n /\n 70\n"
},
{
"code": null,
"e": 26193,
"s": 25965,
"text": "We start from 50 and travel up. We keep travelling up till we find an unbalanced node. In above case, we reach the node 60 and see 60 got unbalanced after insertion and this is Right Left Case. So we need to apply two rotations"
},
{
"code": null,
"e": 26711,
"s": 26193,
"text": " 60 60 80\n / \\ Right Rotate(100) / \\ Left Rotate(60) / \\\n 20 100 -----------------> 20 80 ---------------> 60 100 \n / \\ / \\ / \\ \\\n 80 120 70 100 20 70 120 \n / \\ \n 70 120 \n"
},
{
"code": null,
"e": 26733,
"s": 26711,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 26762,
"s": 26733,
"text": "Balanced Binary Search Trees"
},
{
"code": null,
"e": 26778,
"s": 26762,
"text": "Data Structures"
},
{
"code": null,
"e": 26823,
"s": 26778,
"text": "Data Structures-Balanced Binary Search Trees"
},
{
"code": null,
"e": 26839,
"s": 26823,
"text": "Data Structures"
},
{
"code": null,
"e": 26855,
"s": 26839,
"text": "Data Structures"
},
{
"code": null,
"e": 26953,
"s": 26855,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26962,
"s": 26953,
"text": "Comments"
},
{
"code": null,
"e": 26975,
"s": 26962,
"text": "Old Comments"
},
{
"code": null,
"e": 27032,
"s": 26975,
"text": "C program to implement Adjacency Matrix of a given Graph"
},
{
"code": null,
"e": 27076,
"s": 27032,
"text": "Advantages and Disadvantages of Linked List"
},
{
"code": null,
"e": 27137,
"s": 27076,
"text": "Difference between Singly linked list and Doubly linked list"
},
{
"code": null,
"e": 27209,
"s": 27137,
"text": "Introduction to Data Structures | 10 most commonly used Data Structures"
},
{
"code": null,
"e": 27246,
"s": 27209,
"text": "FIFO vs LIFO approach in Programming"
},
{
"code": null,
"e": 27269,
"s": 27246,
"text": "Multilevel Linked List"
},
{
"code": null,
"e": 27308,
"s": 27269,
"text": "Advantages of vector over array in C++"
},
{
"code": null,
"e": 27355,
"s": 27308,
"text": "Bit manipulation | Swap Endianness of a number"
},
{
"code": null,
"e": 27403,
"s": 27355,
"text": "Difference between data type and data structure"
}
] |
How to move the horizontal slider right-to-left in Java?
|
At first, let us create a horizontal slider −
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 55);
Now, we will set it to move right-to-left using setInverted() −
slider.setInverted(true);
The following is an example to move the horizontal slider right-to-left −
package my;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.WindowConstants;
public class SwingDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Frame with Slider");
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 55);
slider.setInverted(true);
slider.setMinorTickSpacing(10);
slider.setMajorTickSpacing(25);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setBackground(Color.orange);
slider.setForeground(Color.white);
Font font = new Font("Serif", Font.BOLD, 20);
slider.setFont(font);
JPanel panel = new JPanel();
panel.add(slider);
frame.add(panel);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(600, 300);
frame.setVisible(true);
}
}
|
[
{
"code": null,
"e": 1108,
"s": 1062,
"text": "At first, let us create a horizontal slider −"
},
{
"code": null,
"e": 1170,
"s": 1108,
"text": "JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 55);"
},
{
"code": null,
"e": 1234,
"s": 1170,
"text": "Now, we will set it to move right-to-left using setInverted() −"
},
{
"code": null,
"e": 1260,
"s": 1234,
"text": "slider.setInverted(true);"
},
{
"code": null,
"e": 1334,
"s": 1260,
"text": "The following is an example to move the horizontal slider right-to-left −"
},
{
"code": null,
"e": 2261,
"s": 1334,
"text": "package my;\nimport java.awt.Color;\nimport java.awt.Font;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JSlider;\nimport javax.swing.WindowConstants;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Frame with Slider\");\n JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 55);\n slider.setInverted(true);\n slider.setMinorTickSpacing(10);\n slider.setMajorTickSpacing(25);\n slider.setPaintTicks(true);\n slider.setPaintLabels(true);\n slider.setBackground(Color.orange);\n slider.setForeground(Color.white);\n Font font = new Font(\"Serif\", Font.BOLD, 20);\n slider.setFont(font);\n JPanel panel = new JPanel();\n panel.add(slider);\n frame.add(panel);\n frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);\n frame.setSize(600, 300);\n frame.setVisible(true);\n }\n}"
}
] |
Maven - Deployment Automation
|
In project development, normally a deployment process consists of the following steps −
Check-in the code from all project in progress into the SVN (version control system) or source code repository and tag it.
Check-in the code from all project in progress into the SVN (version control system) or source code repository and tag it.
Download the complete source code from SVN.
Download the complete source code from SVN.
Build the application.
Build the application.
Store the build output either WAR or EAR file to a common network location.
Store the build output either WAR or EAR file to a common network location.
Get the file from network and deploy the file to the production site.
Get the file from network and deploy the file to the production site.
Updated the documentation with date and updated version number of the application.
Updated the documentation with date and updated version number of the application.
There are normally multiple people involved in the above mentioned deployment process. One team may handle check-in of code, other may handle build and so on. It is very likely that any step may be missed out due to manual efforts involved and owing to multi-team environment. For example, older build may not be replaced on network machine and deployment team deployed the older build again.
Automate the deployment process by combining the following −
Maven, to build and release projects.
SubVersion, source code repository, to manage source code.
Remote Repository Manager (Jfrog/Nexus) to manage project binaries.
We will be using Maven Release plug-in to create an automated release process.
For Example: bus-core-api project POM.xml.
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>bus-core-api</groupId>
<artifactId>bus-core-api</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<scm>
<url>http://www.svn.com</url>
<connection>scm:svn:http://localhost:8080/svn/jrepo/trunk/
Framework</connection>
<developerConnection>scm:svn:${username}/${password}@localhost:8080:
common_core_api:1101:code</developerConnection>
</scm>
<distributionManagement>
<repository>
<id>Core-API-Java-Release</id>
<name>Release repository</name>
<url>http://localhost:8081/nexus/content/repositories/
Core-Api-Release</url>
</repository>
</distributionManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.0-beta-9</version>
<configuration>
<useReleaseProfile>false</useReleaseProfile>
<goals>deploy</goals>
<scmCommentPrefix>[bus-core-api-release-checkin]-<
/scmCommentPrefix>
</configuration>
</plugin>
</plugins>
</build>
</project>
In Pom.xml, following are the important elements we have used −
SCM
Configures the SVN location from where Maven will check out the source code.
Repositories
Location where built WAR/EAR/JAR or any other artifact will be stored after code build is successful.
Plugin
maven-release-plugin is configured to automate the deployment process.
The Maven does the following useful tasks using maven-release-plugin.
mvn release:clean
It cleans the workspace in case the last release process was not successful.
mvn release:rollback
Rollback the changes done to workspace code and configuration in case the last release process was not successful.
mvn release:prepare
Performs multiple number of operations, such as −
Checks whether there are any uncommitted local changes or not.
Checks whether there are any uncommitted local changes or not.
Ensures that there are no SNAPSHOT dependencies.
Ensures that there are no SNAPSHOT dependencies.
Changes the version of the application and removes SNAPSHOT from the version to make release.
Changes the version of the application and removes SNAPSHOT from the version to make release.
Update pom files to SVN.
Update pom files to SVN.
Run test cases.
Run test cases.
Commit the modified POM files.
Commit the modified POM files.
Tag the code in subversion
Tag the code in subversion
Increment the version number and append SNAPSHOT for future release.
Increment the version number and append SNAPSHOT for future release.
Commit the modified POM files to SVN.
Commit the modified POM files to SVN.
mvn release:perform
Checks out the code using the previously defined tag and run the Maven deploy goal, to deploy the war or built artifact to repository.
Let's open the command console, go to the C:\ > MVN >bus-core-api directory and execute the following mvn command.
>mvn release:prepare
Maven will start building the project. Once build is successful run the following mvn command.
>mvn release:perform
Once build is successful you can verify the uploaded JAR file in your repository.
34 Lectures
4 hours
Karthikeya T
14 Lectures
1.5 hours
Quaatso Learning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2148,
"s": 2060,
"text": "In project development, normally a deployment process consists of the following steps −"
},
{
"code": null,
"e": 2271,
"s": 2148,
"text": "Check-in the code from all project in progress into the SVN (version control system) or source code repository and tag it."
},
{
"code": null,
"e": 2394,
"s": 2271,
"text": "Check-in the code from all project in progress into the SVN (version control system) or source code repository and tag it."
},
{
"code": null,
"e": 2438,
"s": 2394,
"text": "Download the complete source code from SVN."
},
{
"code": null,
"e": 2482,
"s": 2438,
"text": "Download the complete source code from SVN."
},
{
"code": null,
"e": 2505,
"s": 2482,
"text": "Build the application."
},
{
"code": null,
"e": 2528,
"s": 2505,
"text": "Build the application."
},
{
"code": null,
"e": 2604,
"s": 2528,
"text": "Store the build output either WAR or EAR file to a common network location."
},
{
"code": null,
"e": 2680,
"s": 2604,
"text": "Store the build output either WAR or EAR file to a common network location."
},
{
"code": null,
"e": 2750,
"s": 2680,
"text": "Get the file from network and deploy the file to the production site."
},
{
"code": null,
"e": 2820,
"s": 2750,
"text": "Get the file from network and deploy the file to the production site."
},
{
"code": null,
"e": 2903,
"s": 2820,
"text": "Updated the documentation with date and updated version number of the application."
},
{
"code": null,
"e": 2986,
"s": 2903,
"text": "Updated the documentation with date and updated version number of the application."
},
{
"code": null,
"e": 3379,
"s": 2986,
"text": "There are normally multiple people involved in the above mentioned deployment process. One team may handle check-in of code, other may handle build and so on. It is very likely that any step may be missed out due to manual efforts involved and owing to multi-team environment. For example, older build may not be replaced on network machine and deployment team deployed the older build again."
},
{
"code": null,
"e": 3440,
"s": 3379,
"text": "Automate the deployment process by combining the following −"
},
{
"code": null,
"e": 3478,
"s": 3440,
"text": "Maven, to build and release projects."
},
{
"code": null,
"e": 3537,
"s": 3478,
"text": "SubVersion, source code repository, to manage source code."
},
{
"code": null,
"e": 3605,
"s": 3537,
"text": "Remote Repository Manager (Jfrog/Nexus) to manage project binaries."
},
{
"code": null,
"e": 3684,
"s": 3605,
"text": "We will be using Maven Release plug-in to create an automated release process."
},
{
"code": null,
"e": 3727,
"s": 3684,
"text": "For Example: bus-core-api project POM.xml."
},
{
"code": null,
"e": 5194,
"s": 3727,
"text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>bus-core-api</groupId>\n <artifactId>bus-core-api</artifactId>\n <version>1.0-SNAPSHOT</version>\n <packaging>jar</packaging> \n <scm>\n <url>http://www.svn.com</url>\n <connection>scm:svn:http://localhost:8080/svn/jrepo/trunk/\n Framework</connection>\n <developerConnection>scm:svn:${username}/${password}@localhost:8080:\n common_core_api:1101:code</developerConnection>\n </scm>\n <distributionManagement>\n <repository>\n <id>Core-API-Java-Release</id>\n <name>Release repository</name>\n <url>http://localhost:8081/nexus/content/repositories/\n Core-Api-Release</url>\n </repository>\n </distributionManagement>\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-release-plugin</artifactId>\n <version>2.0-beta-9</version>\n <configuration>\n <useReleaseProfile>false</useReleaseProfile>\n <goals>deploy</goals>\n <scmCommentPrefix>[bus-core-api-release-checkin]-<\n /scmCommentPrefix>\n </configuration>\n </plugin>\n </plugins>\n </build>\n</project>"
},
{
"code": null,
"e": 5258,
"s": 5194,
"text": "In Pom.xml, following are the important elements we have used −"
},
{
"code": null,
"e": 5262,
"s": 5258,
"text": "SCM"
},
{
"code": null,
"e": 5339,
"s": 5262,
"text": "Configures the SVN location from where Maven will check out the source code."
},
{
"code": null,
"e": 5352,
"s": 5339,
"text": "Repositories"
},
{
"code": null,
"e": 5454,
"s": 5352,
"text": "Location where built WAR/EAR/JAR or any other artifact will be stored after code build is successful."
},
{
"code": null,
"e": 5461,
"s": 5454,
"text": "Plugin"
},
{
"code": null,
"e": 5532,
"s": 5461,
"text": "maven-release-plugin is configured to automate the deployment process."
},
{
"code": null,
"e": 5602,
"s": 5532,
"text": "The Maven does the following useful tasks using maven-release-plugin."
},
{
"code": null,
"e": 5621,
"s": 5602,
"text": "mvn release:clean\n"
},
{
"code": null,
"e": 5698,
"s": 5621,
"text": "It cleans the workspace in case the last release process was not successful."
},
{
"code": null,
"e": 5720,
"s": 5698,
"text": "mvn release:rollback\n"
},
{
"code": null,
"e": 5835,
"s": 5720,
"text": "Rollback the changes done to workspace code and configuration in case the last release process was not successful."
},
{
"code": null,
"e": 5856,
"s": 5835,
"text": "mvn release:prepare\n"
},
{
"code": null,
"e": 5906,
"s": 5856,
"text": "Performs multiple number of operations, such as −"
},
{
"code": null,
"e": 5969,
"s": 5906,
"text": "Checks whether there are any uncommitted local changes or not."
},
{
"code": null,
"e": 6032,
"s": 5969,
"text": "Checks whether there are any uncommitted local changes or not."
},
{
"code": null,
"e": 6081,
"s": 6032,
"text": "Ensures that there are no SNAPSHOT dependencies."
},
{
"code": null,
"e": 6130,
"s": 6081,
"text": "Ensures that there are no SNAPSHOT dependencies."
},
{
"code": null,
"e": 6224,
"s": 6130,
"text": "Changes the version of the application and removes SNAPSHOT from the version to make release."
},
{
"code": null,
"e": 6318,
"s": 6224,
"text": "Changes the version of the application and removes SNAPSHOT from the version to make release."
},
{
"code": null,
"e": 6343,
"s": 6318,
"text": "Update pom files to SVN."
},
{
"code": null,
"e": 6368,
"s": 6343,
"text": "Update pom files to SVN."
},
{
"code": null,
"e": 6384,
"s": 6368,
"text": "Run test cases."
},
{
"code": null,
"e": 6400,
"s": 6384,
"text": "Run test cases."
},
{
"code": null,
"e": 6431,
"s": 6400,
"text": "Commit the modified POM files."
},
{
"code": null,
"e": 6462,
"s": 6431,
"text": "Commit the modified POM files."
},
{
"code": null,
"e": 6489,
"s": 6462,
"text": "Tag the code in subversion"
},
{
"code": null,
"e": 6516,
"s": 6489,
"text": "Tag the code in subversion"
},
{
"code": null,
"e": 6585,
"s": 6516,
"text": "Increment the version number and append SNAPSHOT for future release."
},
{
"code": null,
"e": 6654,
"s": 6585,
"text": "Increment the version number and append SNAPSHOT for future release."
},
{
"code": null,
"e": 6692,
"s": 6654,
"text": "Commit the modified POM files to SVN."
},
{
"code": null,
"e": 6730,
"s": 6692,
"text": "Commit the modified POM files to SVN."
},
{
"code": null,
"e": 6751,
"s": 6730,
"text": "mvn release:perform\n"
},
{
"code": null,
"e": 6886,
"s": 6751,
"text": "Checks out the code using the previously defined tag and run the Maven deploy goal, to deploy the war or built artifact to repository."
},
{
"code": null,
"e": 7001,
"s": 6886,
"text": "Let's open the command console, go to the C:\\ > MVN >bus-core-api directory and execute the following mvn command."
},
{
"code": null,
"e": 7023,
"s": 7001,
"text": ">mvn release:prepare\n"
},
{
"code": null,
"e": 7118,
"s": 7023,
"text": "Maven will start building the project. Once build is successful run the following mvn command."
},
{
"code": null,
"e": 7140,
"s": 7118,
"text": ">mvn release:perform\n"
},
{
"code": null,
"e": 7222,
"s": 7140,
"text": "Once build is successful you can verify the uploaded JAR file in your repository."
},
{
"code": null,
"e": 7255,
"s": 7222,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7269,
"s": 7255,
"text": " Karthikeya T"
},
{
"code": null,
"e": 7304,
"s": 7269,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7322,
"s": 7304,
"text": " Quaatso Learning"
},
{
"code": null,
"e": 7329,
"s": 7322,
"text": " Print"
},
{
"code": null,
"e": 7340,
"s": 7329,
"text": " Add Notes"
}
] |
JavaScript adding a class name to the element - GeeksforGeeks
|
15 Nov, 2021
In this article, we will learn how to add the class name property to the element, along with understanding the implementation through the example. The class name attribute can be used by CSS and JavaScript to perform certain tasks for elements with the specified class name. Adding the class name by using JavaScript can be done in many ways.
Using .className property: This property is used to add a class name to the selected element.
Syntax:
It is used to set the className property.
element.className += "newClass";
It is used to return the className property.
element.className;
Property Value:
newClass: It specifies the element’s class name. For applying multiple classes, it needs to separate by space.
Return value: It is of string type which represents the class or list of classes of elements with space-separated.
Example: This example uses the .className property to add a class name.
HTML
<!DOCTYPE html><html> <head> <title>JavaScript to add class name</title> <style> .addCSS { color: green; font-size: 25px; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="p"> A Computer Science portal for Geeks. </p> <button onclick="addClass()"> AddClass </button> <!-- Script to add class name --> <script> function addClass() { var v = document.getElementById("p"); v.className += "addCSS"; } </script></body> </html>
Output:
.className Property
Using .add() method: This method is used to add a class name to the selected element.
Syntax:
element.classList.add("newClass");
Example: This example uses .add() method to add class name.
HTML
<!DOCTYPE html><html> <head> <style> .addCSS { background-color: green; color: white; padding: 20px; font-size: 25px; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="p"> A Computer Science portal for Geeks. </p> <button onclick="addClass()"> AddClass </button> <!-- Script to add class name --> <script> function addClass() { var elem = document.getElementById("p"); elem.classList.add("addCSS"); } </script></body> </html>
Output:
.add() Method
Supported Browser:
Google Chrome 22.0
Microsoft Edge 12.0
Internet Explorer 5.0
Firefox 1.0
Opera 8.0
Safari 1.0
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
bhaskargeeksforgeeks
JavaScript-Questions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 25180,
"s": 25152,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 25524,
"s": 25180,
"text": "In this article, we will learn how to add the class name property to the element, along with understanding the implementation through the example. The class name attribute can be used by CSS and JavaScript to perform certain tasks for elements with the specified class name. Adding the class name by using JavaScript can be done in many ways. "
},
{
"code": null,
"e": 25618,
"s": 25524,
"text": "Using .className property: This property is used to add a class name to the selected element."
},
{
"code": null,
"e": 25626,
"s": 25618,
"text": "Syntax:"
},
{
"code": null,
"e": 25668,
"s": 25626,
"text": "It is used to set the className property."
},
{
"code": null,
"e": 25701,
"s": 25668,
"text": "element.className += \"newClass\";"
},
{
"code": null,
"e": 25746,
"s": 25701,
"text": "It is used to return the className property."
},
{
"code": null,
"e": 25765,
"s": 25746,
"text": "element.className;"
},
{
"code": null,
"e": 25781,
"s": 25765,
"text": "Property Value:"
},
{
"code": null,
"e": 25892,
"s": 25781,
"text": "newClass: It specifies the element’s class name. For applying multiple classes, it needs to separate by space."
},
{
"code": null,
"e": 26007,
"s": 25892,
"text": "Return value: It is of string type which represents the class or list of classes of elements with space-separated."
},
{
"code": null,
"e": 26079,
"s": 26007,
"text": "Example: This example uses the .className property to add a class name."
},
{
"code": null,
"e": 26084,
"s": 26079,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>JavaScript to add class name</title> <style> .addCSS { color: green; font-size: 25px; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"p\"> A Computer Science portal for Geeks. </p> <button onclick=\"addClass()\"> AddClass </button> <!-- Script to add class name --> <script> function addClass() { var v = document.getElementById(\"p\"); v.className += \"addCSS\"; } </script></body> </html>",
"e": 26651,
"s": 26084,
"text": null
},
{
"code": null,
"e": 26659,
"s": 26651,
"text": "Output:"
},
{
"code": null,
"e": 26679,
"s": 26659,
"text": ".className Property"
},
{
"code": null,
"e": 26765,
"s": 26679,
"text": "Using .add() method: This method is used to add a class name to the selected element."
},
{
"code": null,
"e": 26773,
"s": 26765,
"text": "Syntax:"
},
{
"code": null,
"e": 26808,
"s": 26773,
"text": "element.classList.add(\"newClass\");"
},
{
"code": null,
"e": 26868,
"s": 26808,
"text": "Example: This example uses .add() method to add class name."
},
{
"code": null,
"e": 26873,
"s": 26868,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .addCSS { background-color: green; color: white; padding: 20px; font-size: 25px; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"p\"> A Computer Science portal for Geeks. </p> <button onclick=\"addClass()\"> AddClass </button> <!-- Script to add class name --> <script> function addClass() { var elem = document.getElementById(\"p\"); elem.classList.add(\"addCSS\"); } </script></body> </html>",
"e": 27455,
"s": 26873,
"text": null
},
{
"code": null,
"e": 27463,
"s": 27455,
"text": "Output:"
},
{
"code": null,
"e": 27477,
"s": 27463,
"text": ".add() Method"
},
{
"code": null,
"e": 27496,
"s": 27477,
"text": "Supported Browser:"
},
{
"code": null,
"e": 27515,
"s": 27496,
"text": "Google Chrome 22.0"
},
{
"code": null,
"e": 27535,
"s": 27515,
"text": "Microsoft Edge 12.0"
},
{
"code": null,
"e": 27557,
"s": 27535,
"text": "Internet Explorer 5.0"
},
{
"code": null,
"e": 27569,
"s": 27557,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 27579,
"s": 27569,
"text": "Opera 8.0"
},
{
"code": null,
"e": 27590,
"s": 27579,
"text": "Safari 1.0"
},
{
"code": null,
"e": 27809,
"s": 27590,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 27830,
"s": 27809,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 27851,
"s": 27830,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 27862,
"s": 27851,
"text": "JavaScript"
},
{
"code": null,
"e": 27879,
"s": 27862,
"text": "Web Technologies"
},
{
"code": null,
"e": 27977,
"s": 27879,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28022,
"s": 27977,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28083,
"s": 28022,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28155,
"s": 28083,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28201,
"s": 28155,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 28242,
"s": 28201,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28284,
"s": 28242,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28317,
"s": 28284,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28360,
"s": 28317,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28410,
"s": 28360,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
What is the usage and purpose of DCLGEN and host variables used in COBOL-DB2 program
|
A COBOL-DB2 program can query/update/insert/delete data from multiple DB2 tables. However, in order to achieve this, we must fulfill two main conditions.
Notify the structure of the DB2 table to the COBOL-DB2 program. This includes all the columns and data types of these columns.The respective host variables for each column. The host variables are used in the program logic to move the data from DB2 to program and vice versa. There is one host variable for every table column based on its data type. For example, for a table column with data type CHAR(2), there should be a host variable with equivalent COBOL data type as PIC X(2).
Notify the structure of the DB2 table to the COBOL-DB2 program. This includes all the columns and data types of these columns.
Notify the structure of the DB2 table to the COBOL-DB2 program. This includes all the columns and data types of these columns.
The respective host variables for each column. The host variables are used in the program logic to move the data from DB2 to program and vice versa. There is one host variable for every table column based on its data type. For example, for a table column with data type CHAR(2), there should be a host variable with equivalent COBOL data type as PIC X(2).
The respective host variables for each column. The host variables are used in the program logic to move the data from DB2 to program and vice versa. There is one host variable for every table column based on its data type. For example, for a table column with data type CHAR(2), there should be a host variable with equivalent COBOL data type as PIC X(2).
The DCLGEN utility helps us to generate the table structures and host variables automatically. Using this utility, we just need to give the DB2 table name and it will return
the table structure and the host variables in a PDS member. We can simply use this PDS member in our COBOL-DB2 program in the working storage section using the INCLUDE
statement as below−
EXEC SQL
INCLUDE ORDERD
END-EXEC
The ORDERD is a PDS member which is generated using a DCLGEN utility. This will have the structure of the ORDERS table and host variables for all the columns. For example,the columns ORDER_ID and ORDER_DATE with data type as CHAR(30) and TIMESTAMP will have a host variable as ORDER-ID PIC X(30) and ORDER-DATE PIC X(26) respectively.If we want to use this host variable to move the data from DB2 to program, then we can have−
EXEC SQL
EXEC SQL
SELECT ORDER_DATE
INTO :ORDER-DATE,
FROM ORDERS
WHERE ORDER_ID = :ORDER-ID
END-EXEC
END-EXEC
|
[
{
"code": null,
"e": 1216,
"s": 1062,
"text": "A COBOL-DB2 program can query/update/insert/delete data from multiple DB2 tables. However, in order to achieve this, we must fulfill two main conditions."
},
{
"code": null,
"e": 1698,
"s": 1216,
"text": "Notify the structure of the DB2 table to the COBOL-DB2 program. This includes all the columns and data types of these columns.The respective host variables for each column. The host variables are used in the program logic to move the data from DB2 to program and vice versa. There is one host variable for every table column based on its data type. For example, for a table column with data type CHAR(2), there should be a host variable with equivalent COBOL data type as PIC X(2)."
},
{
"code": null,
"e": 1825,
"s": 1698,
"text": "Notify the structure of the DB2 table to the COBOL-DB2 program. This includes all the columns and data types of these columns."
},
{
"code": null,
"e": 1952,
"s": 1825,
"text": "Notify the structure of the DB2 table to the COBOL-DB2 program. This includes all the columns and data types of these columns."
},
{
"code": null,
"e": 2308,
"s": 1952,
"text": "The respective host variables for each column. The host variables are used in the program logic to move the data from DB2 to program and vice versa. There is one host variable for every table column based on its data type. For example, for a table column with data type CHAR(2), there should be a host variable with equivalent COBOL data type as PIC X(2)."
},
{
"code": null,
"e": 2664,
"s": 2308,
"text": "The respective host variables for each column. The host variables are used in the program logic to move the data from DB2 to program and vice versa. There is one host variable for every table column based on its data type. For example, for a table column with data type CHAR(2), there should be a host variable with equivalent COBOL data type as PIC X(2)."
},
{
"code": null,
"e": 3026,
"s": 2664,
"text": "The DCLGEN utility helps us to generate the table structures and host variables automatically. Using this utility, we just need to give the DB2 table name and it will return\nthe table structure and the host variables in a PDS member. We can simply use this PDS member in our COBOL-DB2 program in the working storage section using the INCLUDE\nstatement as below−"
},
{
"code": null,
"e": 3062,
"s": 3026,
"text": "EXEC SQL\n INCLUDE ORDERD\nEND-EXEC"
},
{
"code": null,
"e": 3489,
"s": 3062,
"text": "The ORDERD is a PDS member which is generated using a DCLGEN utility. This will have the structure of the ORDERS table and host variables for all the columns. For example,the columns ORDER_ID and ORDER_DATE with data type as CHAR(30) and TIMESTAMP will have a host variable as ORDER-ID PIC X(30) and ORDER-DATE PIC X(26) respectively.If we want to use this host variable to move the data from DB2 to program, then we can have−"
},
{
"code": null,
"e": 3621,
"s": 3489,
"text": "EXEC SQL\nEXEC SQL\n SELECT ORDER_DATE\n INTO :ORDER-DATE,\n FROM ORDERS\n WHERE ORDER_ID = :ORDER-ID\nEND-EXEC\nEND-EXEC"
}
] |
Data Pipelines With Python And Pandas | by Matt | Towards Data Science
|
If you are not dealing with big data you are probably using Pandas to write scripts to do some data processing. If so, then you are certainly using Jupyter because it allows seeing the results of the transformations applied. However, you may have already noticed that notebooks can quickly become messy.
When the start-up phase comes, the question of reproducibility and maintenance arises. Tools such as paper mill allow you to put a notebook directly into production. However, this does not guarantee reproducibility and readability for a future person who will be in charge of maintenance when you are gone.
If notebooks offer the possibility of writing markdown to document its data processing, it’s quite time consuming and there is a risk that the code no longer matches the documentation over the iterations.
What is needed is to have a framework to refactor the code quickly and at the same time that allows people to quickly know what the code is doing.
genpipes is a small library to help write readable and reproducible pipelines based on decorators and generators. You can install it with pip install genpipes
It can easily be integrated with pandas in order to write data pipelines. Below a simple example of how to integrate the library with pandas code for data processing.
If you use scikit-learn you might get familiar with the Pipeline Class that allows creating a machine learning pipeline. With Genpipes it is possible to reproduce the same thing but for data processing scripts. Genpipes allow both to make the code readable and to create functions that are pipeable thanks to the Pipeline class. Let’s see in more details how it works.
The first task in data processing is usually to write code to acquire data. The library provides a decorator to declare your data source.
The decorators take in a list of inputs to be passed as positional arguments to the decorated function. This way you are binding arguments to the function but you are not hardcoding arguments inside the function.
However, if you want to let some arguments defined later you could use keywords arguments.
This way of proceeding makes it possible on the one hand to encapsulate these data sources and on the other hand to make the code more readable. Indeed having the entry just above the code of the function allows a little to have like a configuration file with the code which uses it.
But data sources are not yet part of the pipeline, we need to declare a generator in order to feed the stream.
Genpipes rely on generators to be able to create a series of tasks that take as input the output of the previous task. It means the first step of the pipeline should be a function that initializes the stream.
That the generatordecorator purpose. Function decorated with it is transformed into a generator object. You can decorate any function you want your stream begins with likedatasource
Or a more complex function, like a merge between two data source
To test your generatordecorated functions, you need to pass in a Python generator object.
Because the decorator returns a function that creates a generator object you can create many generator objects and feed several consumers.
the generator decorator allows us to put data into the stream, but not to work with values from the stream for this purpose we need processing functions.
Now that we have seen how to declare data sources and how to generate a stream thanks to generator decorator. Let’s see how to declare processing functions.
One big difference between generatorand processois that the function decorated with processor MUST BE a Python generator object. In addition, the function must also take as first argument the stream.
Even if we can use the decorator helper function alone, the library provides a Pipelineclass that helps to assemble functions decorated with generator and processor .
A pipeline object is composed of steps that are tuplewith 3 components:
1- The description of the step
2- The decorated function
3- The keywords arguments to forward as a dict, if no keywords arguments are needed then pass in an empty dict
The pipeline class allows both to describe the processing performed by the functions and to see the sequence of this one at a glance. By going back in the file we can have the detail of the functions that interest us.
One key feature is that when declaring the pipeline object we are not evaluating it. This means that we can import the pipeline without executing it. This allows you to write a file by domain data processing for example and assemble it in a main pipeline located in the entry point of a data processing script.
script/ app.py # import from pipelines and do final processing pipelines/ orders_processing.py # import datasource customer_processing.py datasources/ orders.py customers.py
Because readability is important when we call print on pipeline objects we get a string representation with the sequence of steps composing the pipeline instance. For instance, calling print in the pipe instance define earlier will give us this output:
>> print(pipe)---- Start ----1- data source is the merging of data one and data two2- droping dups---- End ----
To actually evaluate the pipeline, we need to call the run method. This method returns the last object pulled out from the stream. In our case, it will be the dedup data frame from the last defined step.
dedup_df = pipe.run()
We can run the pipeline multiple time, it will redo all the steps:
ddedup_df = pipe.run()dedup_df_bis = pipe.run()assert dedup_df.equals(dedup_df_bis) # True
Finally, pipeline objects can be used in other pipeline instance as a step:
If you are working with pandas to do non-large data processing then genpipes library can help you increase the readability and maintenance of your scripts with easy integration.
|
[
{
"code": null,
"e": 476,
"s": 172,
"text": "If you are not dealing with big data you are probably using Pandas to write scripts to do some data processing. If so, then you are certainly using Jupyter because it allows seeing the results of the transformations applied. However, you may have already noticed that notebooks can quickly become messy."
},
{
"code": null,
"e": 783,
"s": 476,
"text": "When the start-up phase comes, the question of reproducibility and maintenance arises. Tools such as paper mill allow you to put a notebook directly into production. However, this does not guarantee reproducibility and readability for a future person who will be in charge of maintenance when you are gone."
},
{
"code": null,
"e": 988,
"s": 783,
"text": "If notebooks offer the possibility of writing markdown to document its data processing, it’s quite time consuming and there is a risk that the code no longer matches the documentation over the iterations."
},
{
"code": null,
"e": 1135,
"s": 988,
"text": "What is needed is to have a framework to refactor the code quickly and at the same time that allows people to quickly know what the code is doing."
},
{
"code": null,
"e": 1294,
"s": 1135,
"text": "genpipes is a small library to help write readable and reproducible pipelines based on decorators and generators. You can install it with pip install genpipes"
},
{
"code": null,
"e": 1461,
"s": 1294,
"text": "It can easily be integrated with pandas in order to write data pipelines. Below a simple example of how to integrate the library with pandas code for data processing."
},
{
"code": null,
"e": 1830,
"s": 1461,
"text": "If you use scikit-learn you might get familiar with the Pipeline Class that allows creating a machine learning pipeline. With Genpipes it is possible to reproduce the same thing but for data processing scripts. Genpipes allow both to make the code readable and to create functions that are pipeable thanks to the Pipeline class. Let’s see in more details how it works."
},
{
"code": null,
"e": 1968,
"s": 1830,
"text": "The first task in data processing is usually to write code to acquire data. The library provides a decorator to declare your data source."
},
{
"code": null,
"e": 2181,
"s": 1968,
"text": "The decorators take in a list of inputs to be passed as positional arguments to the decorated function. This way you are binding arguments to the function but you are not hardcoding arguments inside the function."
},
{
"code": null,
"e": 2272,
"s": 2181,
"text": "However, if you want to let some arguments defined later you could use keywords arguments."
},
{
"code": null,
"e": 2556,
"s": 2272,
"text": "This way of proceeding makes it possible on the one hand to encapsulate these data sources and on the other hand to make the code more readable. Indeed having the entry just above the code of the function allows a little to have like a configuration file with the code which uses it."
},
{
"code": null,
"e": 2667,
"s": 2556,
"text": "But data sources are not yet part of the pipeline, we need to declare a generator in order to feed the stream."
},
{
"code": null,
"e": 2876,
"s": 2667,
"text": "Genpipes rely on generators to be able to create a series of tasks that take as input the output of the previous task. It means the first step of the pipeline should be a function that initializes the stream."
},
{
"code": null,
"e": 3058,
"s": 2876,
"text": "That the generatordecorator purpose. Function decorated with it is transformed into a generator object. You can decorate any function you want your stream begins with likedatasource"
},
{
"code": null,
"e": 3123,
"s": 3058,
"text": "Or a more complex function, like a merge between two data source"
},
{
"code": null,
"e": 3213,
"s": 3123,
"text": "To test your generatordecorated functions, you need to pass in a Python generator object."
},
{
"code": null,
"e": 3352,
"s": 3213,
"text": "Because the decorator returns a function that creates a generator object you can create many generator objects and feed several consumers."
},
{
"code": null,
"e": 3506,
"s": 3352,
"text": "the generator decorator allows us to put data into the stream, but not to work with values from the stream for this purpose we need processing functions."
},
{
"code": null,
"e": 3663,
"s": 3506,
"text": "Now that we have seen how to declare data sources and how to generate a stream thanks to generator decorator. Let’s see how to declare processing functions."
},
{
"code": null,
"e": 3863,
"s": 3663,
"text": "One big difference between generatorand processois that the function decorated with processor MUST BE a Python generator object. In addition, the function must also take as first argument the stream."
},
{
"code": null,
"e": 4030,
"s": 3863,
"text": "Even if we can use the decorator helper function alone, the library provides a Pipelineclass that helps to assemble functions decorated with generator and processor ."
},
{
"code": null,
"e": 4102,
"s": 4030,
"text": "A pipeline object is composed of steps that are tuplewith 3 components:"
},
{
"code": null,
"e": 4133,
"s": 4102,
"text": "1- The description of the step"
},
{
"code": null,
"e": 4159,
"s": 4133,
"text": "2- The decorated function"
},
{
"code": null,
"e": 4270,
"s": 4159,
"text": "3- The keywords arguments to forward as a dict, if no keywords arguments are needed then pass in an empty dict"
},
{
"code": null,
"e": 4488,
"s": 4270,
"text": "The pipeline class allows both to describe the processing performed by the functions and to see the sequence of this one at a glance. By going back in the file we can have the detail of the functions that interest us."
},
{
"code": null,
"e": 4799,
"s": 4488,
"text": "One key feature is that when declaring the pipeline object we are not evaluating it. This means that we can import the pipeline without executing it. This allows you to write a file by domain data processing for example and assemble it in a main pipeline located in the entry point of a data processing script."
},
{
"code": null,
"e": 4990,
"s": 4799,
"text": "script/ app.py # import from pipelines and do final processing pipelines/ orders_processing.py # import datasource customer_processing.py datasources/ orders.py customers.py"
},
{
"code": null,
"e": 5243,
"s": 4990,
"text": "Because readability is important when we call print on pipeline objects we get a string representation with the sequence of steps composing the pipeline instance. For instance, calling print in the pipe instance define earlier will give us this output:"
},
{
"code": null,
"e": 5355,
"s": 5243,
"text": ">> print(pipe)---- Start ----1- data source is the merging of data one and data two2- droping dups---- End ----"
},
{
"code": null,
"e": 5559,
"s": 5355,
"text": "To actually evaluate the pipeline, we need to call the run method. This method returns the last object pulled out from the stream. In our case, it will be the dedup data frame from the last defined step."
},
{
"code": null,
"e": 5581,
"s": 5559,
"text": "dedup_df = pipe.run()"
},
{
"code": null,
"e": 5648,
"s": 5581,
"text": "We can run the pipeline multiple time, it will redo all the steps:"
},
{
"code": null,
"e": 5739,
"s": 5648,
"text": "ddedup_df = pipe.run()dedup_df_bis = pipe.run()assert dedup_df.equals(dedup_df_bis) # True"
},
{
"code": null,
"e": 5815,
"s": 5739,
"text": "Finally, pipeline objects can be used in other pipeline instance as a step:"
}
] |
Differential Equations as a Neural Network Layers | by Kevin Hannay | Towards Data Science
|
The main idea of artificial neural networks (ANN) is to build up representations for complicated functions using compositions of relatively simple functions called layers.
A deep neural network is one that has many layers, or many functions composed together.
Although layers are typically simple functions( e.g. relu(Wx+b)) in general they could be any differentiable functions.
The layer is specified by some finite vector of parameters θ ∈ Rp. To be practically useful we need to be able to fit this layer (or layers) to data. This involves defining a cost or loss function which measures the closeness of the model prediction to the data.
If our layers are differentiable then we can find the gradient of this cost function ∇C(θ) and use this to find a local minimum of the cost in an efficient manner.
Here I am considering differential equations models. These systems describe the time evolution of the state of a system (x) in time, using an expression which involves the derivative of the current state. In general, they take the form:
A differential equation fits into our neural network framework, as it takes in some parameters and produces the solution as output and it is differentiable.
Thus, we can use a differential equation as a layer in a neural network. This is really neat for a few reasons:
Differential equations are the fundamental language of all physical laws.
Outside of physics and chemistry differential equations are an important tool in describing the behavior of complex systems. Using differential equations models in our neural networks allows these models to be combined with neural networks approaches.
Building effective neural networks involves choosing a good underlying structure for the network. It is often easier to think of describing how a function changes in time, then it is to write down a function for the phenomena. Relatively simple rate laws can turn into very complex behavior (see the Lorenz system below!).
For simplicity, in this article, I am going to focus on neural networks with a single differential equations based layer in this article. However, these layers could easily be embedded as one layer in a deep learning project. The combination of deep learning with domain knowledge in the form of a differential equation is a game-changer in many fields.
To demonstrate how you can build your own differential equations layers into neural networks I am going to make use of the Julia Flux, DiffEqFlux and DifferentialEquations libraries. In the article, I will keep the code to small snippets to allow for developing intuition, but the full code for these examples has been posted in this Github repo.
To begin we will consider fitting the parameters of a classic model in mathematical biology. The Lotka-Volterra predator prey model describes the oscillations in a population that can be observed in simple ecological communities.
A famous example of this can be observed in the Hudson bay trading company fur trade data from the 1800s.
The equations for the model are given by
The predator species oscillations will tend to lag behind the peak in the prey species population.
Now let’s use this model as a layer in a neural network, with a set of six parameters. Two for the initial populations of the prey x0 and predators y0 and the four rate parameters α, β, δ, γ.
In Julia, we can define this system and a set of default parameters.
Now we define the differential equation layer as a function of the input parameters. The parameter array has the first two entries as the initial conditions.
The next thing to do is generate some fake data to fit from (add some noise) and then define a loss function. I used a simple mean square error loss function for our data, although we certainly could add some regularization of the parameters to the loss function easily.
Finally, we define a function to actually perform the model fitting. Here is where the Julia ecosystem really pays off as this system can easily use gradient methods for fitting the parameters.
As you can see I use 3000 Adams iterations followed by a call to BFGS to fit minimize the cost. This is a good combination, you could just jump straight to BFGS but the convergence will take much longer. It is better to let the Adams iterations get you in the neighborhood and then finish with BFGS.
The recovered parameters are given by:
The parameters are [0.9987532818277052, 0.9809616721237869, 1.5075095360807464, 1.009470157647888, 2.974936372236448, 0.993477599859459] with final loss value 2.1229151208653736The actual parameters should be: [1,1,1.5,1,3,1]
Here is a plot of our data against the simulated time-series data. As you can see the minimization finds and excellent fit to the data.
Of course, the real test for a neural network is how it generalizes to validation data. In this case, we can easily test the system for an unobserved initial condition to see if our neural network has captured the dynamics.
Great it works!
Now let’s consider the problem of recovering the parameters from a dynamical system that often comes up in my research field. The Stuart-Landau equation describes the dynamics of a nonlinear system which is near a Hopf bifurcation (common way oscillations emerge in nonlinear systems). I’m going to consider a variation of this which comes up in the study of synchrony in populations of coupled oscillators.
Part of the motivation for using this model is due to my familiarity with this model. However, I have another deeper motivation. The Lotka-Volterra predator-prey model is a great model to start with, but it is kind of a weird model for mathematical biology. It is a conservative system, much like is observed in physical system (without friction). This means instead of having an isolated attracting oscillation (called a limit cycle) the Lotka-Volterra system has a whole class of concentric cycles.
This has the potential to skew our understanding of fitting differential equation models, because conservative systems retain a memory of initial conditions. For limit cycle oscillations we lose information about the initial conditions over time (transient dynamics decay, arrow of time). Since many initial conditions end up at the same final state this could make the question of parameter recovery more difficult.
The equations for the system are given by:
these are written in polar coordinates. Thus R describes the amplitude and ψ the angle in radians. The dynamics take the qualitative form of
In Julia it is a simple matter to update our predator prey model to allow for this type of system.
Now we define a ode layer generate some data and create a loss function.
Finally, the following function creates runs an optimization to recover parameters.
The recovered parameters are given by:
The parameters are [0.02293619193779294, 0.08918144968755219, 0.08304049248335474, 6.275224626122101, 0.11589347566722544, 0.9019465183126854] with final loss value 0.7300967336849258The actual parameters are:[0.0,0.08,0.1, 6.28, 0.1, 1.0]
The fit for the training data is shown below:
We can test our model further by looking at how well it generalizes for new initial values.
Now time for a fun application. Let’s consider a parameter recovery using time-series data from a chaotic system. For this, we will use the famous lorenz system.
It is simple enough to define this system in Julia:
As a matter of demonstration let’s take a look at some time series data for the X variable generated from slightly different initial condition values.
This plot demonstrates a sensitive dependence on initial conditions which is a hallmark of chaos.
As usual, we define a differential equation layer which depends on initial conditions and parameters.
Generate some data and add some noise to the time-series and define our usual error function.
Now define the training function using the DiffEqFlux library.
Running the optimization gives a good fit to the training data, which generalizes well when we integrate for times beyond the training sample.
We can also look at the training model fit in a time-series plot.
Since the model was only trained on t ∈ [0,10], we can see that the model generalizes pretty well for t ∈ [10,20] but quickly diverges from the true value after that time.
The parameters are [0.9727986684296102, 0.034212291835795355, -0.001627150535904438, 9.99887680497206, 28.00267472723392, 2.666573010932292] with final loss value 1.7015586033442565The actual parameters are:[1.0,0.0,0.0,10.0,28.0,2.6666666666666665]
So we have found a pretty close fit.
It is relatively straightforward to include differential equation models into neural networks using the Julia ecosystem (scientific machine learning sciml). This allows us to include whole branches of knowledge through classical dynamical systems models into our neural network models for time-series data. The next step is to combine these differential equations layers into our deep learning models.
On the subject of the interface of dynamical systems and artificial neural networks. Three possible generalizations of what we have begun here are:
Neural differential equations is a term that is used to describe using an artificial neural network function as the right-hand side of a dynamical system. Since these systems make use of a general ANN function they can show poor convergence in modeling time-series.
Universal differential equations is a term that has been used for mixing a mathematical model and a ANN function. The idea here is to specify as much as possible of the dynamics and then let the ANN fill in the unmodeled dynamics, control function, etc. These systems can show much faster convergence and allow us to combine the power of neural networks to describe high dimensional functions with domain knowledge.
Hybrid dynamical systems are used to combine differential equation models (or more generally domain knowledge of some kind) with a separate machine learning approach. Many variations of these types exist but I would distinguish this class that it separates the machine learning model from the domain model. They can then be combined or fed into one another as an input.
Also, I should mention that all of the models we discussed in this article can easily be moved to the GPU for training. One simply has to declare the initial conditions to be on the GPU.
Reminder all of the code for this article can be found here.
|
[
{
"code": null,
"e": 344,
"s": 172,
"text": "The main idea of artificial neural networks (ANN) is to build up representations for complicated functions using compositions of relatively simple functions called layers."
},
{
"code": null,
"e": 432,
"s": 344,
"text": "A deep neural network is one that has many layers, or many functions composed together."
},
{
"code": null,
"e": 552,
"s": 432,
"text": "Although layers are typically simple functions( e.g. relu(Wx+b)) in general they could be any differentiable functions."
},
{
"code": null,
"e": 815,
"s": 552,
"text": "The layer is specified by some finite vector of parameters θ ∈ Rp. To be practically useful we need to be able to fit this layer (or layers) to data. This involves defining a cost or loss function which measures the closeness of the model prediction to the data."
},
{
"code": null,
"e": 979,
"s": 815,
"text": "If our layers are differentiable then we can find the gradient of this cost function ∇C(θ) and use this to find a local minimum of the cost in an efficient manner."
},
{
"code": null,
"e": 1216,
"s": 979,
"text": "Here I am considering differential equations models. These systems describe the time evolution of the state of a system (x) in time, using an expression which involves the derivative of the current state. In general, they take the form:"
},
{
"code": null,
"e": 1373,
"s": 1216,
"text": "A differential equation fits into our neural network framework, as it takes in some parameters and produces the solution as output and it is differentiable."
},
{
"code": null,
"e": 1485,
"s": 1373,
"text": "Thus, we can use a differential equation as a layer in a neural network. This is really neat for a few reasons:"
},
{
"code": null,
"e": 1559,
"s": 1485,
"text": "Differential equations are the fundamental language of all physical laws."
},
{
"code": null,
"e": 1811,
"s": 1559,
"text": "Outside of physics and chemistry differential equations are an important tool in describing the behavior of complex systems. Using differential equations models in our neural networks allows these models to be combined with neural networks approaches."
},
{
"code": null,
"e": 2134,
"s": 1811,
"text": "Building effective neural networks involves choosing a good underlying structure for the network. It is often easier to think of describing how a function changes in time, then it is to write down a function for the phenomena. Relatively simple rate laws can turn into very complex behavior (see the Lorenz system below!)."
},
{
"code": null,
"e": 2488,
"s": 2134,
"text": "For simplicity, in this article, I am going to focus on neural networks with a single differential equations based layer in this article. However, these layers could easily be embedded as one layer in a deep learning project. The combination of deep learning with domain knowledge in the form of a differential equation is a game-changer in many fields."
},
{
"code": null,
"e": 2835,
"s": 2488,
"text": "To demonstrate how you can build your own differential equations layers into neural networks I am going to make use of the Julia Flux, DiffEqFlux and DifferentialEquations libraries. In the article, I will keep the code to small snippets to allow for developing intuition, but the full code for these examples has been posted in this Github repo."
},
{
"code": null,
"e": 3065,
"s": 2835,
"text": "To begin we will consider fitting the parameters of a classic model in mathematical biology. The Lotka-Volterra predator prey model describes the oscillations in a population that can be observed in simple ecological communities."
},
{
"code": null,
"e": 3171,
"s": 3065,
"text": "A famous example of this can be observed in the Hudson bay trading company fur trade data from the 1800s."
},
{
"code": null,
"e": 3212,
"s": 3171,
"text": "The equations for the model are given by"
},
{
"code": null,
"e": 3311,
"s": 3212,
"text": "The predator species oscillations will tend to lag behind the peak in the prey species population."
},
{
"code": null,
"e": 3503,
"s": 3311,
"text": "Now let’s use this model as a layer in a neural network, with a set of six parameters. Two for the initial populations of the prey x0 and predators y0 and the four rate parameters α, β, δ, γ."
},
{
"code": null,
"e": 3572,
"s": 3503,
"text": "In Julia, we can define this system and a set of default parameters."
},
{
"code": null,
"e": 3730,
"s": 3572,
"text": "Now we define the differential equation layer as a function of the input parameters. The parameter array has the first two entries as the initial conditions."
},
{
"code": null,
"e": 4001,
"s": 3730,
"text": "The next thing to do is generate some fake data to fit from (add some noise) and then define a loss function. I used a simple mean square error loss function for our data, although we certainly could add some regularization of the parameters to the loss function easily."
},
{
"code": null,
"e": 4195,
"s": 4001,
"text": "Finally, we define a function to actually perform the model fitting. Here is where the Julia ecosystem really pays off as this system can easily use gradient methods for fitting the parameters."
},
{
"code": null,
"e": 4495,
"s": 4195,
"text": "As you can see I use 3000 Adams iterations followed by a call to BFGS to fit minimize the cost. This is a good combination, you could just jump straight to BFGS but the convergence will take much longer. It is better to let the Adams iterations get you in the neighborhood and then finish with BFGS."
},
{
"code": null,
"e": 4534,
"s": 4495,
"text": "The recovered parameters are given by:"
},
{
"code": null,
"e": 4760,
"s": 4534,
"text": "The parameters are [0.9987532818277052, 0.9809616721237869, 1.5075095360807464, 1.009470157647888, 2.974936372236448, 0.993477599859459] with final loss value 2.1229151208653736The actual parameters should be: [1,1,1.5,1,3,1]"
},
{
"code": null,
"e": 4896,
"s": 4760,
"text": "Here is a plot of our data against the simulated time-series data. As you can see the minimization finds and excellent fit to the data."
},
{
"code": null,
"e": 5120,
"s": 4896,
"text": "Of course, the real test for a neural network is how it generalizes to validation data. In this case, we can easily test the system for an unobserved initial condition to see if our neural network has captured the dynamics."
},
{
"code": null,
"e": 5136,
"s": 5120,
"text": "Great it works!"
},
{
"code": null,
"e": 5544,
"s": 5136,
"text": "Now let’s consider the problem of recovering the parameters from a dynamical system that often comes up in my research field. The Stuart-Landau equation describes the dynamics of a nonlinear system which is near a Hopf bifurcation (common way oscillations emerge in nonlinear systems). I’m going to consider a variation of this which comes up in the study of synchrony in populations of coupled oscillators."
},
{
"code": null,
"e": 6045,
"s": 5544,
"text": "Part of the motivation for using this model is due to my familiarity with this model. However, I have another deeper motivation. The Lotka-Volterra predator-prey model is a great model to start with, but it is kind of a weird model for mathematical biology. It is a conservative system, much like is observed in physical system (without friction). This means instead of having an isolated attracting oscillation (called a limit cycle) the Lotka-Volterra system has a whole class of concentric cycles."
},
{
"code": null,
"e": 6462,
"s": 6045,
"text": "This has the potential to skew our understanding of fitting differential equation models, because conservative systems retain a memory of initial conditions. For limit cycle oscillations we lose information about the initial conditions over time (transient dynamics decay, arrow of time). Since many initial conditions end up at the same final state this could make the question of parameter recovery more difficult."
},
{
"code": null,
"e": 6505,
"s": 6462,
"text": "The equations for the system are given by:"
},
{
"code": null,
"e": 6646,
"s": 6505,
"text": "these are written in polar coordinates. Thus R describes the amplitude and ψ the angle in radians. The dynamics take the qualitative form of"
},
{
"code": null,
"e": 6745,
"s": 6646,
"text": "In Julia it is a simple matter to update our predator prey model to allow for this type of system."
},
{
"code": null,
"e": 6818,
"s": 6745,
"text": "Now we define a ode layer generate some data and create a loss function."
},
{
"code": null,
"e": 6902,
"s": 6818,
"text": "Finally, the following function creates runs an optimization to recover parameters."
},
{
"code": null,
"e": 6941,
"s": 6902,
"text": "The recovered parameters are given by:"
},
{
"code": null,
"e": 7181,
"s": 6941,
"text": "The parameters are [0.02293619193779294, 0.08918144968755219, 0.08304049248335474, 6.275224626122101, 0.11589347566722544, 0.9019465183126854] with final loss value 0.7300967336849258The actual parameters are:[0.0,0.08,0.1, 6.28, 0.1, 1.0]"
},
{
"code": null,
"e": 7227,
"s": 7181,
"text": "The fit for the training data is shown below:"
},
{
"code": null,
"e": 7319,
"s": 7227,
"text": "We can test our model further by looking at how well it generalizes for new initial values."
},
{
"code": null,
"e": 7481,
"s": 7319,
"text": "Now time for a fun application. Let’s consider a parameter recovery using time-series data from a chaotic system. For this, we will use the famous lorenz system."
},
{
"code": null,
"e": 7533,
"s": 7481,
"text": "It is simple enough to define this system in Julia:"
},
{
"code": null,
"e": 7684,
"s": 7533,
"text": "As a matter of demonstration let’s take a look at some time series data for the X variable generated from slightly different initial condition values."
},
{
"code": null,
"e": 7782,
"s": 7684,
"text": "This plot demonstrates a sensitive dependence on initial conditions which is a hallmark of chaos."
},
{
"code": null,
"e": 7884,
"s": 7782,
"text": "As usual, we define a differential equation layer which depends on initial conditions and parameters."
},
{
"code": null,
"e": 7978,
"s": 7884,
"text": "Generate some data and add some noise to the time-series and define our usual error function."
},
{
"code": null,
"e": 8041,
"s": 7978,
"text": "Now define the training function using the DiffEqFlux library."
},
{
"code": null,
"e": 8184,
"s": 8041,
"text": "Running the optimization gives a good fit to the training data, which generalizes well when we integrate for times beyond the training sample."
},
{
"code": null,
"e": 8250,
"s": 8184,
"text": "We can also look at the training model fit in a time-series plot."
},
{
"code": null,
"e": 8422,
"s": 8250,
"text": "Since the model was only trained on t ∈ [0,10], we can see that the model generalizes pretty well for t ∈ [10,20] but quickly diverges from the true value after that time."
},
{
"code": null,
"e": 8672,
"s": 8422,
"text": "The parameters are [0.9727986684296102, 0.034212291835795355, -0.001627150535904438, 9.99887680497206, 28.00267472723392, 2.666573010932292] with final loss value 1.7015586033442565The actual parameters are:[1.0,0.0,0.0,10.0,28.0,2.6666666666666665]"
},
{
"code": null,
"e": 8709,
"s": 8672,
"text": "So we have found a pretty close fit."
},
{
"code": null,
"e": 9111,
"s": 8709,
"text": "It is relatively straightforward to include differential equation models into neural networks using the Julia ecosystem (scientific machine learning sciml). This allows us to include whole branches of knowledge through classical dynamical systems models into our neural network models for time-series data. The next step is to combine these differential equations layers into our deep learning models."
},
{
"code": null,
"e": 9259,
"s": 9111,
"text": "On the subject of the interface of dynamical systems and artificial neural networks. Three possible generalizations of what we have begun here are:"
},
{
"code": null,
"e": 9525,
"s": 9259,
"text": "Neural differential equations is a term that is used to describe using an artificial neural network function as the right-hand side of a dynamical system. Since these systems make use of a general ANN function they can show poor convergence in modeling time-series."
},
{
"code": null,
"e": 9941,
"s": 9525,
"text": "Universal differential equations is a term that has been used for mixing a mathematical model and a ANN function. The idea here is to specify as much as possible of the dynamics and then let the ANN fill in the unmodeled dynamics, control function, etc. These systems can show much faster convergence and allow us to combine the power of neural networks to describe high dimensional functions with domain knowledge."
},
{
"code": null,
"e": 10311,
"s": 9941,
"text": "Hybrid dynamical systems are used to combine differential equation models (or more generally domain knowledge of some kind) with a separate machine learning approach. Many variations of these types exist but I would distinguish this class that it separates the machine learning model from the domain model. They can then be combined or fed into one another as an input."
},
{
"code": null,
"e": 10498,
"s": 10311,
"text": "Also, I should mention that all of the models we discussed in this article can easily be moved to the GPU for training. One simply has to declare the initial conditions to be on the GPU."
}
] |
How to change state continuously after a certain amount of time in React? - GeeksforGeeks
|
01 Sep, 2020
To change a state continuously after a certain amount of time is required in a few cases for the toggling. First, make a function that is responsible for changing the state of the component. Then call the function from the constructor method for the first time. Use the set interval method inside the function to change the state after a fixed amount of time. setInterval method takes two parameter callback and time. The callback function is called again and again after that given amount of time. Use the setState method to change the state of the component.
timing(){
setInterval(() => {
this.setState({
stateName : new-state-value
})
}, time)
}
Example 1: This example illustrates how to change the state continuously after a certain amount of time.
index.js:
Javascript
import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))
App.js:
Javascript
import React, { Component } from 'react' class App extends Component { constructor(props){ super(props) this.state = {Number : 0} this.makeTimer() } makeTimer(){ setInterval(() => { let rand = Math.floor(Math.random() * 10) + 1 this.setState({number: rand}) }, 1000) } render(){ return ( <div> <h1> Random Number : {this.state.number} </h1> </div> ) }} export default App
Output:
react-js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
How to append HTML code to a div using JavaScript ?
File uploading in React.js
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 27142,
"s": 27114,
"text": "\n01 Sep, 2020"
},
{
"code": null,
"e": 27705,
"s": 27142,
"text": "To change a state continuously after a certain amount of time is required in a few cases for the toggling. First, make a function that is responsible for changing the state of the component. Then call the function from the constructor method for the first time. Use the set interval method inside the function to change the state after a fixed amount of time. setInterval method takes two parameter callback and time. The callback function is called again and again after that given amount of time. Use the setState method to change the state of the component."
},
{
"code": null,
"e": 27812,
"s": 27705,
"text": "timing(){\n setInterval(() => {\n this.setState({\n stateName : new-state-value\n })\n }, time)\n}\n"
},
{
"code": null,
"e": 27917,
"s": 27812,
"text": "Example 1: This example illustrates how to change the state continuously after a certain amount of time."
},
{
"code": null,
"e": 27928,
"s": 27917,
"text": "index.js: "
},
{
"code": null,
"e": 27939,
"s": 27928,
"text": "Javascript"
},
{
"code": "import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))",
"e": 28079,
"s": 27939,
"text": null
},
{
"code": null,
"e": 28087,
"s": 28079,
"text": "App.js:"
},
{
"code": null,
"e": 28098,
"s": 28087,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react' class App extends Component { constructor(props){ super(props) this.state = {Number : 0} this.makeTimer() } makeTimer(){ setInterval(() => { let rand = Math.floor(Math.random() * 10) + 1 this.setState({number: rand}) }, 1000) } render(){ return ( <div> <h1> Random Number : {this.state.number} </h1> </div> ) }} export default App",
"e": 28556,
"s": 28098,
"text": null
},
{
"code": null,
"e": 28565,
"s": 28556,
"text": "Output: "
},
{
"code": null,
"e": 28574,
"s": 28565,
"text": "react-js"
},
{
"code": null,
"e": 28585,
"s": 28574,
"text": "JavaScript"
},
{
"code": null,
"e": 28602,
"s": 28585,
"text": "Web Technologies"
},
{
"code": null,
"e": 28700,
"s": 28602,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28745,
"s": 28700,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28806,
"s": 28745,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28875,
"s": 28806,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 28927,
"s": 28875,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28954,
"s": 28927,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 28996,
"s": 28954,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29029,
"s": 28996,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29072,
"s": 29029,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29134,
"s": 29072,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
How to copy rows from one table to another in MySQL?
|
For this, use INSERT INTO SELECT statement. Let us first create a table −
mysql> create table DemoTable1879
(
Id int,
Name varchar(20)
);
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1879 values(101,'Chris Brown');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1879 values(102,'David Miller');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1879 values(103,'Adam Smith');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1879;
This will produce the following output −
+------+--------------+
| Id | Name |
+------+--------------+
| 101 | Chris Brown |
| 102 | David Miller |
| 103 | Adam Smith |
+------+--------------+
3 rows in set (0.00 sec)
Here is the query to create second table −
mysql> create table DemoTable1880
(
ClientId int,
ClientName varchar(20)
);
Query OK, 0 rows affected (0.00 sec)
Here is the query to copy rows from one table to another −
mysql> insert into DemoTable1880(ClientId,ClientName) select Id,Name from DemoTable1879 where Id IN(101,103);
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
Display all records from the table using select statement −
mysql> select * from DemoTable1880;
This will produce the following output −
+----------+-------------+
| ClientId | ClientName |
+----------+-------------+
| 101 | Chris Brown |
| 103 | Adam Smith |
+----------+-------------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1136,
"s": 1062,
"text": "For this, use INSERT INTO SELECT statement. Let us first create a table −"
},
{
"code": null,
"e": 1249,
"s": 1136,
"text": "mysql> create table DemoTable1879\n (\n Id int,\n Name varchar(20)\n );\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 1305,
"s": 1249,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1593,
"s": 1305,
"text": "mysql> insert into DemoTable1879 values(101,'Chris Brown');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1879 values(102,'David Miller');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1879 values(103,'Adam Smith');\nQuery OK, 1 row affected (0.00 sec)"
},
{
"code": null,
"e": 1653,
"s": 1593,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1689,
"s": 1653,
"text": "mysql> select * from DemoTable1879;"
},
{
"code": null,
"e": 1730,
"s": 1689,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1923,
"s": 1730,
"text": "+------+--------------+\n| Id | Name |\n+------+--------------+\n| 101 | Chris Brown |\n| 102 | David Miller |\n| 103 | Adam Smith |\n+------+--------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1966,
"s": 1923,
"text": "Here is the query to create second table −"
},
{
"code": null,
"e": 2091,
"s": 1966,
"text": "mysql> create table DemoTable1880\n (\n ClientId int,\n ClientName varchar(20)\n );\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 2150,
"s": 2091,
"text": "Here is the query to copy rows from one table to another −"
},
{
"code": null,
"e": 2336,
"s": 2150,
"text": "mysql> insert into DemoTable1880(ClientId,ClientName) select Id,Name from DemoTable1879 where Id IN(101,103);\nQuery OK, 2 rows affected (0.00 sec)\nRecords: 2 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2396,
"s": 2336,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2432,
"s": 2396,
"text": "mysql> select * from DemoTable1880;"
},
{
"code": null,
"e": 2473,
"s": 2432,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2660,
"s": 2473,
"text": "+----------+-------------+\n| ClientId | ClientName |\n+----------+-------------+\n| 101 | Chris Brown |\n| 103 | Adam Smith |\n+----------+-------------+\n2 rows in set (0.00 sec)"
}
] |
Java If ... Else
|
Java supports the usual logical conditions from mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
You can use these conditions to perform different actions for different decisions.
Java has the following conditional statements:
Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed
Use the if statement to specify a block of Java code to be executed if a condition is true.
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
In the example below, we test two values to find out if 20 is greater than
18. If the condition is true, print some text:
if (20 > 18) {
System.out.println("20 is greater than 18");
}
Try it Yourself »
We can also test variables:
int x = 20;
int y = 18;
if (x > y) {
System.out.println("x is greater than y");
}
Try it Yourself »
In the example above we use two variables, x and y,
to test whether x is greater than y
(using the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that "x is greater than y".
Use the else statement to specify a block of code to be executed if the condition is false.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
Try it Yourself »
In the example above, time (20) is greater than 18, so the condition is false.
Because of this, we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good day".
Use the else if statement to specify a new condition if the first condition is false.
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 20) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
Try it Yourself »
In the example above, time (22) is greater than 10, so the first condition is false. The next condition, in the
else if statement, is also false, so we move on to the else
condition since condition1 and condition2 is both false - and print to the screen "Good
evening".
However, if the time was 14, our program would print "Good day."
Print "Hello World" if x is greater than y.
int x = 50;
int y = 10;
(x y) {
System.out.println("Hello World");
}
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 61,
"s": 0,
"text": "Java supports the usual logical conditions from mathematics:"
},
{
"code": null,
"e": 78,
"s": 61,
"text": "Less than: a < b"
},
{
"code": null,
"e": 108,
"s": 78,
"text": "Less than or equal to: a <= b"
},
{
"code": null,
"e": 128,
"s": 108,
"text": "Greater than: a > b"
},
{
"code": null,
"e": 161,
"s": 128,
"text": "Greater than or equal to: a >= b"
},
{
"code": null,
"e": 177,
"s": 161,
"text": "Equal to a == b"
},
{
"code": null,
"e": 198,
"s": 177,
"text": "Not Equal to: a != b"
},
{
"code": null,
"e": 281,
"s": 198,
"text": "You can use these conditions to perform different actions for different decisions."
},
{
"code": null,
"e": 328,
"s": 281,
"text": "Java has the following conditional statements:"
},
{
"code": null,
"e": 411,
"s": 328,
"text": "Use if to specify a block of code to be executed, if a specified condition is true"
},
{
"code": null,
"e": 494,
"s": 411,
"text": "Use else to specify a block of code to be executed, if the same condition is false"
},
{
"code": null,
"e": 574,
"s": 494,
"text": "Use else if to specify a new condition to test, if the first condition is false"
},
{
"code": null,
"e": 643,
"s": 574,
"text": "Use switch to specify many alternative blocks of code to be executed"
},
{
"code": null,
"e": 735,
"s": 643,
"text": "Use the if statement to specify a block of Java code to be executed if a condition is true."
},
{
"code": null,
"e": 814,
"s": 735,
"text": "if (condition) {\n // block of code to be executed if the condition is true\n}\n"
},
{
"code": null,
"e": 905,
"s": 814,
"text": "Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error."
},
{
"code": null,
"e": 1028,
"s": 905,
"text": "In the example below, we test two values to find out if 20 is greater than \n18. If the condition is true, print some text:"
},
{
"code": null,
"e": 1093,
"s": 1028,
"text": "if (20 > 18) {\n System.out.println(\"20 is greater than 18\");\n}\n"
},
{
"code": null,
"e": 1113,
"s": 1093,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 1141,
"s": 1113,
"text": "We can also test variables:"
},
{
"code": null,
"e": 1226,
"s": 1141,
"text": "int x = 20;\nint y = 18;\nif (x > y) {\n System.out.println(\"x is greater than y\");\n}\n"
},
{
"code": null,
"e": 1246,
"s": 1226,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 1476,
"s": 1246,
"text": "In the example above we use two variables, x and y, \nto test whether x is greater than y \n(using the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that \"x is greater than y\"."
},
{
"code": null,
"e": 1568,
"s": 1476,
"text": "Use the else statement to specify a block of code to be executed if the condition is false."
},
{
"code": null,
"e": 1716,
"s": 1568,
"text": "if (condition) {\n // block of code to be executed if the condition is true\n} else {\n // block of code to be executed if the condition is false\n}\n"
},
{
"code": null,
"e": 1863,
"s": 1716,
"text": "int time = 20;\nif (time < 18) {\n System.out.println(\"Good day.\");\n} else {\n System.out.println(\"Good evening.\");\n}\n// Outputs \"Good evening.\"\n \n"
},
{
"code": null,
"e": 1883,
"s": 1863,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 2120,
"s": 1883,
"text": "In the example above, time (20) is greater than 18, so the condition is false. \nBecause of this, we move on to the else condition and print to the screen \"Good \nevening\". If the time was less than 18, the program would print \"Good day\"."
},
{
"code": null,
"e": 2206,
"s": 2120,
"text": "Use the else if statement to specify a new condition if the first condition is false."
},
{
"code": null,
"e": 2486,
"s": 2206,
"text": "if (condition1) {\n // block of code to be executed if condition1 is true\n} else if (condition2) {\n // block of code to be executed if the condition1 is false and condition2 is true\n} else {\n // block of code to be executed if the condition1 is false and condition2 is false\n}\n"
},
{
"code": null,
"e": 2696,
"s": 2486,
"text": "int time = 22;\nif (time < 10) {\n System.out.println(\"Good morning.\");\n} else if (time < 20) {\n System.out.println(\"Good day.\");\n} else {\n System.out.println(\"Good evening.\");\n}\n// Outputs \"Good evening.\"\n \n"
},
{
"code": null,
"e": 2716,
"s": 2696,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 2989,
"s": 2716,
"text": "In the example above, time (22) is greater than 10, so the first condition is false. The next condition, in the \nelse if statement, is also false, so we move on to the else\ncondition since condition1 and condition2 is both false - and print to the screen \"Good \nevening\"."
},
{
"code": null,
"e": 3054,
"s": 2989,
"text": "However, if the time was 14, our program would print \"Good day.\""
},
{
"code": null,
"e": 3098,
"s": 3054,
"text": "Print \"Hello World\" if x is greater than y."
},
{
"code": null,
"e": 3172,
"s": 3098,
"text": "int x = 50;\nint y = 10;\n (x y) {\n System.out.println(\"Hello World\");\n}\n"
},
{
"code": null,
"e": 3191,
"s": 3172,
"text": "Start the Exercise"
},
{
"code": null,
"e": 3224,
"s": 3191,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 3266,
"s": 3224,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 3373,
"s": 3266,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 3392,
"s": 3373,
"text": "[email protected]"
}
] |
How to retrieve XY data from a Matplotlib figure?
|
To retrieve XY data from a matplotlib figure, we can use get_xdata() and get_ydata() methods.
Create x and y data points using numpy.
Create x and y data points using numpy.
Limit X and Y axes range, using xlim() and ylim() methods.
Limit X and Y axes range, using xlim() and ylim() methods.
Plot xs and ys data points using plot() method with marker=diamond, color=red, and markersize=10, store the returned tuple in a line.
Plot xs and ys data points using plot() method with marker=diamond, color=red, and markersize=10, store the returned tuple in a line.
Use get_xdata() and get_ydata() methods on the line to get xy data.
Use get_xdata() and get_ydata() methods on the line to get xy data.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
xs = np.random.rand(10)
ys = np.random.rand(10)
plt.xlim(0, 1)
plt.ylim(0, 1)
line, = plt.plot(xs, ys, marker='d', c='red', markersize=10)
xdata = line.get_xdata()
ydata = line.get_ydata()
print("X-data of plot is: {}\nY-data for plot is: {}".format(xdata, ydata))
plt.show()
When we execute the code, it will display a plot and print its XY data on the console.
X-data of plot is: [0.80956382 0.99844606 0.57811592 0.01201992 0.85059459
0.03628843 0.99122502 0.7581602 0.93371784 0.60358098]
Y-data for plot is: [0.65190208 0.27895754 0.46742327 0.79049074 0.36485545
0.80771822 0.9753513 0.91897778 0.17651205 0.7898951 ]
|
[
{
"code": null,
"e": 1156,
"s": 1062,
"text": "To retrieve XY data from a matplotlib figure, we can use get_xdata() and get_ydata() methods."
},
{
"code": null,
"e": 1196,
"s": 1156,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1236,
"s": 1196,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1295,
"s": 1236,
"text": "Limit X and Y axes range, using xlim() and ylim() methods."
},
{
"code": null,
"e": 1354,
"s": 1295,
"text": "Limit X and Y axes range, using xlim() and ylim() methods."
},
{
"code": null,
"e": 1488,
"s": 1354,
"text": "Plot xs and ys data points using plot() method with marker=diamond, color=red, and markersize=10, store the returned tuple in a line."
},
{
"code": null,
"e": 1622,
"s": 1488,
"text": "Plot xs and ys data points using plot() method with marker=diamond, color=red, and markersize=10, store the returned tuple in a line."
},
{
"code": null,
"e": 1690,
"s": 1622,
"text": "Use get_xdata() and get_ydata() methods on the line to get xy data."
},
{
"code": null,
"e": 1758,
"s": 1690,
"text": "Use get_xdata() and get_ydata() methods on the line to get xy data."
},
{
"code": null,
"e": 1800,
"s": 1758,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1842,
"s": 1800,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2261,
"s": 1842,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nxs = np.random.rand(10)\nys = np.random.rand(10)\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nline, = plt.plot(xs, ys, marker='d', c='red', markersize=10)\nxdata = line.get_xdata()\nydata = line.get_ydata()\nprint(\"X-data of plot is: {}\\nY-data for plot is: {}\".format(xdata, ydata))\nplt.show()"
},
{
"code": null,
"e": 2348,
"s": 2261,
"text": "When we execute the code, it will display a plot and print its XY data on the console."
},
{
"code": null,
"e": 2609,
"s": 2348,
"text": "X-data of plot is: [0.80956382 0.99844606 0.57811592 0.01201992 0.85059459\n0.03628843 0.99122502 0.7581602 0.93371784 0.60358098]\nY-data for plot is: [0.65190208 0.27895754 0.46742327 0.79049074 0.36485545\n0.80771822 0.9753513 0.91897778 0.17651205 0.7898951 ]"
}
] |
Count Possible Decodings of a given Digit Sequence in C++
|
We are given a string representing a digit sequence. Each digit is decoded from 1 to 26 as English Alphabet. 1 is ‘A’, 2 is ‘B’ and so on till 26 as ‘Z’. The goal is to find the count of all possible decodings out of a given digit sequence. If the sequence is ‘123’ then possible decodings are ‘ABC’ ( 1-2-3 ), ‘LC’ (12-3), ‘AW’ (1-23). Count is 3.
Let us understand with examples.
Input − str[]=”1532”
Output − Count of Possible Decodings of a given Digit Sequence are − 2
Explanation − Possible decodings are AECB - (1-5-3-2) and OCB (15-3-2).
Input − str[]=”216”
Output − Count of Possible Decodings of a given Digit Sequence are − 3
Explanation − Possible decodings are “BAF” ( 2-1-6 ), “UF” ( 21-6 ), “BP” ( 2-16 )
We will do this using a recursive method. Pass portions of string to this recursive method.
Check if the last digit is not ‘0’ if true, check the rest of the string between 0 and length-1. Check if the last two digit string portion makes a number between 1 and 26. If true, update count and check the rest of the string between 0 and length-2.
We are taking the input as string str[].
We are taking the input as string str[].
Function decode_digit_seq(char *str, int length) takes the string and its length and returns count of possible decodings of str.
Function decode_digit_seq(char *str, int length) takes the string and its length and returns count of possible decodings of str.
If length is 0. Return 1.
If length is 0. Return 1.
If length is 1. Return 1.
If length is 1. Return 1.
If last single character is non-zero, count will be decode_digit_seq(str, int length-1)
If last single character is non-zero, count will be decode_digit_seq(str, int length-1)
If the second last character is 1 then last two digits would be between 10 and 19 (J to S ), update count as count = count + decode_digit_seq(str, length-2)
If the second last character is 1 then last two digits would be between 10 and 19 (J to S ), update count as count = count + decode_digit_seq(str, length-2)
If second last character is 2 and last character is <7 then last two digits would be between 20 and 26 (T to Z), update count as count = count + decode_digit_seq(str, length-2)
If second last character is 2 and last character is <7 then last two digits would be between 20 and 26 (T to Z), update count as count = count + decode_digit_seq(str, length-2)
Now all cases are taken.
Now all cases are taken.
In the end after all recursions return count as result.
In the end after all recursions return count as result.
Live Demo
#include <iostream>
#include
using namespace std;
int decode_digit_seq(char *str, int length){
int count = 0;
if(length == 0){
return 1;
}
if(length == 1){
return 1;
}
if(str[0] == '0'){
return 0;
}
if(str[length-1] > '0'){
count = decode_digit_seq(str, length-1);
}
if(str[length-2] == '1'){
count = count + decode_digit_seq(str, length-2);
}
if(str[length-2] == '2' && str[length-1] < '7'){
count = count + decode_digit_seq(str, length-2);
}
return count;
}
int main(){
char str[] = "7651";
int length = strlen(str);
cout<<"Count of Possible Decodings of a given Digit Sequence are: "<< decode_digit_seq(str, length);
return 0;
}
If we run the above code it will generate the following output −
Count of Possible Decoding of a given Digit Sequence are: 1
|
[
{
"code": null,
"e": 1411,
"s": 1062,
"text": "We are given a string representing a digit sequence. Each digit is decoded from 1 to 26 as English Alphabet. 1 is ‘A’, 2 is ‘B’ and so on till 26 as ‘Z’. The goal is to find the count of all possible decodings out of a given digit sequence. If the sequence is ‘123’ then possible decodings are ‘ABC’ ( 1-2-3 ), ‘LC’ (12-3), ‘AW’ (1-23). Count is 3."
},
{
"code": null,
"e": 1444,
"s": 1411,
"text": "Let us understand with examples."
},
{
"code": null,
"e": 1465,
"s": 1444,
"text": "Input − str[]=”1532”"
},
{
"code": null,
"e": 1536,
"s": 1465,
"text": "Output − Count of Possible Decodings of a given Digit Sequence are − 2"
},
{
"code": null,
"e": 1608,
"s": 1536,
"text": "Explanation − Possible decodings are AECB - (1-5-3-2) and OCB (15-3-2)."
},
{
"code": null,
"e": 1628,
"s": 1608,
"text": "Input − str[]=”216”"
},
{
"code": null,
"e": 1699,
"s": 1628,
"text": "Output − Count of Possible Decodings of a given Digit Sequence are − 3"
},
{
"code": null,
"e": 1782,
"s": 1699,
"text": "Explanation − Possible decodings are “BAF” ( 2-1-6 ), “UF” ( 21-6 ), “BP” ( 2-16 )"
},
{
"code": null,
"e": 1874,
"s": 1782,
"text": "We will do this using a recursive method. Pass portions of string to this recursive method."
},
{
"code": null,
"e": 2126,
"s": 1874,
"text": "Check if the last digit is not ‘0’ if true, check the rest of the string between 0 and length-1. Check if the last two digit string portion makes a number between 1 and 26. If true, update count and check the rest of the string between 0 and length-2."
},
{
"code": null,
"e": 2167,
"s": 2126,
"text": "We are taking the input as string str[]."
},
{
"code": null,
"e": 2208,
"s": 2167,
"text": "We are taking the input as string str[]."
},
{
"code": null,
"e": 2337,
"s": 2208,
"text": "Function decode_digit_seq(char *str, int length) takes the string and its length and returns count of possible decodings of str."
},
{
"code": null,
"e": 2466,
"s": 2337,
"text": "Function decode_digit_seq(char *str, int length) takes the string and its length and returns count of possible decodings of str."
},
{
"code": null,
"e": 2492,
"s": 2466,
"text": "If length is 0. Return 1."
},
{
"code": null,
"e": 2518,
"s": 2492,
"text": "If length is 0. Return 1."
},
{
"code": null,
"e": 2544,
"s": 2518,
"text": "If length is 1. Return 1."
},
{
"code": null,
"e": 2570,
"s": 2544,
"text": "If length is 1. Return 1."
},
{
"code": null,
"e": 2658,
"s": 2570,
"text": "If last single character is non-zero, count will be decode_digit_seq(str, int length-1)"
},
{
"code": null,
"e": 2746,
"s": 2658,
"text": "If last single character is non-zero, count will be decode_digit_seq(str, int length-1)"
},
{
"code": null,
"e": 2903,
"s": 2746,
"text": "If the second last character is 1 then last two digits would be between 10 and 19 (J to S ), update count as count = count + decode_digit_seq(str, length-2)"
},
{
"code": null,
"e": 3060,
"s": 2903,
"text": "If the second last character is 1 then last two digits would be between 10 and 19 (J to S ), update count as count = count + decode_digit_seq(str, length-2)"
},
{
"code": null,
"e": 3237,
"s": 3060,
"text": "If second last character is 2 and last character is <7 then last two digits would be between 20 and 26 (T to Z), update count as count = count + decode_digit_seq(str, length-2)"
},
{
"code": null,
"e": 3414,
"s": 3237,
"text": "If second last character is 2 and last character is <7 then last two digits would be between 20 and 26 (T to Z), update count as count = count + decode_digit_seq(str, length-2)"
},
{
"code": null,
"e": 3439,
"s": 3414,
"text": "Now all cases are taken."
},
{
"code": null,
"e": 3464,
"s": 3439,
"text": "Now all cases are taken."
},
{
"code": null,
"e": 3520,
"s": 3464,
"text": "In the end after all recursions return count as result."
},
{
"code": null,
"e": 3576,
"s": 3520,
"text": "In the end after all recursions return count as result."
},
{
"code": null,
"e": 3587,
"s": 3576,
"text": " Live Demo"
},
{
"code": null,
"e": 4309,
"s": 3587,
"text": "#include <iostream>\n#include\nusing namespace std;\nint decode_digit_seq(char *str, int length){\n int count = 0;\n if(length == 0){\n return 1;\n }\n if(length == 1){\n return 1;\n }\n if(str[0] == '0'){\n return 0;\n }\n if(str[length-1] > '0'){\n count = decode_digit_seq(str, length-1);\n }\n if(str[length-2] == '1'){\n count = count + decode_digit_seq(str, length-2);\n }\n if(str[length-2] == '2' && str[length-1] < '7'){\n count = count + decode_digit_seq(str, length-2);\n }\n return count;\n}\nint main(){\n char str[] = \"7651\";\n int length = strlen(str);\n cout<<\"Count of Possible Decodings of a given Digit Sequence are: \"<< decode_digit_seq(str, length);\n return 0;\n}"
},
{
"code": null,
"e": 4374,
"s": 4309,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 4434,
"s": 4374,
"text": "Count of Possible Decoding of a given Digit Sequence are: 1"
}
] |
JSON.simple - Encode JSONObject
|
Using JSON.simple, we can encode a JSON Object using following ways −
Encode a JSON Object - to String − Simple encoding.
Encode a JSON Object - to String − Simple encoding.
Encode a JSON Object - Streaming − Output can be used for streaming.
Encode a JSON Object - Streaming − Output can be used for streaming.
Encode a JSON Object - Using Map − Encoding by preserving the order.
Encode a JSON Object - Using Map − Encoding by preserving the order.
Encode a JSON Object - Using Map and Streaming − Encoding by preserving the order and to stream.
Encode a JSON Object - Using Map and Streaming − Encoding by preserving the order and to stream.
Following example illustrates the above concepts.
import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
class JsonDemo {
public static void main(String[] args) throws IOException {
JSONObject obj = new JSONObject();
String jsonText;
obj.put("name", "foo");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", new Boolean(true));
jsonText = obj.toString();
System.out.println("Encode a JSON Object - to String");
System.out.print(jsonText);
StringWriter out = new StringWriter();
obj.writeJSONString(out);
jsonText = out.toString();
System.out.println("\nEncode a JSON Object - Streaming");
System.out.print(jsonText);
Map obj1 = new LinkedHashMap();
obj1.put("name", "foo");
obj1.put("num", new Integer(100));
obj1.put("balance", new Double(1000.21));
obj1.put("is_vip", new Boolean(true));
jsonText = JSONValue.toJSONString(obj1);
System.out.println("\nEncode a JSON Object - Preserving Order");
System.out.print(jsonText);
out = new StringWriter();
JSONValue.writeJSONString(obj1, out);
jsonText = out.toString();
System.out.println("\nEncode a JSON Object - Preserving Order and Stream");
System.out.print(jsonText);
}
}
Encode a JSON Object - to String
{"balance":1000.21,"is_vip":true,"num":100,"name":"foo"}
Encode a JSON Object - Streaming
{"balance":1000.21,"is_vip":true,"num":100,"name":"foo"}
Encode a JSON Object - Preserving Order
{"name":"foo","num":100,"balance":1000.21,"is_vip":true}
Encode a JSON Object - Preserving Order and Stream
{"name":"foo","num":100,"balance":1000.21,"is_vip":true}
20 Lectures
1 hours
Laurence Svekis
16 Lectures
1 hours
Laurence Svekis
10 Lectures
1 hours
Laurence Svekis
23 Lectures
2.5 hours
Laurence Svekis
9 Lectures
48 mins
Nilay Mehta
18 Lectures
2.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2293,
"s": 2223,
"text": "Using JSON.simple, we can encode a JSON Object using following ways −"
},
{
"code": null,
"e": 2345,
"s": 2293,
"text": "Encode a JSON Object - to String − Simple encoding."
},
{
"code": null,
"e": 2397,
"s": 2345,
"text": "Encode a JSON Object - to String − Simple encoding."
},
{
"code": null,
"e": 2466,
"s": 2397,
"text": "Encode a JSON Object - Streaming − Output can be used for streaming."
},
{
"code": null,
"e": 2535,
"s": 2466,
"text": "Encode a JSON Object - Streaming − Output can be used for streaming."
},
{
"code": null,
"e": 2604,
"s": 2535,
"text": "Encode a JSON Object - Using Map − Encoding by preserving the order."
},
{
"code": null,
"e": 2673,
"s": 2604,
"text": "Encode a JSON Object - Using Map − Encoding by preserving the order."
},
{
"code": null,
"e": 2770,
"s": 2673,
"text": "Encode a JSON Object - Using Map and Streaming − Encoding by preserving the order and to stream."
},
{
"code": null,
"e": 2867,
"s": 2770,
"text": "Encode a JSON Object - Using Map and Streaming − Encoding by preserving the order and to stream."
},
{
"code": null,
"e": 2917,
"s": 2867,
"text": "Following example illustrates the above concepts."
},
{
"code": null,
"e": 4351,
"s": 2917,
"text": "import java.io.IOException;\nimport java.io.StringWriter;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\n\nimport org.json.simple.JSONObject;\nimport org.json.simple.JSONValue;\n\nclass JsonDemo {\n public static void main(String[] args) throws IOException {\n JSONObject obj = new JSONObject();\n String jsonText;\n\n obj.put(\"name\", \"foo\");\n obj.put(\"num\", new Integer(100));\n obj.put(\"balance\", new Double(1000.21));\n obj.put(\"is_vip\", new Boolean(true));\n jsonText = obj.toString();\n\n System.out.println(\"Encode a JSON Object - to String\");\n System.out.print(jsonText);\n\n StringWriter out = new StringWriter();\n obj.writeJSONString(out); \n jsonText = out.toString();\n\n System.out.println(\"\\nEncode a JSON Object - Streaming\"); \n System.out.print(jsonText);\n\n Map obj1 = new LinkedHashMap();\n obj1.put(\"name\", \"foo\");\n obj1.put(\"num\", new Integer(100));\n obj1.put(\"balance\", new Double(1000.21));\n obj1.put(\"is_vip\", new Boolean(true));\n\n jsonText = JSONValue.toJSONString(obj1); \n System.out.println(\"\\nEncode a JSON Object - Preserving Order\");\n System.out.print(jsonText);\n\n out = new StringWriter();\n JSONValue.writeJSONString(obj1, out); \n jsonText = out.toString();\n System.out.println(\"\\nEncode a JSON Object - Preserving Order and Stream\");\n System.out.print(jsonText);\n }\n}"
},
{
"code": null,
"e": 4737,
"s": 4351,
"text": "Encode a JSON Object - to String\n{\"balance\":1000.21,\"is_vip\":true,\"num\":100,\"name\":\"foo\"}\nEncode a JSON Object - Streaming\n{\"balance\":1000.21,\"is_vip\":true,\"num\":100,\"name\":\"foo\"}\nEncode a JSON Object - Preserving Order\n{\"name\":\"foo\",\"num\":100,\"balance\":1000.21,\"is_vip\":true}\nEncode a JSON Object - Preserving Order and Stream\n{\"name\":\"foo\",\"num\":100,\"balance\":1000.21,\"is_vip\":true}\n"
},
{
"code": null,
"e": 4770,
"s": 4737,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4787,
"s": 4770,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4820,
"s": 4787,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4837,
"s": 4820,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4870,
"s": 4837,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4887,
"s": 4870,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4922,
"s": 4887,
"text": "\n 23 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4939,
"s": 4922,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4970,
"s": 4939,
"text": "\n 9 Lectures \n 48 mins\n"
},
{
"code": null,
"e": 4983,
"s": 4970,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5018,
"s": 4983,
"text": "\n 18 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5041,
"s": 5018,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 5048,
"s": 5041,
"text": " Print"
},
{
"code": null,
"e": 5059,
"s": 5048,
"text": " Add Notes"
}
] |
How to convert hex string to byte Array in Java?
|
We can convert a hex string to byte array in Java by first converting the hexadecimal number to integer value using the parseInt() method of the Integer class in java. This will return an integer value which will be the decimal conversion of hexadecimal value. We will then use the toByteArray() method of BigInteger class that will return a byte array.
Live Demo
import java.math.BigInteger;
public class Demo {
public static void main(String args[]) {
String str = "1D08A";
int it = Integer.parseInt(str, 16);
System.out.println("Hexadecimal String " + str);
BigInteger bigInt = BigInteger.valueOf(it);
byte[] bytearray = (bigInt.toByteArray());
System.out.print("Byte Array : ");
for(int i = 0; i < bytearray.length; i++)
System.out.print(bytearray[i]+ "\t");
}
}
Hexadecimal String 1D08A
Byte Array : 1 -48 -118
|
[
{
"code": null,
"e": 1416,
"s": 1062,
"text": "We can convert a hex string to byte array in Java by first converting the hexadecimal number to integer value using the parseInt() method of the Integer class in java. This will return an integer value which will be the decimal conversion of hexadecimal value. We will then use the toByteArray() method of BigInteger class that will return a byte array."
},
{
"code": null,
"e": 1427,
"s": 1416,
"text": " Live Demo"
},
{
"code": null,
"e": 1884,
"s": 1427,
"text": "import java.math.BigInteger;\npublic class Demo {\n public static void main(String args[]) {\n String str = \"1D08A\";\n int it = Integer.parseInt(str, 16);\n System.out.println(\"Hexadecimal String \" + str);\n BigInteger bigInt = BigInteger.valueOf(it);\n byte[] bytearray = (bigInt.toByteArray());\n System.out.print(\"Byte Array : \");\n for(int i = 0; i < bytearray.length; i++)\n System.out.print(bytearray[i]+ \"\\t\");\n }\n}"
},
{
"code": null,
"e": 1933,
"s": 1884,
"text": "Hexadecimal String 1D08A\nByte Array : 1 -48 -118"
}
] |
Java BeanUtils - Nested Property Access
|
You can access the value of nested property of the bean by concatenating the property names of the access path by using "." separators.
You can get and set the values of Nested property by using the below methods:
PropertyUtils.getNestedProperty(Object, String)
PropertyUtils.getNestedProperty(Object, String)
PropertyUtils.setNestedProperty(Object, String, Object)
PropertyUtils.setNestedProperty(Object, String, Object)
Parameters:
Object: It is a bean whose property to be obtained or modified.
Object: It is a bean whose property to be obtained or modified.
String: It is a name of the nested property to be obtained or modified.
String: It is a name of the nested property to be obtained or modified.
In this example, you'll see how to get and set the values of nested property. We will be creating three classes; SubBean, AppLayer1Bean for beans and BeanUtilsDemo as a main program to run.
import org.apache.commons.beanutils.PropertyUtils;
public class BeanUtilsDemo {
public static void main(String args[]){
try{
// create the bean
AppLayer1Bean nested = new AppLayer1Bean();
// set a SubBean which is part of another bean
SubBean sb = new SubBean();
sb.setStringProperty("Hello World from SubBean");
nested.setSubBean(sb);
// accessing and setting nested properties
PropertyUtils.setNestedProperty(
nested, "subBean.stringProperty",
"Hello World from SubBean, set via Nested Property Access");
System.out.println(
PropertyUtils.getNestedProperty(nested, "subBean.stringProperty"));
}
catch(Exception e){
System.out.println(e);
}
}
}
Now we will create another class called SubBean.java as shown below:
public class SubBean {
private int intProperty;
private String stringProperty;
public void setIntProperty(int intProperty) {
this.intProperty = intProperty;
}
public int getIntProperty() {
return this.intProperty;
}
public void setStringProperty(String stringProperty) {
this.stringProperty = stringProperty;
}
public String getStringProperty() {
return this.stringProperty;
}
}
Create the one more class AppLayer1Bean.java along with the below code:
public class AppLayer1Bean {
private SubBean subBean;
public void setSubBean(SubBean subBean) {
this.subBean = subBean;
}
public SubBean getSubBean(){
return this.subBean;
}
}
Let's carry out the following steps to see how above code works:
Save the above first code as BeanUtilsDemo.java.
Save the above first code as BeanUtilsDemo.java.
Now execute the code using Run option or Ctrl+f11 and output as below gets displayed.
Now execute the code using Run option or Ctrl+f11 and output as below gets displayed.
The following methods are provided by the PropertyUtils class, which accepts any arbitrary combinations of simple, indexed and mapped property access to get and set the value of the property of the specified bean.
PropertyUtils.getProperty(Object, String)
PropertyUtils.getProperty(Object, String)
PropertyUtils.setProperty(Object, String, Object)
PropertyUtils.setProperty(Object, String, Object)
Parameters:
Object: It is a bean whose property to be obtained or modified.
Object: It is a bean whose property to be obtained or modified.
String: It is a name of the indexed and/or nested property to be obtained or modified.
String: It is a name of the indexed and/or nested property to be obtained or modified.
The following simple program illustrates the use of getProperty and setProperty methods:
import org.apache.commons.beanutils.PropertyUtils;
public class PropertyUtilsTest {
public static void main(String args[]){
try{
Tv Color = new Tv();
PropertyUtils.setProperty(Color, "color", "Black");
String value = (String) PropertyUtils.getProperty(Color, "color");
System.out.println("The color value of Tv is: " + value);
}
catch(Exception ex){
ex.printStackTrace();
}
}
public static class Tv{
private String color;
public String getColor(){
return color;
}
public void setColor(String color){
this.color = color;
}
}
}
Run the code as specified in the above example and you would get the below output:
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": 2292,
"s": 2156,
"text": "You can access the value of nested property of the bean by concatenating the property names of the access path by using \".\" separators."
},
{
"code": null,
"e": 2370,
"s": 2292,
"text": "You can get and set the values of Nested property by using the below methods:"
},
{
"code": null,
"e": 2418,
"s": 2370,
"text": "PropertyUtils.getNestedProperty(Object, String)"
},
{
"code": null,
"e": 2466,
"s": 2418,
"text": "PropertyUtils.getNestedProperty(Object, String)"
},
{
"code": null,
"e": 2522,
"s": 2466,
"text": "PropertyUtils.setNestedProperty(Object, String, Object)"
},
{
"code": null,
"e": 2578,
"s": 2522,
"text": "PropertyUtils.setNestedProperty(Object, String, Object)"
},
{
"code": null,
"e": 2590,
"s": 2578,
"text": "Parameters:"
},
{
"code": null,
"e": 2654,
"s": 2590,
"text": "Object: It is a bean whose property to be obtained or modified."
},
{
"code": null,
"e": 2718,
"s": 2654,
"text": "Object: It is a bean whose property to be obtained or modified."
},
{
"code": null,
"e": 2790,
"s": 2718,
"text": "String: It is a name of the nested property to be obtained or modified."
},
{
"code": null,
"e": 2862,
"s": 2790,
"text": "String: It is a name of the nested property to be obtained or modified."
},
{
"code": null,
"e": 3052,
"s": 2862,
"text": "In this example, you'll see how to get and set the values of nested property. We will be creating three classes; SubBean, AppLayer1Bean for beans and BeanUtilsDemo as a main program to run."
},
{
"code": null,
"e": 3914,
"s": 3052,
"text": "import org.apache.commons.beanutils.PropertyUtils;\n\npublic class BeanUtilsDemo {\n public static void main(String args[]){\n try{\n // create the bean\n AppLayer1Bean nested = new AppLayer1Bean();\n // set a SubBean which is part of another bean\n SubBean sb = new SubBean();\n sb.setStringProperty(\"Hello World from SubBean\");\n nested.setSubBean(sb);\n\t\t\n // accessing and setting nested properties\n PropertyUtils.setNestedProperty(\n nested, \"subBean.stringProperty\",\n \"Hello World from SubBean, set via Nested Property Access\");\n\t\t\t\n System.out.println(\n PropertyUtils.getNestedProperty(nested, \"subBean.stringProperty\"));\n }\n catch(Exception e){\n System.out.println(e);\n }\n }\n}"
},
{
"code": null,
"e": 3983,
"s": 3914,
"text": "Now we will create another class called SubBean.java as shown below:"
},
{
"code": null,
"e": 4445,
"s": 3983,
"text": "public class SubBean {\n private int intProperty;\n private String stringProperty;\n\t\n public void setIntProperty(int intProperty) { \n this.intProperty = intProperty; \n }\n public int getIntProperty() {\n return this.intProperty; \n }\n\t\n public void setStringProperty(String stringProperty) { \n this.stringProperty = stringProperty; \n }\n public String getStringProperty() { \n return this.stringProperty; \n }\n}"
},
{
"code": null,
"e": 4517,
"s": 4445,
"text": "Create the one more class AppLayer1Bean.java along with the below code:"
},
{
"code": null,
"e": 4731,
"s": 4517,
"text": "public class AppLayer1Bean {\n private SubBean subBean;\n\n public void setSubBean(SubBean subBean) {\n this.subBean = subBean;\n }\n public SubBean getSubBean(){\n return this.subBean;\n }\t\n}"
},
{
"code": null,
"e": 4796,
"s": 4731,
"text": "Let's carry out the following steps to see how above code works:"
},
{
"code": null,
"e": 4845,
"s": 4796,
"text": "Save the above first code as BeanUtilsDemo.java."
},
{
"code": null,
"e": 4894,
"s": 4845,
"text": "Save the above first code as BeanUtilsDemo.java."
},
{
"code": null,
"e": 4980,
"s": 4894,
"text": "Now execute the code using Run option or Ctrl+f11 and output as below gets displayed."
},
{
"code": null,
"e": 5066,
"s": 4980,
"text": "Now execute the code using Run option or Ctrl+f11 and output as below gets displayed."
},
{
"code": null,
"e": 5280,
"s": 5066,
"text": "The following methods are provided by the PropertyUtils class, which accepts any arbitrary combinations of simple, indexed and mapped property access to get and set the value of the property of the specified bean."
},
{
"code": null,
"e": 5322,
"s": 5280,
"text": "PropertyUtils.getProperty(Object, String)"
},
{
"code": null,
"e": 5364,
"s": 5322,
"text": "PropertyUtils.getProperty(Object, String)"
},
{
"code": null,
"e": 5414,
"s": 5364,
"text": "PropertyUtils.setProperty(Object, String, Object)"
},
{
"code": null,
"e": 5464,
"s": 5414,
"text": "PropertyUtils.setProperty(Object, String, Object)"
},
{
"code": null,
"e": 5476,
"s": 5464,
"text": "Parameters:"
},
{
"code": null,
"e": 5540,
"s": 5476,
"text": "Object: It is a bean whose property to be obtained or modified."
},
{
"code": null,
"e": 5604,
"s": 5540,
"text": "Object: It is a bean whose property to be obtained or modified."
},
{
"code": null,
"e": 5691,
"s": 5604,
"text": "String: It is a name of the indexed and/or nested property to be obtained or modified."
},
{
"code": null,
"e": 5778,
"s": 5691,
"text": "String: It is a name of the indexed and/or nested property to be obtained or modified."
},
{
"code": null,
"e": 5867,
"s": 5778,
"text": "The following simple program illustrates the use of getProperty and setProperty methods:"
},
{
"code": null,
"e": 6573,
"s": 5867,
"text": "import org.apache.commons.beanutils.PropertyUtils;\n\npublic class PropertyUtilsTest {\n public static void main(String args[]){\n try{\n Tv Color = new Tv();\n PropertyUtils.setProperty(Color, \"color\", \"Black\");\n String value = (String) PropertyUtils.getProperty(Color, \"color\");\n System.out.println(\"The color value of Tv is: \" + value);\n }\n catch(Exception ex){\n ex.printStackTrace();\n }\n }\n public static class Tv{\n private String color;\n\t \n public String getColor(){\n return color;\n }\n public void setColor(String color){\n this.color = color;\n }\n }\n}"
},
{
"code": null,
"e": 6656,
"s": 6573,
"text": "Run the code as specified in the above example and you would get the below output:"
},
{
"code": null,
"e": 6689,
"s": 6656,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6705,
"s": 6689,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6738,
"s": 6705,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6754,
"s": 6738,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6789,
"s": 6754,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6803,
"s": 6789,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6837,
"s": 6803,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6851,
"s": 6837,
"text": " Tushar Kale"
},
{
"code": null,
"e": 6888,
"s": 6851,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6903,
"s": 6888,
"text": " Monica Mittal"
},
{
"code": null,
"e": 6936,
"s": 6903,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6955,
"s": 6936,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6962,
"s": 6955,
"text": " Print"
},
{
"code": null,
"e": 6973,
"s": 6962,
"text": " Add Notes"
}
] |
Python Comparison Operators Example
|
These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
Assume variable a holds 10 and variable b holds 20, then −
#!/usr/bin/python
a = 21
b = 10
c = 0
if ( a == b ):
print "Line 1 - a is equal to b"
else:
print "Line 1 - a is not equal to b"
if ( a != b ):
print "Line 2 - a is not equal to b"
else:
print "Line 2 - a is equal to b"
if ( a <> b ):
print "Line 3 - a is not equal to b"
else:
print "Line 3 - a is equal to b"
if ( a < b ):
print "Line 4 - a is less than b"
else:
print "Line 4 - a is not less than b"
if ( a > b ):
print "Line 5 - a is greater than b"
else:
print "Line 5 - a is not greater than b"
a = 5;
b = 20;
if ( a <= b ):
print "Line 6 - a is either less than or equal to b"
else:
print "Line 6 - a is neither less than nor equal to b"
if ( b >= a ):
print "Line 7 - b is either greater than or equal to b"
else:
print "Line 7 - b is neither greater than nor equal to b"
When you execute the above program it produces the following result −
Line 1 - a is not equal to b
Line 2 - a is not equal to b
Line 3 - a is not equal to b
Line 4 - a is not less than b
Line 5 - a is greater than b
Line 6 - a is either less than or equal to b
Line 7 - b is either greater than or equal to b
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2382,
"s": 2244,
"text": "These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators."
},
{
"code": null,
"e": 2441,
"s": 2382,
"text": "Assume variable a holds 10 and variable b holds 20, then −"
},
{
"code": null,
"e": 2500,
"s": 2441,
"text": "Assume variable a holds 10 and variable b holds 20, then −"
},
{
"code": null,
"e": 3335,
"s": 2500,
"text": "#!/usr/bin/python\n\na = 21\nb = 10\nc = 0\n\nif ( a == b ):\n print \"Line 1 - a is equal to b\"\nelse:\n print \"Line 1 - a is not equal to b\"\n\nif ( a != b ):\n print \"Line 2 - a is not equal to b\"\nelse:\n print \"Line 2 - a is equal to b\"\n\nif ( a <> b ):\n print \"Line 3 - a is not equal to b\"\nelse:\n print \"Line 3 - a is equal to b\"\n\nif ( a < b ):\n print \"Line 4 - a is less than b\" \nelse:\n print \"Line 4 - a is not less than b\"\n\nif ( a > b ):\n print \"Line 5 - a is greater than b\"\nelse:\n print \"Line 5 - a is not greater than b\"\n\na = 5;\nb = 20;\nif ( a <= b ):\n print \"Line 6 - a is either less than or equal to b\"\nelse:\n print \"Line 6 - a is neither less than nor equal to b\"\n\nif ( b >= a ):\n print \"Line 7 - b is either greater than or equal to b\"\nelse:\n print \"Line 7 - b is neither greater than nor equal to b\""
},
{
"code": null,
"e": 3405,
"s": 3335,
"text": "When you execute the above program it produces the following result −"
},
{
"code": null,
"e": 3645,
"s": 3405,
"text": "Line 1 - a is not equal to b\nLine 2 - a is not equal to b\nLine 3 - a is not equal to b\nLine 4 - a is not less than b\nLine 5 - a is greater than b\nLine 6 - a is either less than or equal to b\nLine 7 - b is either greater than or equal to b\n"
},
{
"code": null,
"e": 3682,
"s": 3645,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3698,
"s": 3682,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3731,
"s": 3698,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3750,
"s": 3731,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3785,
"s": 3750,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3807,
"s": 3785,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3841,
"s": 3807,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3869,
"s": 3841,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3904,
"s": 3869,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3918,
"s": 3904,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3951,
"s": 3918,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3968,
"s": 3951,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3975,
"s": 3968,
"text": " Print"
},
{
"code": null,
"e": 3986,
"s": 3975,
"text": " Add Notes"
}
] |
Android - Push Notification
|
A notification is a message you can display to the user outside of your application's normal UI. You can create your own notifications in android very easily.
Android provides NotificationManager class for this purpose. In order to use this class, you need to instantiate an object of this class by requesting the android system through getSystemService() method. Its syntax is given below −
NotificationManager NM;
NM=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
After that you will create Notification through Notification class and specify its attributes such as icon,title and time e.t.c. Its syntax is given below −
Notification notify = new Notification(android.R.drawable.stat_notify_more,title,System.currentTimeMillis());
The next thing you need to do is to create a PendingIntent by passing context and intent as a parameter. By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified as if the other application was yourself.
PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(),0);
The last thing you need to do is to call setLatestEventInfo method of the Notification class and pass the pending intent along with notification subject and body details. Its syntax is given below. And then finally call the notify method of the NotificationManager class.
notify.setLatestEventInfo(getApplicationContext(), subject, body,pending);
NM.notify(0, notify);
Apart from the notify method, there are other methods available in the NotificationManager class. They are listed below −
cancel(int id)
This method cancel a previously shown notification.
cancel(String tag, int id)
This method also cancel a previously shown notification.
cancelAll()
This method cancel all previously shown notifications.
notify(int id, Notification notification)
This method post a notification to be shown in the status bar.
notify(String tag, int id, Notification notification)
This method also Post a notification to be shown in the status bar.
The below example demonstrates the use of NotificationManager class. It crates a basic application that allows you to create a notification.
To experiment with this example, you need to run this on an actual device or in an emulator.
Here is the content of MainActivity.java.
package com.example.sairamkrishna.myapplication;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
EditText ed1,ed2,ed3;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
Button b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String tittle=ed1.getText().toString().trim();
String subject=ed2.getText().toString().trim();
String body=ed3.getText().toString().trim();
NotificationManager notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notify=new Notification.Builder
(getApplicationContext()).setContentTitle(tittle).setContentText(body).
setContentTitle(subject).setSmallIcon(R.drawable.abc).build();
notify.flags |= Notification.FLAG_AUTO_CANCEL;
notif.notify(0, notify);
}
});
}
}
Here is the content of 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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notification"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/textView2"
android:layout_alignLeft="@+id/textView2"
android:layout_alignStart="@+id/textView2"
android:layout_marginTop="52dp"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:hint="Name" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:hint="Subject"
android:layout_below="@+id/editText"
android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editText3"
android:hint="Body"
android:layout_below="@+id/editText2"
android:layout_alignLeft="@+id/editText2"
android:layout_alignStart="@+id/editText2"
android:layout_alignRight="@+id/editText2"
android:layout_alignEnd="@+id/editText2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notification"
android:id="@+id/button"
android:layout_marginTop="77dp"
android:layout_below="@+id/editText3"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView" />
</RelativeLayout>
Here is the content of AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<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 our application. To run the app from Android studio, open one of your project's activity files and click Run icon from the tool bar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application.
Now fill in the field with the title , subject and the body. This has been shown below in the figure −
Now click on the notify button and you will see a notification in the top notification bar. It has been shown below −
Now scroll down the notification bar and see the notification. This has been shown below in the figure −
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3766,
"s": 3607,
"text": "A notification is a message you can display to the user outside of your application's normal UI. You can create your own notifications in android very easily."
},
{
"code": null,
"e": 3999,
"s": 3766,
"text": "Android provides NotificationManager class for this purpose. In order to use this class, you need to instantiate an object of this class by requesting the android system through getSystemService() method. Its syntax is given below −"
},
{
"code": null,
"e": 4096,
"s": 3999,
"text": "NotificationManager NM;\nNM=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);\n"
},
{
"code": null,
"e": 4253,
"s": 4096,
"text": "After that you will create Notification through Notification class and specify its attributes such as icon,title and time e.t.c. Its syntax is given below −"
},
{
"code": null,
"e": 4364,
"s": 4253,
"text": "Notification notify = new Notification(android.R.drawable.stat_notify_more,title,System.currentTimeMillis());\n"
},
{
"code": null,
"e": 4635,
"s": 4364,
"text": "The next thing you need to do is to create a PendingIntent by passing context and intent as a parameter. By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified as if the other application was yourself."
},
{
"code": null,
"e": 4731,
"s": 4635,
"text": "PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(),0);\n"
},
{
"code": null,
"e": 5003,
"s": 4731,
"text": "The last thing you need to do is to call setLatestEventInfo method of the Notification class and pass the pending intent along with notification subject and body details. Its syntax is given below. And then finally call the notify method of the NotificationManager class."
},
{
"code": null,
"e": 5103,
"s": 5003,
"text": "notify.setLatestEventInfo(getApplicationContext(), subject, body,pending);\nNM.notify(0, notify);\t\t\n"
},
{
"code": null,
"e": 5225,
"s": 5103,
"text": "Apart from the notify method, there are other methods available in the NotificationManager class. They are listed below −"
},
{
"code": null,
"e": 5240,
"s": 5225,
"text": "cancel(int id)"
},
{
"code": null,
"e": 5292,
"s": 5240,
"text": "This method cancel a previously shown notification."
},
{
"code": null,
"e": 5319,
"s": 5292,
"text": "cancel(String tag, int id)"
},
{
"code": null,
"e": 5376,
"s": 5319,
"text": "This method also cancel a previously shown notification."
},
{
"code": null,
"e": 5388,
"s": 5376,
"text": "cancelAll()"
},
{
"code": null,
"e": 5443,
"s": 5388,
"text": "This method cancel all previously shown notifications."
},
{
"code": null,
"e": 5485,
"s": 5443,
"text": "notify(int id, Notification notification)"
},
{
"code": null,
"e": 5548,
"s": 5485,
"text": "This method post a notification to be shown in the status bar."
},
{
"code": null,
"e": 5602,
"s": 5548,
"text": "notify(String tag, int id, Notification notification)"
},
{
"code": null,
"e": 5670,
"s": 5602,
"text": "This method also Post a notification to be shown in the status bar."
},
{
"code": null,
"e": 5811,
"s": 5670,
"text": "The below example demonstrates the use of NotificationManager class. It crates a basic application that allows you to create a notification."
},
{
"code": null,
"e": 5904,
"s": 5811,
"text": "To experiment with this example, you need to run this on an actual device or in an emulator."
},
{
"code": null,
"e": 5946,
"s": 5904,
"text": "Here is the content of MainActivity.java."
},
{
"code": null,
"e": 7460,
"s": 5946,
"text": "package com.example.sairamkrishna.myapplication;\n\nimport android.app.Notification;\nimport android.app.NotificationManager;\n\nimport android.content.Context;\nimport android.support.v7.app.ActionBarActivity;\nimport android.os.Bundle;\nimport android.view.View;\n\nimport android.widget.Button;\nimport android.widget.EditText;\n\npublic class MainActivity extends ActionBarActivity {\n EditText ed1,ed2,ed3;\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n ed1=(EditText)findViewById(R.id.editText);\n ed2=(EditText)findViewById(R.id.editText2);\n ed3=(EditText)findViewById(R.id.editText3);\n Button b1=(Button)findViewById(R.id.button);\n\n b1.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String tittle=ed1.getText().toString().trim();\n String subject=ed2.getText().toString().trim();\n String body=ed3.getText().toString().trim();\n\n NotificationManager notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);\n Notification notify=new Notification.Builder\n (getApplicationContext()).setContentTitle(tittle).setContentText(body).\n setContentTitle(subject).setSmallIcon(R.drawable.abc).build();\n \n notify.flags |= Notification.FLAG_AUTO_CANCEL;\n notif.notify(0, notify);\n }\n });\n }\n}"
},
{
"code": null,
"e": 7501,
"s": 7460,
"text": "Here is the content of activity_main.xml"
},
{
"code": null,
"e": 10304,
"s": 7501,
"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\" android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\" tools:context=\".MainActivity\">\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Notification\"\n android:id=\"@+id/textView\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:textSize=\"30dp\" />\n .\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials Point\"\n android:id=\"@+id/textView2\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\"\n android:textSize=\"35dp\"\n android:textColor=\"#ff16ff01\" />\n \n <EditText\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/editText\"\n android:layout_below=\"@+id/textView2\"\n android:layout_alignLeft=\"@+id/textView2\"\n android:layout_alignStart=\"@+id/textView2\"\n android:layout_marginTop=\"52dp\"\n android:layout_alignRight=\"@+id/textView2\"\n android:layout_alignEnd=\"@+id/textView2\"\n android:hint=\"Name\" />\n \n <EditText\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/editText2\"\n android:hint=\"Subject\"\n android:layout_below=\"@+id/editText\"\n android:layout_alignLeft=\"@+id/editText\"\n android:layout_alignStart=\"@+id/editText\"\n android:layout_alignRight=\"@+id/editText\"\n android:layout_alignEnd=\"@+id/editText\" />\n \n <EditText\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:inputType=\"textPersonName\"\n android:ems=\"10\"\n android:id=\"@+id/editText3\"\n android:hint=\"Body\"\n android:layout_below=\"@+id/editText2\"\n android:layout_alignLeft=\"@+id/editText2\"\n android:layout_alignStart=\"@+id/editText2\"\n android:layout_alignRight=\"@+id/editText2\"\n android:layout_alignEnd=\"@+id/editText2\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Notification\"\n android:id=\"@+id/button\"\n android:layout_marginTop=\"77dp\"\n android:layout_below=\"@+id/editText3\"\n android:layout_alignRight=\"@+id/textView\"\n android:layout_alignEnd=\"@+id/textView\" />\n\n</RelativeLayout>"
},
{
"code": null,
"e": 10348,
"s": 10304,
"text": "Here is the content of AndroidManifest.xml."
},
{
"code": null,
"e": 11053,
"s": 10348,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\" >\n \n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\".MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 11351,
"s": 11053,
"text": "Let's try to run our application. To run the app from Android studio, open one of your project's activity files and click Run icon from the tool bar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application."
},
{
"code": null,
"e": 11454,
"s": 11351,
"text": "Now fill in the field with the title , subject and the body. This has been shown below in the figure −"
},
{
"code": null,
"e": 11572,
"s": 11454,
"text": "Now click on the notify button and you will see a notification in the top notification bar. It has been shown below −"
},
{
"code": null,
"e": 11677,
"s": 11572,
"text": "Now scroll down the notification bar and see the notification. This has been shown below in the figure −"
},
{
"code": null,
"e": 11712,
"s": 11677,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 11724,
"s": 11712,
"text": " Aditya Dua"
},
{
"code": null,
"e": 11759,
"s": 11724,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 11773,
"s": 11759,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 11805,
"s": 11773,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 11822,
"s": 11805,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 11857,
"s": 11822,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11874,
"s": 11857,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 11909,
"s": 11874,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11926,
"s": 11909,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 11959,
"s": 11926,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 11976,
"s": 11959,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 11983,
"s": 11976,
"text": " Print"
},
{
"code": null,
"e": 11994,
"s": 11983,
"text": " Add Notes"
}
] |
Header files “stdio.h” and “stdlib.h” in C
|
The header file stdio.h stands for Standard Input Output. It has the information related to input/output functions.
Here is the table that displays some of the functions in stdio.h in C language,
Here is an example of stdio.h in C language,
Live Demo
#include<stdio.h>
int main () {
char val;
printf("Enter the character: \n");
val = getc(stdin);
printf("Character entered: ");
putc(val, stdout);
return(0);
}
Here is the output
Enter the character: s
Character entered: s
The header file stdlib.h stands for Standard Library. It has the information of memory allocation/freeing functions.
Here is the table that displays some of the functions in stdlib.h in C language,
Here is an example of stdlib.h in C language,
Live Demo
#include <stdio.h>
#include<stdlib.h>
int main() {
char str1[20] = "53875";
char str2[20] = "367587938";
char str3[20] = "53875.8843";
long int a = atol(str1);
printf("String to long int : %d\n", a);
long long int b = atoll(str2);
printf("String to long long int : %d\n", b);
double c = atof(str3);
printf("String to long int : %f\n", c);
printf("The first random value : %d\n", rand());
printf("The second random value : %d", rand());
return 0;
}
Here is the output
String to long int : 53875
String to long long int : 367587938
String to long int : 53875.884300
The first random value : 1804289383
The second random value : 846930886
|
[
{
"code": null,
"e": 1178,
"s": 1062,
"text": "The header file stdio.h stands for Standard Input Output. It has the information related to input/output functions."
},
{
"code": null,
"e": 1258,
"s": 1178,
"text": "Here is the table that displays some of the functions in stdio.h in C language,"
},
{
"code": null,
"e": 1303,
"s": 1258,
"text": "Here is an example of stdio.h in C language,"
},
{
"code": null,
"e": 1314,
"s": 1303,
"text": " Live Demo"
},
{
"code": null,
"e": 1494,
"s": 1314,
"text": "#include<stdio.h>\n\nint main () {\n char val;\n\n printf(\"Enter the character: \\n\");\n val = getc(stdin);\n printf(\"Character entered: \");\n putc(val, stdout);\n\n return(0);\n}"
},
{
"code": null,
"e": 1513,
"s": 1494,
"text": "Here is the output"
},
{
"code": null,
"e": 1557,
"s": 1513,
"text": "Enter the character: s\nCharacter entered: s"
},
{
"code": null,
"e": 1674,
"s": 1557,
"text": "The header file stdlib.h stands for Standard Library. It has the information of memory allocation/freeing functions."
},
{
"code": null,
"e": 1755,
"s": 1674,
"text": "Here is the table that displays some of the functions in stdlib.h in C language,"
},
{
"code": null,
"e": 1801,
"s": 1755,
"text": "Here is an example of stdlib.h in C language,"
},
{
"code": null,
"e": 1812,
"s": 1801,
"text": " Live Demo"
},
{
"code": null,
"e": 2301,
"s": 1812,
"text": "#include <stdio.h>\n#include<stdlib.h>\n\nint main() {\n char str1[20] = \"53875\";\n char str2[20] = \"367587938\";\n char str3[20] = \"53875.8843\";\n\n long int a = atol(str1);\n printf(\"String to long int : %d\\n\", a);\n\n long long int b = atoll(str2);\n printf(\"String to long long int : %d\\n\", b);\n\n double c = atof(str3);\n printf(\"String to long int : %f\\n\", c);\n printf(\"The first random value : %d\\n\", rand());\n printf(\"The second random value : %d\", rand());\n\n return 0;\n}"
},
{
"code": null,
"e": 2320,
"s": 2301,
"text": "Here is the output"
},
{
"code": null,
"e": 2489,
"s": 2320,
"text": "String to long int : 53875\nString to long long int : 367587938\nString to long int : 53875.884300\nThe first random value : 1804289383\nThe second random value : 846930886"
}
] |
Speed up Code executions with help of Pragma in C/C++
|
21 Sep, 2021
The primary goal of a compiler is to reduce the cost of compilation and to make debugging produce the expected results. Not all optimizations are controlled directly by a flag, sometimes we need to explicitly declare flags to produce optimizations. By default optimizations are suppressed. To use suppressed optimizations we will use pragmas.
Example for unoptimized program: Let us consider an example to calculate Prime Numbers up to 10000000.
Below is the code with no optimization:
C++
// C++ program to calculate the Prime// Numbers upto 10000000 using Sieve// of Eratosthenes with NO optimization #include <cmath>#include <iostream>#include <vector>#define N 10000005using namespace std; // Boolean array for Prime Numbervector<bool> prime(N, true); // Sieve implemented to find Prime// Numbervoid sieveOfEratosthenes(){ for (int i = 2; i <= sqrt(N); ++i) { if (prime[i]) { for (int j = i * i; j <= N; j += i) { prime[j] = false; } } }} // Driver Codeint main(){ // Initialise clock to calculate // time required to execute without // optimization clock_t start, end; // Start clock start = clock(); // Function call to find Prime Numbers sieveOfEratosthenes(); // End clock end = clock(); // Calculate the time difference double time_taken = double(end - start) / double(CLOCKS_PER_SEC); // Print the Calculated execution time cout << "Execution time: " << time_taken << " secs"; return 0;}
Execution time: 0.592183 secs
Following are the Optimization:
1. O1: Optimizing compilation at O1 includes more time and memory to break down larger functions. The compiler makes an attempt to reduce both code and execution time. At O1 hardly any optimizations produce great results, but O1 is a setback for an attempt for better optimizations.
Below is the implementation of previous program with O1 optimization:
C++
// C++ program to calculate the Prime// Numbers upto 10000000 using Sieve// of Eratosthenes with O1 optimization // To see the working of controlled// optimization "O1"#pragma GCC optimize("O1") #include <cmath>#include <iostream>#include <vector>#define N 10000005using namespace std; // Boolean array for Prime Numbervector<bool> prime(N, true); // Sieve implemented to find Prime// Numbervoid sieveOfEratosthenes(){ for (int i = 2; i <= sqrt(N); ++i) { if (prime[i]) { for (int j = i * i; j <= N; j += i) { prime[j] = false; } } }} // Driver Codeint main(){ // Initialise clock to calculate // time required to execute without // optimization clock_t start, end; // Start clock start = clock(); // Function call to find Prime Numbers sieveOfEratosthenes(); // End clock end = clock(); // Calculate the time difference double time_taken = double(end - start) / double(CLOCKS_PER_SEC); // Print the Calculated execution time cout << "Execution time: " << time_taken << " secs."; return 0;}
Execution time: 0.384945 secs.
2. O2: Optimizing compilation at O2 optimize to a greater extent. As compared to O1, this option increases both compilation time and the performance of the generated code. O2 turns on all optimization flags specified by O1.
Below is the implementation of previous program with O2 optimization:
C++
// C++ program to calculate the Prime// Numbers upto 10000000 using Sieve// of Eratosthenes with O2 optimization // To see the working of controlled// optimization "O2"#pragma GCC optimize("O2") #include <cmath>#include <iostream>#include <vector>#define N 10000005using namespace std; // Boolean array for Prime Numbervector<bool> prime(N, true); // Sieve implemented to find Prime// Numbervoid sieveOfEratosthenes(){ for (int i = 2; i <= sqrt(N); ++i) { if (prime[i]) { for (int j = i * i; j <= N; j += i) { prime[j] = false; } } }} // Driver Codeint main(){ // Initialise clock to calculate // time required to execute without // optimization clock_t start, end; // Start clock start = clock(); // Function call to find Prime Numbers sieveOfEratosthenes(); // End clock end = clock(); // Calculate the time difference double time_taken = double(end - start) / double(CLOCKS_PER_SEC); // Print the Calculated execution time cout << "Execution time: " << time_taken << " secs."; return 0;}
Execution time: 0.288337 secs.
3. O3: All the optimizations at level O2 are specified by O3 and a list of other flags are also enabled. Few of the flags which are included in O3 are flop-interchange -flop-unroll-jam and -fpeel-loops.
Below is the implementation of previous program with O3 optimization:
C++
// C++ program to calculate the Prime// Numbers upto 10000000 using Sieve// of Eratosthenes with O3 optimization // To see the working of controlled// optimization "O3"#pragma GCC optimize("O3") #include <cmath>#include <iostream>#include <vector>#define N 10000005using namespace std; // Boolean array for Prime Numbervector<bool> prime(N, true); // Sieve implemented to find Prime// Numbervoid sieveOfEratosthenes(){ for (int i = 2; i <= sqrt(N); ++i) { if (prime[i]) { for (int j = i * i; j <= N; j += i) { prime[j] = false; } } }} // Driver Codeint main(){ // Initialise clock to calculate // time required to execute without // optimization clock_t start, end; // Start clock start = clock(); // Function call to find Prime Numbers sieveOfEratosthenes(); // End clock end = clock(); // Calculate the time difference double time_taken = double(end - start) / double(CLOCKS_PER_SEC); // Print the Calculated execution time cout << "Execution time: " << time_taken << " secs."; return 0;}
Execution time: 0.580154 secs.
4. Os: It is optimize for size. Os enables all O2 optimizations except the ones that have increased code size. It also enables -finline-functions, causes the compiler to tune for code size rather than execution speed and performs further optimizations designed to reduce code size.
Below is the implementation of previous program with Os optimization:
C++
// C++ program to calculate the Prime// Numbers upto 10000000 using Sieve// of Eratosthenes with Os optimization // To see the working of controlled// optimization "Os"#pragma GCC optimize("Os") #include <cmath>#include <iostream>#include <vector>#define N 10000005using namespace std; // Boolean array for Prime Numbervector<bool> prime(N, true); // Sieve implemented to find Prime// Numbervoid sieveOfEratosthenes(){ for (int i = 2; i <= sqrt(N); ++i) { if (prime[i]) { for (int j = i * i; j <= N; j += i) { prime[j] = false; } } }} // Driver Codeint main(){ // Initialise clock to calculate // time required to execute without // optimization clock_t start, end; // Start clock start = clock(); // Function call to find Prime Numbers sieveOfEratosthenes(); // End clock end = clock(); // Calculate the time difference double time_taken = double(end - start) / double(CLOCKS_PER_SEC); // Print the Calculated execution time cout << "Execution time: " << time_taken << " secs."; return 0;}
Execution time: 0.317845 secs.
5. Ofast: Ofast enables all O3 optimizations. It also has the number of enabled flags that produce super optimized results. Ofast combines optimizations produced by each of the above O levels. This optimization is usually preferred by a lot of competitive programmers and is hence recommended. In case more than one optimizations are declared the last declared one gets enabled.
Below is the implementation of previous program with Ofast optimization:
C++
// C++ program to calculate the Prime// Numbers upto 10000000 using Sieve// of Eratosthenes with Ofast optimization // To see the working of controlled// optimization "Ofast"#pragma GCC optimize("Ofast") #include <cmath>#include <iostream>#include <vector>#define N 10000005using namespace std; // Boolean array for Prime Numbervector<bool> prime(N, true); // Sieve implemented to find Prime// Numbervoid sieveOfEratosthenes(){ for (int i = 2; i <= sqrt(N); ++i) { if (prime[i]) { for (int j = i * i; j <= N; j += i) { prime[j] = false; } } }} // Driver Codeint main(){ // Initialise clock to calculate // time required to execute without // optimization clock_t start, end; // Start clock start = clock(); // Function call to find Prime Numbers sieveOfEratosthenes(); // End clock end = clock(); // Calculate the time difference double time_taken = double(end - start) / double(CLOCKS_PER_SEC); // Print the Calculated execution time cout << "Execution time: " << time_taken << " secs."; return 0;}
Execution time: 0.303287 secs.
To further achieve optimizations at architecture level we can use targets with pragmas. These optimizations can produce surprising results. However it is recommended to use target with any of the optimizations specified above.
Below is the implementation of previous program with Target:
C++14
// C++ program to calculate the Prime// Numbers upto 10000000 using Sieve// of Eratosthenes with Ofast optimization along with target optimizations // To see the working of controlled// optimization "Ofast"#pragma GCC optimize("Ofast")#pragma GCC target("avx,avx2,fma") #include <cmath>#include <iostream>#include <vector>#define N 10000005using namespace std; // Boolean array for Prime Numbervector<bool> prime(N, true); // Sieve implemented to find Prime// Numbervoid sieveOfEratosthenes(){ for (int i = 2; i <= sqrt(N); ++i) { if (prime[i]) { for (int j = i * i; j <= N; j += i) { prime[j] = false; } } }} // Driver Codeint main(){ // Initialise clock to calculate // time required to execute without // optimization clock_t start, end; // Start clock start = clock(); // Function call to find Prime Numbers sieveOfEratosthenes(); // End clock end = clock(); // Calculate the time difference double time_taken = double(end - start) / double(CLOCKS_PER_SEC); // Print the Calculated execution time cout << "Execution time: " << time_taken << " secs."; return 0;}
Execution time: 0.292147 secs.
executable
nidhi_biet
gabaa406
simmytarika5
optimization-technique
Technical Scripter 2019
C Language
C++
Competitive Programming
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Priority Queue in C++ Standard Template Library (STL)
Set in C++ Standard Template Library (STL)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 398,
"s": 54,
"text": "The primary goal of a compiler is to reduce the cost of compilation and to make debugging produce the expected results. Not all optimizations are controlled directly by a flag, sometimes we need to explicitly declare flags to produce optimizations. By default optimizations are suppressed. To use suppressed optimizations we will use pragmas. "
},
{
"code": null,
"e": 501,
"s": 398,
"text": "Example for unoptimized program: Let us consider an example to calculate Prime Numbers up to 10000000."
},
{
"code": null,
"e": 543,
"s": 501,
"text": "Below is the code with no optimization: "
},
{
"code": null,
"e": 547,
"s": 543,
"text": "C++"
},
{
"code": "// C++ program to calculate the Prime// Numbers upto 10000000 using Sieve// of Eratosthenes with NO optimization #include <cmath>#include <iostream>#include <vector>#define N 10000005using namespace std; // Boolean array for Prime Numbervector<bool> prime(N, true); // Sieve implemented to find Prime// Numbervoid sieveOfEratosthenes(){ for (int i = 2; i <= sqrt(N); ++i) { if (prime[i]) { for (int j = i * i; j <= N; j += i) { prime[j] = false; } } }} // Driver Codeint main(){ // Initialise clock to calculate // time required to execute without // optimization clock_t start, end; // Start clock start = clock(); // Function call to find Prime Numbers sieveOfEratosthenes(); // End clock end = clock(); // Calculate the time difference double time_taken = double(end - start) / double(CLOCKS_PER_SEC); // Print the Calculated execution time cout << \"Execution time: \" << time_taken << \" secs\"; return 0;}",
"e": 1587,
"s": 547,
"text": null
},
{
"code": null,
"e": 1617,
"s": 1587,
"text": "Execution time: 0.592183 secs"
},
{
"code": null,
"e": 1652,
"s": 1619,
"text": "Following are the Optimization: "
},
{
"code": null,
"e": 1935,
"s": 1652,
"text": "1. O1: Optimizing compilation at O1 includes more time and memory to break down larger functions. The compiler makes an attempt to reduce both code and execution time. At O1 hardly any optimizations produce great results, but O1 is a setback for an attempt for better optimizations."
},
{
"code": null,
"e": 2005,
"s": 1935,
"text": "Below is the implementation of previous program with O1 optimization:"
},
{
"code": null,
"e": 2009,
"s": 2005,
"text": "C++"
},
{
"code": "// C++ program to calculate the Prime// Numbers upto 10000000 using Sieve// of Eratosthenes with O1 optimization // To see the working of controlled// optimization \"O1\"#pragma GCC optimize(\"O1\") #include <cmath>#include <iostream>#include <vector>#define N 10000005using namespace std; // Boolean array for Prime Numbervector<bool> prime(N, true); // Sieve implemented to find Prime// Numbervoid sieveOfEratosthenes(){ for (int i = 2; i <= sqrt(N); ++i) { if (prime[i]) { for (int j = i * i; j <= N; j += i) { prime[j] = false; } } }} // Driver Codeint main(){ // Initialise clock to calculate // time required to execute without // optimization clock_t start, end; // Start clock start = clock(); // Function call to find Prime Numbers sieveOfEratosthenes(); // End clock end = clock(); // Calculate the time difference double time_taken = double(end - start) / double(CLOCKS_PER_SEC); // Print the Calculated execution time cout << \"Execution time: \" << time_taken << \" secs.\"; return 0;}",
"e": 3132,
"s": 2009,
"text": null
},
{
"code": null,
"e": 3163,
"s": 3132,
"text": "Execution time: 0.384945 secs."
},
{
"code": null,
"e": 3389,
"s": 3165,
"text": "2. O2: Optimizing compilation at O2 optimize to a greater extent. As compared to O1, this option increases both compilation time and the performance of the generated code. O2 turns on all optimization flags specified by O1."
},
{
"code": null,
"e": 3459,
"s": 3389,
"text": "Below is the implementation of previous program with O2 optimization:"
},
{
"code": null,
"e": 3463,
"s": 3459,
"text": "C++"
},
{
"code": "// C++ program to calculate the Prime// Numbers upto 10000000 using Sieve// of Eratosthenes with O2 optimization // To see the working of controlled// optimization \"O2\"#pragma GCC optimize(\"O2\") #include <cmath>#include <iostream>#include <vector>#define N 10000005using namespace std; // Boolean array for Prime Numbervector<bool> prime(N, true); // Sieve implemented to find Prime// Numbervoid sieveOfEratosthenes(){ for (int i = 2; i <= sqrt(N); ++i) { if (prime[i]) { for (int j = i * i; j <= N; j += i) { prime[j] = false; } } }} // Driver Codeint main(){ // Initialise clock to calculate // time required to execute without // optimization clock_t start, end; // Start clock start = clock(); // Function call to find Prime Numbers sieveOfEratosthenes(); // End clock end = clock(); // Calculate the time difference double time_taken = double(end - start) / double(CLOCKS_PER_SEC); // Print the Calculated execution time cout << \"Execution time: \" << time_taken << \" secs.\"; return 0;}",
"e": 4586,
"s": 3463,
"text": null
},
{
"code": null,
"e": 4617,
"s": 4586,
"text": "Execution time: 0.288337 secs."
},
{
"code": null,
"e": 4822,
"s": 4619,
"text": "3. O3: All the optimizations at level O2 are specified by O3 and a list of other flags are also enabled. Few of the flags which are included in O3 are flop-interchange -flop-unroll-jam and -fpeel-loops."
},
{
"code": null,
"e": 4892,
"s": 4822,
"text": "Below is the implementation of previous program with O3 optimization:"
},
{
"code": null,
"e": 4896,
"s": 4892,
"text": "C++"
},
{
"code": "// C++ program to calculate the Prime// Numbers upto 10000000 using Sieve// of Eratosthenes with O3 optimization // To see the working of controlled// optimization \"O3\"#pragma GCC optimize(\"O3\") #include <cmath>#include <iostream>#include <vector>#define N 10000005using namespace std; // Boolean array for Prime Numbervector<bool> prime(N, true); // Sieve implemented to find Prime// Numbervoid sieveOfEratosthenes(){ for (int i = 2; i <= sqrt(N); ++i) { if (prime[i]) { for (int j = i * i; j <= N; j += i) { prime[j] = false; } } }} // Driver Codeint main(){ // Initialise clock to calculate // time required to execute without // optimization clock_t start, end; // Start clock start = clock(); // Function call to find Prime Numbers sieveOfEratosthenes(); // End clock end = clock(); // Calculate the time difference double time_taken = double(end - start) / double(CLOCKS_PER_SEC); // Print the Calculated execution time cout << \"Execution time: \" << time_taken << \" secs.\"; return 0;}",
"e": 6019,
"s": 4896,
"text": null
},
{
"code": null,
"e": 6050,
"s": 6019,
"text": "Execution time: 0.580154 secs."
},
{
"code": null,
"e": 6334,
"s": 6052,
"text": "4. Os: It is optimize for size. Os enables all O2 optimizations except the ones that have increased code size. It also enables -finline-functions, causes the compiler to tune for code size rather than execution speed and performs further optimizations designed to reduce code size."
},
{
"code": null,
"e": 6404,
"s": 6334,
"text": "Below is the implementation of previous program with Os optimization:"
},
{
"code": null,
"e": 6408,
"s": 6404,
"text": "C++"
},
{
"code": "// C++ program to calculate the Prime// Numbers upto 10000000 using Sieve// of Eratosthenes with Os optimization // To see the working of controlled// optimization \"Os\"#pragma GCC optimize(\"Os\") #include <cmath>#include <iostream>#include <vector>#define N 10000005using namespace std; // Boolean array for Prime Numbervector<bool> prime(N, true); // Sieve implemented to find Prime// Numbervoid sieveOfEratosthenes(){ for (int i = 2; i <= sqrt(N); ++i) { if (prime[i]) { for (int j = i * i; j <= N; j += i) { prime[j] = false; } } }} // Driver Codeint main(){ // Initialise clock to calculate // time required to execute without // optimization clock_t start, end; // Start clock start = clock(); // Function call to find Prime Numbers sieveOfEratosthenes(); // End clock end = clock(); // Calculate the time difference double time_taken = double(end - start) / double(CLOCKS_PER_SEC); // Print the Calculated execution time cout << \"Execution time: \" << time_taken << \" secs.\"; return 0;}",
"e": 7531,
"s": 6408,
"text": null
},
{
"code": null,
"e": 7562,
"s": 7531,
"text": "Execution time: 0.317845 secs."
},
{
"code": null,
"e": 7943,
"s": 7564,
"text": "5. Ofast: Ofast enables all O3 optimizations. It also has the number of enabled flags that produce super optimized results. Ofast combines optimizations produced by each of the above O levels. This optimization is usually preferred by a lot of competitive programmers and is hence recommended. In case more than one optimizations are declared the last declared one gets enabled."
},
{
"code": null,
"e": 8016,
"s": 7943,
"text": "Below is the implementation of previous program with Ofast optimization:"
},
{
"code": null,
"e": 8020,
"s": 8016,
"text": "C++"
},
{
"code": "// C++ program to calculate the Prime// Numbers upto 10000000 using Sieve// of Eratosthenes with Ofast optimization // To see the working of controlled// optimization \"Ofast\"#pragma GCC optimize(\"Ofast\") #include <cmath>#include <iostream>#include <vector>#define N 10000005using namespace std; // Boolean array for Prime Numbervector<bool> prime(N, true); // Sieve implemented to find Prime// Numbervoid sieveOfEratosthenes(){ for (int i = 2; i <= sqrt(N); ++i) { if (prime[i]) { for (int j = i * i; j <= N; j += i) { prime[j] = false; } } }} // Driver Codeint main(){ // Initialise clock to calculate // time required to execute without // optimization clock_t start, end; // Start clock start = clock(); // Function call to find Prime Numbers sieveOfEratosthenes(); // End clock end = clock(); // Calculate the time difference double time_taken = double(end - start) / double(CLOCKS_PER_SEC); // Print the Calculated execution time cout << \"Execution time: \" << time_taken << \" secs.\"; return 0;}",
"e": 9152,
"s": 8020,
"text": null
},
{
"code": null,
"e": 9183,
"s": 9152,
"text": "Execution time: 0.303287 secs."
},
{
"code": null,
"e": 9413,
"s": 9185,
"text": "To further achieve optimizations at architecture level we can use targets with pragmas. These optimizations can produce surprising results. However it is recommended to use target with any of the optimizations specified above. "
},
{
"code": null,
"e": 9475,
"s": 9413,
"text": "Below is the implementation of previous program with Target: "
},
{
"code": null,
"e": 9481,
"s": 9475,
"text": "C++14"
},
{
"code": "// C++ program to calculate the Prime// Numbers upto 10000000 using Sieve// of Eratosthenes with Ofast optimization along with target optimizations // To see the working of controlled// optimization \"Ofast\"#pragma GCC optimize(\"Ofast\")#pragma GCC target(\"avx,avx2,fma\") #include <cmath>#include <iostream>#include <vector>#define N 10000005using namespace std; // Boolean array for Prime Numbervector<bool> prime(N, true); // Sieve implemented to find Prime// Numbervoid sieveOfEratosthenes(){ for (int i = 2; i <= sqrt(N); ++i) { if (prime[i]) { for (int j = i * i; j <= N; j += i) { prime[j] = false; } } }} // Driver Codeint main(){ // Initialise clock to calculate // time required to execute without // optimization clock_t start, end; // Start clock start = clock(); // Function call to find Prime Numbers sieveOfEratosthenes(); // End clock end = clock(); // Calculate the time difference double time_taken = double(end - start) / double(CLOCKS_PER_SEC); // Print the Calculated execution time cout << \"Execution time: \" << time_taken << \" secs.\"; return 0;}",
"e": 10676,
"s": 9481,
"text": null
},
{
"code": null,
"e": 10707,
"s": 10676,
"text": "Execution time: 0.292147 secs."
},
{
"code": null,
"e": 10720,
"s": 10709,
"text": "executable"
},
{
"code": null,
"e": 10731,
"s": 10720,
"text": "nidhi_biet"
},
{
"code": null,
"e": 10740,
"s": 10731,
"text": "gabaa406"
},
{
"code": null,
"e": 10753,
"s": 10740,
"text": "simmytarika5"
},
{
"code": null,
"e": 10776,
"s": 10753,
"text": "optimization-technique"
},
{
"code": null,
"e": 10800,
"s": 10776,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 10811,
"s": 10800,
"text": "C Language"
},
{
"code": null,
"e": 10815,
"s": 10811,
"text": "C++"
},
{
"code": null,
"e": 10839,
"s": 10815,
"text": "Competitive Programming"
},
{
"code": null,
"e": 10858,
"s": 10839,
"text": "Technical Scripter"
},
{
"code": null,
"e": 10862,
"s": 10858,
"text": "CPP"
},
{
"code": null,
"e": 10960,
"s": 10862,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10977,
"s": 10960,
"text": "Substring in C++"
},
{
"code": null,
"e": 10999,
"s": 10977,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 11045,
"s": 10999,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 11090,
"s": 11045,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 11115,
"s": 11090,
"text": "std::string class in C++"
},
{
"code": null,
"e": 11133,
"s": 11115,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 11176,
"s": 11133,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 11222,
"s": 11176,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 11276,
"s": 11222,
"text": "Priority Queue in C++ Standard Template Library (STL)"
}
] |
Matplotlib.pyplot.setp() function in Python
|
05 Jun, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.
The setp() function in pyplot module of matplotlib library is used to set the property on an artist object.
Syntax: matplotlib.pyplot.setp(obj, \*args, \*\*kwargs)
Parameters: This method accept the following parameters that are described below:
obj: This parameter is the artist object.
**kwargs: There are different keyword arguments which are accepted.
Returns: This method does not returns any value.
Below examples illustrate the matplotlib.pyplot.setp() function in matplotlib.pyplot:
Example 1:
Python3
#Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt def tellme(s): plt.title(s, fontsize=16) plt.draw()plt.clf()plt.setp(plt.gca(), autoscale_on=False) tellme('matplotlib.pyplot.setp() function Example')plt.show()
Output:
Example 2:
Python3
# Implementation of matplotlib functionimport matplotlibimport numpy as npimport matplotlib.cm as cmimport matplotlib.pyplot as plt delta = 0.25x = np.arange(-3.0, 5.0, delta)y = np.arange(-1.3, 2.5, delta)X, Y = np.meshgrid(x, y)Z = (np.exp(-X**2 - Y**2) - np.exp(-(X - 1)**2 - (Y - 1)**2)) im = plt.imshow(Z, interpolation='bilinear', origin='lower', cmap="bone", extent=(-3, 3, -2, 2)) levels = np.arange(-1.2, 1.6, 0.2)CS = plt.contour(Z, levels, origin='lower', cmap='Greens', linewidths=2, extent=(-3, 3, -2, 2)) zc = CS.collections[6]plt.setp(zc, linewidth=2) plt.clabel(CS, levels, inline=1, fmt='%1.1f', fontsize=14) plt.title('matplotlib.pyplot.setp() Example') plt.show()
Output:
Matplotlib Pyplot-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 333,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc."
},
{
"code": null,
"e": 443,
"s": 333,
"text": "The setp() function in pyplot module of matplotlib library is used to set the property on an artist object. "
},
{
"code": null,
"e": 500,
"s": 443,
"text": "Syntax: matplotlib.pyplot.setp(obj, \\*args, \\*\\*kwargs) "
},
{
"code": null,
"e": 583,
"s": 500,
"text": "Parameters: This method accept the following parameters that are described below: "
},
{
"code": null,
"e": 625,
"s": 583,
"text": "obj: This parameter is the artist object."
},
{
"code": null,
"e": 693,
"s": 625,
"text": "**kwargs: There are different keyword arguments which are accepted."
},
{
"code": null,
"e": 743,
"s": 693,
"text": "Returns: This method does not returns any value. "
},
{
"code": null,
"e": 831,
"s": 743,
"text": "Below examples illustrate the matplotlib.pyplot.setp() function in matplotlib.pyplot: "
},
{
"code": null,
"e": 843,
"s": 831,
"text": "Example 1: "
},
{
"code": null,
"e": 851,
"s": 843,
"text": "Python3"
},
{
"code": "#Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt def tellme(s): plt.title(s, fontsize=16) plt.draw()plt.clf()plt.setp(plt.gca(), autoscale_on=False) tellme('matplotlib.pyplot.setp() function Example')plt.show()",
"e": 1114,
"s": 851,
"text": null
},
{
"code": null,
"e": 1123,
"s": 1114,
"text": "Output: "
},
{
"code": null,
"e": 1135,
"s": 1123,
"text": "Example 2: "
},
{
"code": null,
"e": 1143,
"s": 1135,
"text": "Python3"
},
{
"code": "# Implementation of matplotlib functionimport matplotlibimport numpy as npimport matplotlib.cm as cmimport matplotlib.pyplot as plt delta = 0.25x = np.arange(-3.0, 5.0, delta)y = np.arange(-1.3, 2.5, delta)X, Y = np.meshgrid(x, y)Z = (np.exp(-X**2 - Y**2) - np.exp(-(X - 1)**2 - (Y - 1)**2)) im = plt.imshow(Z, interpolation='bilinear', origin='lower', cmap=\"bone\", extent=(-3, 3, -2, 2)) levels = np.arange(-1.2, 1.6, 0.2)CS = plt.contour(Z, levels, origin='lower', cmap='Greens', linewidths=2, extent=(-3, 3, -2, 2)) zc = CS.collections[6]plt.setp(zc, linewidth=2) plt.clabel(CS, levels, inline=1, fmt='%1.1f', fontsize=14) plt.title('matplotlib.pyplot.setp() Example') plt.show()",
"e": 1979,
"s": 1143,
"text": null
},
{
"code": null,
"e": 1988,
"s": 1979,
"text": "Output: "
},
{
"code": null,
"e": 2014,
"s": 1990,
"text": "Matplotlib Pyplot-class"
},
{
"code": null,
"e": 2032,
"s": 2014,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2039,
"s": 2032,
"text": "Python"
},
{
"code": null,
"e": 2137,
"s": 2039,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2155,
"s": 2137,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2197,
"s": 2155,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2219,
"s": 2197,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2254,
"s": 2219,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2280,
"s": 2254,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2312,
"s": 2280,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2341,
"s": 2312,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2368,
"s": 2341,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2398,
"s": 2368,
"text": "Iterate over a list in Python"
}
] |
R – Merge Multiple DataFrames in List
|
10 Oct, 2021
In this article, we will discuss how to merge multiple data frames in the list using R programming language.
First create more than two data frames, so that we could able to merge them. Now, use merge() function along with the required parameters.
Syntax :
merge( x=dataframe , y=dataframe , by= primary_key_of_the_dataframe )
Now, pass this merged dataframe to as.list() to convert it into a list.
Syntax:
as.list(merged_dataframe)
Example 1: Merge multiple dataframes in a list
R
df = data.frame( id=c(1, 2, 3), name=c("karthik", "chandu", "nandu")) df1 = data.frame( id=c(1, 2, 3), branch=c("IT", "CSE", "CSE")) merg = merge(x=df, y=df1, by="id")print(as.list(merg))
Output :
Example 2: Merge multiple dataframes in list
R
df = data.frame( id=c(1, 2, 3), name=c("karthik", "chandu", "nandu")) df1 = data.frame( id=c(1, 2, 3), branch=c("IT", "CSE", "CSE")) df2 = data.frame( id=c(1, 2, 3), company=c("TCS", "Accenture", "Infosys")) merg = merge(x=df, y=df1, z=df2, by="id")print(as.list(merg))
Output :
If we want to merge more than two dataframes we can use cbind() function and pass the resultant cbind() variable into as.list() function to convert it into list .
Syntax :
cbind( df1 , df2 . df3 , . . . dfn )
Example 1: Merge multiple dataframes in list
R
df = data.frame(name=c("karthik", "chandu", "nandu"))df1 = data.frame(branch=c("IT", "CSE", "CSE"))df2 = data.frame(company=c("TCS", "Accenture", "Infosys")) merg = cbind(df, df1, df2)print(as.list(merg))
Output :
Example 2: Merge multiple dataframes in list
R
df = data.frame(name=c("karthik", "chandu", "nandu"))df1 = data.frame(collage_name=c("VFSTR", "VMTW", "IIT"))df2 = data.frame(place=c("Guntur", "Hyderabad", "Kharagpur"))df3 = data.frame(proper=c("yellandu", "yellandu", "yellandu")) merg = cbind(df, df1, df2, df3)print(as.list(merg))
Output :
If we want to merge more than two dataframes we can use tidyverse library too. Here a first an inner join is created for all the participating dataframes and then that is converted to a list as above.
Syntax:
reduce(inner_join, by=”common column”)
Example 1: Merge multiple dataframes in list
R
library("tidyverse") df1 = data.frame( id=c(1, 2, 3), name=c("karthik", "chandu", "nandu")) df2 = data.frame( id=c(1, 2, 3), Gender=c("Male", "Female", "Male")) df3 = data.frame( id=c(1, 2, 3), address=c("Yellandu", "Yellandu", "Yellandu")) data = list(df1, df2, df3)as.list(data % > % reduce(inner_join, by="id"))
Output :
Example 2 : Merge multiple dataframes in list
R
library("tidyverse") df1 = data.frame( id=c(1, 2, 3), name=c("karthik", "chandu", "nandu")) df2 = data.frame( id=c(1, 2, 3), Gender=c("Male", "Female", "Male")) df3 = data.frame( id=c(1, 2, 3), address=c("Yellandu", "Yellandu", "Yellandu")) df4 = data.frame( id=c(1, 2, 3), father_name=c("Ramana", "Radha", "krishna")) data = list(df1, df2, df3, df4)as.list(data % > % reduce(inner_join, by="id"))
Output :
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?
R - if statement
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": "\n10 Oct, 2021"
},
{
"code": null,
"e": 137,
"s": 28,
"text": "In this article, we will discuss how to merge multiple data frames in the list using R programming language."
},
{
"code": null,
"e": 276,
"s": 137,
"text": "First create more than two data frames, so that we could able to merge them. Now, use merge() function along with the required parameters."
},
{
"code": null,
"e": 285,
"s": 276,
"text": "Syntax :"
},
{
"code": null,
"e": 355,
"s": 285,
"text": "merge( x=dataframe , y=dataframe , by= primary_key_of_the_dataframe )"
},
{
"code": null,
"e": 428,
"s": 355,
"text": "Now, pass this merged dataframe to as.list() to convert it into a list. "
},
{
"code": null,
"e": 436,
"s": 428,
"text": "Syntax:"
},
{
"code": null,
"e": 462,
"s": 436,
"text": "as.list(merged_dataframe)"
},
{
"code": null,
"e": 509,
"s": 462,
"text": "Example 1: Merge multiple dataframes in a list"
},
{
"code": null,
"e": 511,
"s": 509,
"text": "R"
},
{
"code": "df = data.frame( id=c(1, 2, 3), name=c(\"karthik\", \"chandu\", \"nandu\")) df1 = data.frame( id=c(1, 2, 3), branch=c(\"IT\", \"CSE\", \"CSE\")) merg = merge(x=df, y=df1, by=\"id\")print(as.list(merg))",
"e": 707,
"s": 511,
"text": null
},
{
"code": null,
"e": 716,
"s": 707,
"text": "Output :"
},
{
"code": null,
"e": 761,
"s": 716,
"text": "Example 2: Merge multiple dataframes in list"
},
{
"code": null,
"e": 763,
"s": 761,
"text": "R"
},
{
"code": "df = data.frame( id=c(1, 2, 3), name=c(\"karthik\", \"chandu\", \"nandu\")) df1 = data.frame( id=c(1, 2, 3), branch=c(\"IT\", \"CSE\", \"CSE\")) df2 = data.frame( id=c(1, 2, 3), company=c(\"TCS\", \"Accenture\", \"Infosys\")) merg = merge(x=df, y=df1, z=df2, by=\"id\")print(as.list(merg))",
"e": 1045,
"s": 763,
"text": null
},
{
"code": null,
"e": 1054,
"s": 1045,
"text": "Output :"
},
{
"code": null,
"e": 1217,
"s": 1054,
"text": "If we want to merge more than two dataframes we can use cbind() function and pass the resultant cbind() variable into as.list() function to convert it into list ."
},
{
"code": null,
"e": 1226,
"s": 1217,
"text": "Syntax :"
},
{
"code": null,
"e": 1263,
"s": 1226,
"text": "cbind( df1 , df2 . df3 , . . . dfn )"
},
{
"code": null,
"e": 1308,
"s": 1263,
"text": "Example 1: Merge multiple dataframes in list"
},
{
"code": null,
"e": 1310,
"s": 1308,
"text": "R"
},
{
"code": "df = data.frame(name=c(\"karthik\", \"chandu\", \"nandu\"))df1 = data.frame(branch=c(\"IT\", \"CSE\", \"CSE\"))df2 = data.frame(company=c(\"TCS\", \"Accenture\", \"Infosys\")) merg = cbind(df, df1, df2)print(as.list(merg))",
"e": 1516,
"s": 1310,
"text": null
},
{
"code": null,
"e": 1525,
"s": 1516,
"text": "Output :"
},
{
"code": null,
"e": 1570,
"s": 1525,
"text": "Example 2: Merge multiple dataframes in list"
},
{
"code": null,
"e": 1572,
"s": 1570,
"text": "R"
},
{
"code": "df = data.frame(name=c(\"karthik\", \"chandu\", \"nandu\"))df1 = data.frame(collage_name=c(\"VFSTR\", \"VMTW\", \"IIT\"))df2 = data.frame(place=c(\"Guntur\", \"Hyderabad\", \"Kharagpur\"))df3 = data.frame(proper=c(\"yellandu\", \"yellandu\", \"yellandu\")) merg = cbind(df, df1, df2, df3)print(as.list(merg))",
"e": 1858,
"s": 1572,
"text": null
},
{
"code": null,
"e": 1867,
"s": 1858,
"text": "Output :"
},
{
"code": null,
"e": 2068,
"s": 1867,
"text": "If we want to merge more than two dataframes we can use tidyverse library too. Here a first an inner join is created for all the participating dataframes and then that is converted to a list as above."
},
{
"code": null,
"e": 2076,
"s": 2068,
"text": "Syntax:"
},
{
"code": null,
"e": 2115,
"s": 2076,
"text": "reduce(inner_join, by=”common column”)"
},
{
"code": null,
"e": 2160,
"s": 2115,
"text": "Example 1: Merge multiple dataframes in list"
},
{
"code": null,
"e": 2162,
"s": 2160,
"text": "R"
},
{
"code": "library(\"tidyverse\") df1 = data.frame( id=c(1, 2, 3), name=c(\"karthik\", \"chandu\", \"nandu\")) df2 = data.frame( id=c(1, 2, 3), Gender=c(\"Male\", \"Female\", \"Male\")) df3 = data.frame( id=c(1, 2, 3), address=c(\"Yellandu\", \"Yellandu\", \"Yellandu\")) data = list(df1, df2, df3)as.list(data % > % reduce(inner_join, by=\"id\"))",
"e": 2489,
"s": 2162,
"text": null
},
{
"code": null,
"e": 2498,
"s": 2489,
"text": "Output :"
},
{
"code": null,
"e": 2544,
"s": 2498,
"text": "Example 2 : Merge multiple dataframes in list"
},
{
"code": null,
"e": 2546,
"s": 2544,
"text": "R"
},
{
"code": "library(\"tidyverse\") df1 = data.frame( id=c(1, 2, 3), name=c(\"karthik\", \"chandu\", \"nandu\")) df2 = data.frame( id=c(1, 2, 3), Gender=c(\"Male\", \"Female\", \"Male\")) df3 = data.frame( id=c(1, 2, 3), address=c(\"Yellandu\", \"Yellandu\", \"Yellandu\")) df4 = data.frame( id=c(1, 2, 3), father_name=c(\"Ramana\", \"Radha\", \"krishna\")) data = list(df1, df2, df3, df4)as.list(data % > % reduce(inner_join, by=\"id\"))",
"e": 2959,
"s": 2546,
"text": null
},
{
"code": null,
"e": 2968,
"s": 2959,
"text": "Output :"
},
{
"code": null,
"e": 2975,
"s": 2968,
"text": "Picked"
},
{
"code": null,
"e": 2996,
"s": 2975,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 3008,
"s": 2996,
"text": "R-DataFrame"
},
{
"code": null,
"e": 3019,
"s": 3008,
"text": "R Language"
},
{
"code": null,
"e": 3030,
"s": 3019,
"text": "R Programs"
},
{
"code": null,
"e": 3128,
"s": 3030,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3180,
"s": 3128,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 3238,
"s": 3180,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3273,
"s": 3238,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 3311,
"s": 3273,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 3328,
"s": 3311,
"text": "R - if statement"
},
{
"code": null,
"e": 3386,
"s": 3328,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3435,
"s": 3386,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 3478,
"s": 3435,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 3516,
"s": 3478,
"text": "Merge DataFrames by Column Names in R"
}
] |
How to find the difference in value in every two consecutive rows in R DataFrame ?
|
30 May, 2021
In this article, we will discuss how to find the difference in value in every two consecutive rows in DataFrame in R Programming Language.
diff() method in base R is used to find the difference among all the pairs of consecutive rows in the R dataframe. It returns a vector with the length equivalent to the length of the input column – 1. The elements of the input column are evaluated from the last element, where each element is replaced by the element at nth index – element at (n-1)th index. No output is returned for the first element, since it doesn’t have any element to induce lag with reference to. This method is applicable for integer or numeric data columns itself.
Syntax:
diff(vec , lag = 1 )
Parameter :
vec – Vector to compute the differences of
lag – (Default : 1 )The nth previous value to compute the differences with
Example:
R
# creating a dataframedata_frame <- data.frame(col1 = rep(c(1:3), each = 3), col2 = letters[1:3], col3 = c(1,4,1,2,3,2,1,2,2)) print ("Original DataFrame")print (data_frame) print ("Difference in col3 successive values")diff(data_frame$col3)
Output
[1] "Original DataFrame"
col1 col2 col3
1 1 a 1
2 1 b 4
3 1 c 1
4 2 a 2
5 2 b 3
6 2 c 2
7 3 a 1
8 3 b 2
9 3 c 2
[1] "Difference in col3 successive values"
[1] 3 -3 1 1 -1 -1 1 0
The “dply” package in R programming language can be used to carry out data modifications or enhancements. It provides a large variety of functions to produce data manipulation and extraction operations.
The mutate() method is used for the creation, deletion, and updating of the columns of the dataframe. It takes as an argument the new column name and the corresponding function to apply upon it.
Syntax:
mutate ( new-col-name = col-name – lag(col-name))
The lag() method of the dplyr package is used to return the previous value of the specified column. It returns NA if there is no preceding row for that column. The customized column name can be assigned to the difference column. This method is different from others as it returns a superset of the original dataframe as an output.
Example:
R
library("dplyr") # creating a dataframedata_frame <- data.frame(col1 = rep(c(1:3), each = 3), col2 = letters[1:3], col3 = c(1,4,1,2,2,2,1,2,2)) print ("Original DataFrame")print (data_frame) print ("Modified DataFrame")# difference in rows of col3data_frame %>% mutate(col3_diff = col3 - lag(col3))
Output
[1] "Original DataFrame"
col1 col2 col3
1 1 a 1
2 1 b 4
3 1 c 1
4 2 a 2
5 2 b 2
6 2 c 2
7 3 a 1
8 3 b 2
9 3 c 2
[1] "Modified DataFrame"
col1 col2 col3 col3_diff
1 1 a 1 NA
2 1 b 4 3
3 1 c 1 -3
4 2 a 2 1
5 2 b 2 0
6 2 c 2 0
7 3 a 1 -1
8 3 b 2 1
9 3 c 2 0
All the columns can be calculated to find the difference of the values in every pair of consecutive rows of the dataframe. The dataframe is accessed from the last row with every row one place before it. And, the value is obtained by the subtraction of the row at nth index with row at (n-1)th index. In case, the class of the dataframe column is a character, a missing value is returned.
The first row is deleted from the output dataframe. The row numbers beginning with row number 2 are returned as an output dataframe.
Example:
R
# creating a dataframedata_frame <- data.frame(col1 = rep(c(1:3), each = 3), col2 = letters[1:3], col3 = c(1,4,1,2,2,2,1,2,2)) print ("Original DataFrame")print (data_frame) # calculating rows of dataframerows <- nrow(data_frame) # difference in rows of entire dataframediff_frame <- data_frame[-1,] - data_frame[-rows,] print ("Modified DataFrame")print(diff_frame)
Output
[1] "Original DataFrame"
col1 col2 col3
1 1 a 1
2 1 b 4
3 1 c 1
4 2 a 2
5 2 b 2
6 2 c 2
7 3 a 1
8 3 b 2
9 3 c 2
[1] "Modified DataFrame"
col1 col2 col3
2 0 NA 3
3 0 NA -3
4 1 NA 1
5 0 NA 0
6 0 NA 0
7 1 NA -1
8 0 NA 1
9 0 NA 0
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.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "In this article, we will discuss how to find the difference in value in every two consecutive rows in DataFrame in R Programming Language."
},
{
"code": null,
"e": 710,
"s": 167,
"text": "diff() method in base R is used to find the difference among all the pairs of consecutive rows in the R dataframe. It returns a vector with the length equivalent to the length of the input column – 1. The elements of the input column are evaluated from the last element, where each element is replaced by the element at nth index – element at (n-1)th index. No output is returned for the first element, since it doesn’t have any element to induce lag with reference to. This method is applicable for integer or numeric data columns itself. "
},
{
"code": null,
"e": 718,
"s": 710,
"text": "Syntax:"
},
{
"code": null,
"e": 739,
"s": 718,
"text": "diff(vec , lag = 1 )"
},
{
"code": null,
"e": 752,
"s": 739,
"text": "Parameter : "
},
{
"code": null,
"e": 795,
"s": 752,
"text": "vec – Vector to compute the differences of"
},
{
"code": null,
"e": 870,
"s": 795,
"text": "lag – (Default : 1 )The nth previous value to compute the differences with"
},
{
"code": null,
"e": 879,
"s": 870,
"text": "Example:"
},
{
"code": null,
"e": 881,
"s": 879,
"text": "R"
},
{
"code": "# creating a dataframedata_frame <- data.frame(col1 = rep(c(1:3), each = 3), col2 = letters[1:3], col3 = c(1,4,1,2,3,2,1,2,2)) print (\"Original DataFrame\")print (data_frame) print (\"Difference in col3 successive values\")diff(data_frame$col3)",
"e": 1173,
"s": 881,
"text": null
},
{
"code": null,
"e": 1180,
"s": 1173,
"text": "Output"
},
{
"code": null,
"e": 1445,
"s": 1180,
"text": "[1] \"Original DataFrame\"\n col1 col2 col3\n1 1 a 1\n2 1 b 4\n3 1 c 1\n4 2 a 2\n5 2 b 3\n6 2 c 2\n7 3 a 1\n8 3 b 2\n9 3 c 2\n[1] \"Difference in col3 successive values\"\n[1] 3 -3 1 1 -1 -1 1 0"
},
{
"code": null,
"e": 1649,
"s": 1445,
"text": "The “dply” package in R programming language can be used to carry out data modifications or enhancements. It provides a large variety of functions to produce data manipulation and extraction operations. "
},
{
"code": null,
"e": 1845,
"s": 1649,
"text": "The mutate() method is used for the creation, deletion, and updating of the columns of the dataframe. It takes as an argument the new column name and the corresponding function to apply upon it. "
},
{
"code": null,
"e": 1853,
"s": 1845,
"text": "Syntax:"
},
{
"code": null,
"e": 1903,
"s": 1853,
"text": "mutate ( new-col-name = col-name – lag(col-name))"
},
{
"code": null,
"e": 2234,
"s": 1903,
"text": "The lag() method of the dplyr package is used to return the previous value of the specified column. It returns NA if there is no preceding row for that column. The customized column name can be assigned to the difference column. This method is different from others as it returns a superset of the original dataframe as an output."
},
{
"code": null,
"e": 2243,
"s": 2234,
"text": "Example:"
},
{
"code": null,
"e": 2245,
"s": 2243,
"text": "R"
},
{
"code": "library(\"dplyr\") # creating a dataframedata_frame <- data.frame(col1 = rep(c(1:3), each = 3), col2 = letters[1:3], col3 = c(1,4,1,2,2,2,1,2,2)) print (\"Original DataFrame\")print (data_frame) print (\"Modified DataFrame\")# difference in rows of col3data_frame %>% mutate(col3_diff = col3 - lag(col3))",
"e": 2596,
"s": 2245,
"text": null
},
{
"code": null,
"e": 2603,
"s": 2596,
"text": "Output"
},
{
"code": null,
"e": 3114,
"s": 2603,
"text": "[1] \"Original DataFrame\" \n col1 col2 col3 \n1 1 a 1 \n2 1 b 4 \n3 1 c 1 \n4 2 a 2 \n5 2 b 2 \n6 2 c 2 \n7 3 a 1 \n8 3 b 2 \n9 3 c 2 \n[1] \"Modified DataFrame\" \n col1 col2 col3 col3_diff \n1 1 a 1 NA \n2 1 b 4 3 \n3 1 c 1 -3 \n4 2 a 2 1 \n5 2 b 2 0 \n6 2 c 2 0 \n7 3 a 1 -1 \n8 3 b 2 1 \n9 3 c 2 0"
},
{
"code": null,
"e": 3503,
"s": 3114,
"text": "All the columns can be calculated to find the difference of the values in every pair of consecutive rows of the dataframe. The dataframe is accessed from the last row with every row one place before it. And, the value is obtained by the subtraction of the row at nth index with row at (n-1)th index. In case, the class of the dataframe column is a character, a missing value is returned. "
},
{
"code": null,
"e": 3637,
"s": 3503,
"text": "The first row is deleted from the output dataframe. The row numbers beginning with row number 2 are returned as an output dataframe. "
},
{
"code": null,
"e": 3646,
"s": 3637,
"text": "Example:"
},
{
"code": null,
"e": 3648,
"s": 3646,
"text": "R"
},
{
"code": "# creating a dataframedata_frame <- data.frame(col1 = rep(c(1:3), each = 3), col2 = letters[1:3], col3 = c(1,4,1,2,2,2,1,2,2)) print (\"Original DataFrame\")print (data_frame) # calculating rows of dataframerows <- nrow(data_frame) # difference in rows of entire dataframediff_frame <- data_frame[-1,] - data_frame[-rows,] print (\"Modified DataFrame\")print(diff_frame)",
"e": 4067,
"s": 3648,
"text": null
},
{
"code": null,
"e": 4074,
"s": 4067,
"text": "Output"
},
{
"code": null,
"e": 4453,
"s": 4074,
"text": "[1] \"Original DataFrame\"\n col1 col2 col3\n1 1 a 1\n2 1 b 4\n3 1 c 1\n4 2 a 2\n5 2 b 2\n6 2 c 2\n7 3 a 1\n8 3 b 2\n9 3 c 2\n[1] \"Modified DataFrame\"\n col1 col2 col3\n 2 0 NA 3\n 3 0 NA -3\n 4 1 NA 1\n 5 0 NA 0\n 6 0 NA 0\n 7 1 NA -1\n 8 0 NA 1\n 9 0 NA 0"
},
{
"code": null,
"e": 4460,
"s": 4453,
"text": "Picked"
},
{
"code": null,
"e": 4481,
"s": 4460,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 4493,
"s": 4481,
"text": "R-DataFrame"
},
{
"code": null,
"e": 4504,
"s": 4493,
"text": "R Language"
},
{
"code": null,
"e": 4515,
"s": 4504,
"text": "R Programs"
}
] |
Node.js fs.rm() Method
|
03 Feb, 2021
The fs.rm() method is used to delete a file at the given path. It can also be used recursively to remove directories.
Syntax:
fs.rm( path, options, callback );
Parameters: This method accepts three parameters as mentioned above and described below:
path: It holds the path of the file that has to be removed. It can be a String, Buffer, or URL.
options: It is an object that can be used to specify optional parameters that will affect the operation as follows:force: It is a boolean value. Exceptions will be ignored if the path does not exist.recursive: It is a boolean value that specifies if recursive directory removal is performed. In this mode, errors are not reported if the specified path is not found and the operation is retried on failure. The default value is false.
force: It is a boolean value. Exceptions will be ignored if the path does not exist.
recursive: It is a boolean value that specifies if recursive directory removal is performed. In this mode, errors are not reported if the specified path is not found and the operation is retried on failure. The default value is false.
callback: It is the function that would be called when the method is executed.err: It is an error that would be thrown if the operation fails.
err: It is an error that would be thrown if the operation fails.
Below examples illustrate the fs.rm() method in Node.js:
Example 1: This example uses fs.rm() method to delete a file.
Filename: index.js
Javascript
// Import necessary moduleslet fs = require('fs'); // List files before deletinggetCurrentFilenames(); fs.rm('./dummy.txt', { recursive:true }, (err) => { if(err){ // File deletion failed console.error(err.message); return; } console.log("File deleted successfully"); // List files after deleting getCurrentFilenames();}) // This will list all files in current directoryfunction getCurrentFilenames() { console.log("\nCurrent filenames:"); fs.readdirSync(__dirname).forEach(file => { console.log(file); }); console.log(""); }
Run the index.js file using the following command:
node index.js
Output:
Current filenames:
dummy.txt
index.js
node_modules
package-lock.json
package.json
File deleted successfully
Current filenames:
index.js
node_modules
package-lock.json
package.json
Example 2: This example uses fs.rm() method with the recursive parameter to delete directories.
Filename: index.js
Javascript
// Import the filesystem module const fs = require('fs'); // List the files in current directory getCurrentFilenames(); // Trying to delete directory without the recursive parameter fs.rm("./build", { recursive: false }, (err) => { if (err) { console.error(err); } else { console.log("Non Recursive: Directory Deleted!"); } }); // Using the recursive option to delete directory fs.rm("./build", { recursive: true }, (err) => { if (err) { console.error(err); } else { console.log("Recursive: Directory Deleted!"); // List files after delete getCurrentFilenames(); } }); // List all files in current directoryfunction getCurrentFilenames() { console.log("\nCurrent filenames:"); fs.readdirSync(__dirname).forEach(file => { console.log(file); }); console.log("\n"); }
Run the index.js file using the following command:
node index.js
Output:
Current filenames:
build
index.js
node_modules
package-lock.json
package.json
SystemError [ERR_FS_EISDIR]: Path is a directory: rm returned EISDIR
(is a directory) ./build
at internal/fs/utils.js:688:23
at FSReqCallback.oncomplete (fs.js:184:5) {
code: 'ERR_FS_EISDIR',
info: {
code: 'EISDIR',
message: 'is a directory',
path: './build',
syscall: 'rm',
errno: 21
},
errno: [Getter/Setter: 21],
syscall: [Getter/Setter: 'rm'],
path: [Getter/Setter: './build']
}
Recursive: Directory Deleted!
Current filenames:
index.js
node_modules
package-lock.json
package.json
Reference:https://nodejs.org/api/fs.html#fs_fs_rm_path_options_callback
Node.js-fs-module
Technical Scripter 2020
Node.js
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Feb, 2021"
},
{
"code": null,
"e": 146,
"s": 28,
"text": "The fs.rm() method is used to delete a file at the given path. It can also be used recursively to remove directories."
},
{
"code": null,
"e": 154,
"s": 146,
"text": "Syntax:"
},
{
"code": null,
"e": 188,
"s": 154,
"text": "fs.rm( path, options, callback );"
},
{
"code": null,
"e": 277,
"s": 188,
"text": "Parameters: This method accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 373,
"s": 277,
"text": "path: It holds the path of the file that has to be removed. It can be a String, Buffer, or URL."
},
{
"code": null,
"e": 807,
"s": 373,
"text": "options: It is an object that can be used to specify optional parameters that will affect the operation as follows:force: It is a boolean value. Exceptions will be ignored if the path does not exist.recursive: It is a boolean value that specifies if recursive directory removal is performed. In this mode, errors are not reported if the specified path is not found and the operation is retried on failure. The default value is false."
},
{
"code": null,
"e": 892,
"s": 807,
"text": "force: It is a boolean value. Exceptions will be ignored if the path does not exist."
},
{
"code": null,
"e": 1127,
"s": 892,
"text": "recursive: It is a boolean value that specifies if recursive directory removal is performed. In this mode, errors are not reported if the specified path is not found and the operation is retried on failure. The default value is false."
},
{
"code": null,
"e": 1270,
"s": 1127,
"text": "callback: It is the function that would be called when the method is executed.err: It is an error that would be thrown if the operation fails."
},
{
"code": null,
"e": 1335,
"s": 1270,
"text": "err: It is an error that would be thrown if the operation fails."
},
{
"code": null,
"e": 1392,
"s": 1335,
"text": "Below examples illustrate the fs.rm() method in Node.js:"
},
{
"code": null,
"e": 1454,
"s": 1392,
"text": "Example 1: This example uses fs.rm() method to delete a file."
},
{
"code": null,
"e": 1473,
"s": 1454,
"text": "Filename: index.js"
},
{
"code": null,
"e": 1484,
"s": 1473,
"text": "Javascript"
},
{
"code": "// Import necessary moduleslet fs = require('fs'); // List files before deletinggetCurrentFilenames(); fs.rm('./dummy.txt', { recursive:true }, (err) => { if(err){ // File deletion failed console.error(err.message); return; } console.log(\"File deleted successfully\"); // List files after deleting getCurrentFilenames();}) // This will list all files in current directoryfunction getCurrentFilenames() { console.log(\"\\nCurrent filenames:\"); fs.readdirSync(__dirname).forEach(file => { console.log(file); }); console.log(\"\"); }",
"e": 2079,
"s": 1484,
"text": null
},
{
"code": null,
"e": 2130,
"s": 2079,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 2144,
"s": 2130,
"text": "node index.js"
},
{
"code": null,
"e": 2152,
"s": 2144,
"text": "Output:"
},
{
"code": null,
"e": 2347,
"s": 2152,
"text": "Current filenames:\ndummy.txt \nindex.js\nnode_modules \npackage-lock.json\npackage.json\n\nFile deleted successfully\n\nCurrent filenames:\nindex.js\nnode_modules\npackage-lock.json\npackage.json"
},
{
"code": null,
"e": 2443,
"s": 2347,
"text": "Example 2: This example uses fs.rm() method with the recursive parameter to delete directories."
},
{
"code": null,
"e": 2462,
"s": 2443,
"text": "Filename: index.js"
},
{
"code": null,
"e": 2473,
"s": 2462,
"text": "Javascript"
},
{
"code": "// Import the filesystem module const fs = require('fs'); // List the files in current directory getCurrentFilenames(); // Trying to delete directory without the recursive parameter fs.rm(\"./build\", { recursive: false }, (err) => { if (err) { console.error(err); } else { console.log(\"Non Recursive: Directory Deleted!\"); } }); // Using the recursive option to delete directory fs.rm(\"./build\", { recursive: true }, (err) => { if (err) { console.error(err); } else { console.log(\"Recursive: Directory Deleted!\"); // List files after delete getCurrentFilenames(); } }); // List all files in current directoryfunction getCurrentFilenames() { console.log(\"\\nCurrent filenames:\"); fs.readdirSync(__dirname).forEach(file => { console.log(file); }); console.log(\"\\n\"); }",
"e": 3307,
"s": 2473,
"text": null
},
{
"code": null,
"e": 3358,
"s": 3307,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 3372,
"s": 3358,
"text": "node index.js"
},
{
"code": null,
"e": 3380,
"s": 3372,
"text": "Output:"
},
{
"code": null,
"e": 3993,
"s": 3380,
"text": "Current filenames:\nbuild\n\nindex.js\nnode_modules \npackage-lock.json\npackage.json\n\nSystemError [ERR_FS_EISDIR]: Path is a directory: rm returned EISDIR \n(is a directory) ./build\n at internal/fs/utils.js:688:23\n at FSReqCallback.oncomplete (fs.js:184:5) {\n code: 'ERR_FS_EISDIR',\n info: {\n code: 'EISDIR',\n message: 'is a directory',\n path: './build',\n syscall: 'rm',\n errno: 21\n },\n errno: [Getter/Setter: 21],\n syscall: [Getter/Setter: 'rm'],\n path: [Getter/Setter: './build']\n}\n\nRecursive: Directory Deleted!\n\nCurrent filenames:\nindex.js\nnode_modules\npackage-lock.json\npackage.json"
},
{
"code": null,
"e": 4065,
"s": 3993,
"text": "Reference:https://nodejs.org/api/fs.html#fs_fs_rm_path_options_callback"
},
{
"code": null,
"e": 4083,
"s": 4065,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 4107,
"s": 4083,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 4115,
"s": 4107,
"text": "Node.js"
},
{
"code": null,
"e": 4134,
"s": 4115,
"text": "Technical Scripter"
}
] |
Perl | Regular Expressions
|
30 May, 2019
Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“. To use the Regex, Binding operators like ‘=~‘(Regex Operator) and ‘!~‘ (Negated Regex Operator) are used. Before moving to Binding operators let’s have a look at building patterns.
Building Patterns: In Perl, patterns can be constructed using the m// operator. In this operator, the required pattern is simply placed between the two slashes and the binding operators are used to search for the pattern in the specified string.
Using m// and Binding Operators: Mostly the binding operators are used with the m// operator so that required pattern could be matched out. Regex operator is used to match a string with a regular expression. The left-hand side of the statement will contain a string which will be matched with the right-hand side containing the specified pattern. Negated regex operator is used to check if the string is not equal to the regular expression specified on the right-hand side.
Program 1: To illustrate the use of ‘m//’ and ‘=~’ as follows:# Perl program to demonstrate# the m// and =~ operators # Actual String$a = "GEEKSFORGEEKS"; # Prints match found if # its found in $aif ($a =~ m[GEEKS]) { print "Match Found\n";} # Prints match not found # if its not found in $aelse { print "Match Not Found\n";}Output:Match Found
# Perl program to demonstrate# the m// and =~ operators # Actual String$a = "GEEKSFORGEEKS"; # Prints match found if # its found in $aif ($a =~ m[GEEKS]) { print "Match Found\n";} # Prints match not found # if its not found in $aelse { print "Match Not Found\n";}
Match Found
Program 2: To illustrate the use of ‘m//’ and ‘!~’ as follows:# Perl program to demonstrate# the m// and !~ operators # Actual String$a = "GEEKSFORGEEKS"; # Prints match found if # its not found in $aif ($a !~ m[GEEKS]) { print "Match Found\n";} # Prints match not found # if it is found in $aelse{ print "Match Not Found\n";}Output:Match Not Found
# Perl program to demonstrate# the m// and !~ operators # Actual String$a = "GEEKSFORGEEKS"; # Prints match found if # its not found in $aif ($a !~ m[GEEKS]) { print "Match Found\n";} # Prints match not found # if it is found in $aelse{ print "Match Not Found\n";}
Match Not Found
Uses of Regular Expression:
It can be used to count the number of occurrence of a specified pattern in a string.
It can be used to search for a string which matches the specified pattern.
It can also replace the searched pattern with some other specified string.
Perl-regex
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | split() Function
Perl | push() Function
Perl | chomp() Function
Perl | substr() function
Perl | grep() Function
Perl | exists() Function
Perl Tutorial - Learn Perl With Examples
Perl | length() Function
Perl | Subroutines or Functions
Use of print() and say() in Perl
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 May, 2019"
},
{
"code": null,
"e": 520,
"s": 54,
"text": "Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“. To use the Regex, Binding operators like ‘=~‘(Regex Operator) and ‘!~‘ (Negated Regex Operator) are used. Before moving to Binding operators let’s have a look at building patterns."
},
{
"code": null,
"e": 766,
"s": 520,
"text": "Building Patterns: In Perl, patterns can be constructed using the m// operator. In this operator, the required pattern is simply placed between the two slashes and the binding operators are used to search for the pattern in the specified string."
},
{
"code": null,
"e": 1240,
"s": 766,
"text": "Using m// and Binding Operators: Mostly the binding operators are used with the m// operator so that required pattern could be matched out. Regex operator is used to match a string with a regular expression. The left-hand side of the statement will contain a string which will be matched with the right-hand side containing the specified pattern. Negated regex operator is used to check if the string is not equal to the regular expression specified on the right-hand side."
},
{
"code": null,
"e": 1594,
"s": 1240,
"text": "Program 1: To illustrate the use of ‘m//’ and ‘=~’ as follows:# Perl program to demonstrate# the m// and =~ operators # Actual String$a = \"GEEKSFORGEEKS\"; # Prints match found if # its found in $aif ($a =~ m[GEEKS]) { print \"Match Found\\n\";} # Prints match not found # if its not found in $aelse { print \"Match Not Found\\n\";}Output:Match Found\n"
},
{
"code": "# Perl program to demonstrate# the m// and =~ operators # Actual String$a = \"GEEKSFORGEEKS\"; # Prints match found if # its found in $aif ($a =~ m[GEEKS]) { print \"Match Found\\n\";} # Prints match not found # if its not found in $aelse { print \"Match Not Found\\n\";}",
"e": 1867,
"s": 1594,
"text": null
},
{
"code": null,
"e": 1880,
"s": 1867,
"text": "Match Found\n"
},
{
"code": null,
"e": 2239,
"s": 1880,
"text": "Program 2: To illustrate the use of ‘m//’ and ‘!~’ as follows:# Perl program to demonstrate# the m// and !~ operators # Actual String$a = \"GEEKSFORGEEKS\"; # Prints match found if # its not found in $aif ($a !~ m[GEEKS]) { print \"Match Found\\n\";} # Prints match not found # if it is found in $aelse{ print \"Match Not Found\\n\";}Output:Match Not Found\n"
},
{
"code": "# Perl program to demonstrate# the m// and !~ operators # Actual String$a = \"GEEKSFORGEEKS\"; # Prints match found if # its not found in $aif ($a !~ m[GEEKS]) { print \"Match Found\\n\";} # Prints match not found # if it is found in $aelse{ print \"Match Not Found\\n\";}",
"e": 2513,
"s": 2239,
"text": null
},
{
"code": null,
"e": 2530,
"s": 2513,
"text": "Match Not Found\n"
},
{
"code": null,
"e": 2558,
"s": 2530,
"text": "Uses of Regular Expression:"
},
{
"code": null,
"e": 2643,
"s": 2558,
"text": "It can be used to count the number of occurrence of a specified pattern in a string."
},
{
"code": null,
"e": 2718,
"s": 2643,
"text": "It can be used to search for a string which matches the specified pattern."
},
{
"code": null,
"e": 2793,
"s": 2718,
"text": "It can also replace the searched pattern with some other specified string."
},
{
"code": null,
"e": 2804,
"s": 2793,
"text": "Perl-regex"
},
{
"code": null,
"e": 2809,
"s": 2804,
"text": "Perl"
},
{
"code": null,
"e": 2814,
"s": 2809,
"text": "Perl"
},
{
"code": null,
"e": 2912,
"s": 2814,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2936,
"s": 2912,
"text": "Perl | split() Function"
},
{
"code": null,
"e": 2959,
"s": 2936,
"text": "Perl | push() Function"
},
{
"code": null,
"e": 2983,
"s": 2959,
"text": "Perl | chomp() Function"
},
{
"code": null,
"e": 3008,
"s": 2983,
"text": "Perl | substr() function"
},
{
"code": null,
"e": 3031,
"s": 3008,
"text": "Perl | grep() Function"
},
{
"code": null,
"e": 3056,
"s": 3031,
"text": "Perl | exists() Function"
},
{
"code": null,
"e": 3097,
"s": 3056,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 3122,
"s": 3097,
"text": "Perl | length() Function"
},
{
"code": null,
"e": 3154,
"s": 3122,
"text": "Perl | Subroutines or Functions"
}
] |
List contains() method in Java with Examples
|
11 Dec, 2018
The contains() method of List interface in Java is used for checking if the specified element exists in the given list or not.
Syntax:
public boolean contains(Object obj)
object-element to be searched for
Parameters: This method accepts a single parameter obj whose presence in this list is to be tested.
Return Value: It returns true if the specified element is found in the list else it returns false.
Below programs illustrate the contains() method in List:
Program 1: Demonstrate the working of the method contains() in List of integer.
// Java code to demonstrate the working of// contains() method in List interface import java.util.*; class GFG { public static void main(String[] args) { // creating an Empty Integer List List<Integer> arr = new ArrayList<Integer>(4); // using add() to initialize values // [1, 2, 3, 4] arr.add(1); arr.add(2); arr.add(3); arr.add(4); // use contains() to check if the element // 2 exits or not boolean ans = arr.contains(2); if (ans) System.out.println("The list contains 2"); else System.out.println("The list does not contains 2"); // use contains() to check if the element // 5 exits or not ans = arr.contains(5); if (ans) System.out.println("The list contains 5"); else System.out.println("The list does not contains 5"); }}
The list contains 2
The list does not contains 5
Program 2: Demonstrate the working of the method contains() in List of string.
// Java code to demonstrate the working of// contains() method in List of string import java.util.*; class GFG { public static void main(String[] args) { // creating an Empty String List List<String> arr = new ArrayList<String>(4); // using add() to initialize values // ["geeks", "for", "geeks"] arr.add("geeks"); arr.add("for"); arr.add("geeks"); // use contains() to check if the element // "geeks" exits or not boolean ans = arr.contains("geeks"); if (ans) System.out.println("The list contains geeks"); else System.out.println("The list does not contains geeks"); // use contains() to check if the element // "coding" exits or not ans = arr.contains("coding"); if (ans) System.out.println("The list contains coding"); else System.out.println("The list does not contains coding"); }}
The list contains geeks
The list does not contains coding
Practical Application: In search operations, we can check if a given element exists in a list or not.
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains(java.lang.Object)
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 155,
"s": 28,
"text": "The contains() method of List interface in Java is used for checking if the specified element exists in the given list or not."
},
{
"code": null,
"e": 163,
"s": 155,
"text": "Syntax:"
},
{
"code": null,
"e": 235,
"s": 163,
"text": "public boolean contains(Object obj)\n\nobject-element to be searched for\n"
},
{
"code": null,
"e": 335,
"s": 235,
"text": "Parameters: This method accepts a single parameter obj whose presence in this list is to be tested."
},
{
"code": null,
"e": 434,
"s": 335,
"text": "Return Value: It returns true if the specified element is found in the list else it returns false."
},
{
"code": null,
"e": 491,
"s": 434,
"text": "Below programs illustrate the contains() method in List:"
},
{
"code": null,
"e": 571,
"s": 491,
"text": "Program 1: Demonstrate the working of the method contains() in List of integer."
},
{
"code": "// Java code to demonstrate the working of// contains() method in List interface import java.util.*; class GFG { public static void main(String[] args) { // creating an Empty Integer List List<Integer> arr = new ArrayList<Integer>(4); // using add() to initialize values // [1, 2, 3, 4] arr.add(1); arr.add(2); arr.add(3); arr.add(4); // use contains() to check if the element // 2 exits or not boolean ans = arr.contains(2); if (ans) System.out.println(\"The list contains 2\"); else System.out.println(\"The list does not contains 2\"); // use contains() to check if the element // 5 exits or not ans = arr.contains(5); if (ans) System.out.println(\"The list contains 5\"); else System.out.println(\"The list does not contains 5\"); }}",
"e": 1492,
"s": 571,
"text": null
},
{
"code": null,
"e": 1542,
"s": 1492,
"text": "The list contains 2\nThe list does not contains 5\n"
},
{
"code": null,
"e": 1621,
"s": 1542,
"text": "Program 2: Demonstrate the working of the method contains() in List of string."
},
{
"code": "// Java code to demonstrate the working of// contains() method in List of string import java.util.*; class GFG { public static void main(String[] args) { // creating an Empty String List List<String> arr = new ArrayList<String>(4); // using add() to initialize values // [\"geeks\", \"for\", \"geeks\"] arr.add(\"geeks\"); arr.add(\"for\"); arr.add(\"geeks\"); // use contains() to check if the element // \"geeks\" exits or not boolean ans = arr.contains(\"geeks\"); if (ans) System.out.println(\"The list contains geeks\"); else System.out.println(\"The list does not contains geeks\"); // use contains() to check if the element // \"coding\" exits or not ans = arr.contains(\"coding\"); if (ans) System.out.println(\"The list contains coding\"); else System.out.println(\"The list does not contains coding\"); }}",
"e": 2593,
"s": 1621,
"text": null
},
{
"code": null,
"e": 2652,
"s": 2593,
"text": "The list contains geeks\nThe list does not contains coding\n"
},
{
"code": null,
"e": 2754,
"s": 2652,
"text": "Practical Application: In search operations, we can check if a given element exists in a list or not."
},
{
"code": null,
"e": 2854,
"s": 2754,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains(java.lang.Object)"
},
{
"code": null,
"e": 2871,
"s": 2854,
"text": "Java-Collections"
},
{
"code": null,
"e": 2886,
"s": 2871,
"text": "Java-Functions"
},
{
"code": null,
"e": 2896,
"s": 2886,
"text": "java-list"
},
{
"code": null,
"e": 2901,
"s": 2896,
"text": "Java"
},
{
"code": null,
"e": 2906,
"s": 2901,
"text": "Java"
},
{
"code": null,
"e": 2923,
"s": 2906,
"text": "Java-Collections"
},
{
"code": null,
"e": 3021,
"s": 2923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3072,
"s": 3021,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3103,
"s": 3072,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3122,
"s": 3103,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3152,
"s": 3122,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3170,
"s": 3152,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3185,
"s": 3170,
"text": "Stream In Java"
},
{
"code": null,
"e": 3205,
"s": 3185,
"text": "Collections in Java"
},
{
"code": null,
"e": 3229,
"s": 3205,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 3261,
"s": 3229,
"text": "Multidimensional Arrays in Java"
}
] |
Python – Sort dictionaries list by Key’s Value list index
|
01 Aug, 2020
Given list of dictionaries, sort dictionaries on basis of Key’s index value.
Input : [{“Gfg” : [6, 7, 8], “is” : 9, “best” : 10},{“Gfg” : [2, 0, 3], “is” : 11, “best” : 19},{“Gfg” : [4, 6, 9], “is” : 16, “best” : 1}], K = “Gfg”, idx = 0Output : [{‘Gfg’: [2, 0, 3], ‘is’: 11, ‘best’: 19}, {‘Gfg’: [4, 6, 9], ‘is’: 16, ‘best’: 1}, {‘Gfg’: [6, 7, 8], ‘is’: 9, ‘best’: 10}]Explanation : 2<4<6, hence dictionary ordered in that way by 0th index of Key.
Input : [{“Gfg” : [6, 7, 8], “is” : 9, “best” : 10},{“Gfg” : [2, 0, 3], “is” : 11, “best” : 19},{“Gfg” : [4, 6, 9], “is” : 16, “best” : 1}], K = “Gfg”, idx = 1Output : [{‘Gfg’: [2, 0, 3], ‘is’: 11, ‘best’: 19}, {‘Gfg’: [4, 6, 9], ‘is’: 16, ‘best’: 1}, {‘Gfg’: [6, 7, 8], ‘is’: 9, ‘best’: 10}]Explanation : 0<6<7, hence dictionary ordered in that way by 1st index.
Method #1 : Using sorted() + lambda
The combination of above functions can be used to solve this problem. In this, we perform sort using sorted and logic based on list index is provided in lambda function.
Python3
# Python3 code to demonstrate working of # Sort dictionaries list by Key's Value list index# Using sorted() + lambda # initializing liststest_list = [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}] # printing original listprint("The original list : " + str(test_list)) # initializing K K = "Gfg" # initializing idx idx = 2 # using sorted() to perform sort in basis of 1 parameter key and # indexres = sorted(test_list, key = lambda ele: ele[K][idx]) # printing result print("The required sort order : " + str(res))
The original list : [{‘Gfg’: [6, 7, 8], ‘is’: 9, ‘best’: 10}, {‘Gfg’: [2, 0, 3], ‘is’: 11, ‘best’: 19}, {‘Gfg’: [4, 6, 9], ‘is’: 16, ‘best’: 1}]The required sort order : [{‘Gfg’: [2, 0, 3], ‘is’: 11, ‘best’: 19}, {‘Gfg’: [6, 7, 8], ‘is’: 9, ‘best’: 10}, {‘Gfg’: [4, 6, 9], ‘is’: 16, ‘best’: 1}]
Method #2 : Using sorted() + lambda (Additional parameter in case of tie)
This is modification in sorting of values, adding another parameter in case of tie of values among list.
Python3
# Python3 code to demonstrate working of # Sort dictionaries list by Key's Value list index# Using sorted() + lambda (Additional parameter in case of tie) # initializing liststest_list = [{"Gfg" : [6, 7, 9], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}] # printing original listprint("The original list : " + str(test_list)) # initializing K K = "Gfg" # initializing idx idx = 2 # initializing K2 K2 = "best" # using sorted() to perform sort in basis of 2 parameter key# inner is evaluated after the outer key in lambda orderres = sorted(sorted(test_list, key = lambda ele: ele[K2]), key = lambda ele: ele[K][idx]) # printing result print("The required sort order : " + str(res))
The original list : [{‘Gfg’: [6, 7, 9], ‘is’: 9, ‘best’: 10}, {‘Gfg’: [2, 0, 3], ‘is’: 11, ‘best’: 19}, {‘Gfg’: [4, 6, 9], ‘is’: 16, ‘best’: 1}]The required sort order : [{‘Gfg’: [2, 0, 3], ‘is’: 11, ‘best’: 19}, {‘Gfg’: [4, 6, 9], ‘is’: 16, ‘best’: 1}, {‘Gfg’: [6, 7, 9], ‘is’: 9, ‘best’: 10}]
Python dictionary-programs
Python list-programs
Python
Python Programs
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": 105,
"s": 28,
"text": "Given list of dictionaries, sort dictionaries on basis of Key’s index value."
},
{
"code": null,
"e": 476,
"s": 105,
"text": "Input : [{“Gfg” : [6, 7, 8], “is” : 9, “best” : 10},{“Gfg” : [2, 0, 3], “is” : 11, “best” : 19},{“Gfg” : [4, 6, 9], “is” : 16, “best” : 1}], K = “Gfg”, idx = 0Output : [{‘Gfg’: [2, 0, 3], ‘is’: 11, ‘best’: 19}, {‘Gfg’: [4, 6, 9], ‘is’: 16, ‘best’: 1}, {‘Gfg’: [6, 7, 8], ‘is’: 9, ‘best’: 10}]Explanation : 2<4<6, hence dictionary ordered in that way by 0th index of Key."
},
{
"code": null,
"e": 840,
"s": 476,
"text": "Input : [{“Gfg” : [6, 7, 8], “is” : 9, “best” : 10},{“Gfg” : [2, 0, 3], “is” : 11, “best” : 19},{“Gfg” : [4, 6, 9], “is” : 16, “best” : 1}], K = “Gfg”, idx = 1Output : [{‘Gfg’: [2, 0, 3], ‘is’: 11, ‘best’: 19}, {‘Gfg’: [4, 6, 9], ‘is’: 16, ‘best’: 1}, {‘Gfg’: [6, 7, 8], ‘is’: 9, ‘best’: 10}]Explanation : 0<6<7, hence dictionary ordered in that way by 1st index."
},
{
"code": null,
"e": 876,
"s": 840,
"text": "Method #1 : Using sorted() + lambda"
},
{
"code": null,
"e": 1046,
"s": 876,
"text": "The combination of above functions can be used to solve this problem. In this, we perform sort using sorted and logic based on list index is provided in lambda function."
},
{
"code": null,
"e": 1054,
"s": 1046,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Sort dictionaries list by Key's Value list index# Using sorted() + lambda # initializing liststest_list = [{\"Gfg\" : [6, 7, 8], \"is\" : 9, \"best\" : 10}, {\"Gfg\" : [2, 0, 3], \"is\" : 11, \"best\" : 19}, {\"Gfg\" : [4, 6, 9], \"is\" : 16, \"best\" : 1}] # printing original listprint(\"The original list : \" + str(test_list)) # initializing K K = \"Gfg\" # initializing idx idx = 2 # using sorted() to perform sort in basis of 1 parameter key and # indexres = sorted(test_list, key = lambda ele: ele[K][idx]) # printing result print(\"The required sort order : \" + str(res))",
"e": 1689,
"s": 1054,
"text": null
},
{
"code": null,
"e": 1984,
"s": 1689,
"text": "The original list : [{‘Gfg’: [6, 7, 8], ‘is’: 9, ‘best’: 10}, {‘Gfg’: [2, 0, 3], ‘is’: 11, ‘best’: 19}, {‘Gfg’: [4, 6, 9], ‘is’: 16, ‘best’: 1}]The required sort order : [{‘Gfg’: [2, 0, 3], ‘is’: 11, ‘best’: 19}, {‘Gfg’: [6, 7, 8], ‘is’: 9, ‘best’: 10}, {‘Gfg’: [4, 6, 9], ‘is’: 16, ‘best’: 1}]"
},
{
"code": null,
"e": 2058,
"s": 1984,
"text": "Method #2 : Using sorted() + lambda (Additional parameter in case of tie)"
},
{
"code": null,
"e": 2163,
"s": 2058,
"text": "This is modification in sorting of values, adding another parameter in case of tie of values among list."
},
{
"code": null,
"e": 2171,
"s": 2163,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Sort dictionaries list by Key's Value list index# Using sorted() + lambda (Additional parameter in case of tie) # initializing liststest_list = [{\"Gfg\" : [6, 7, 9], \"is\" : 9, \"best\" : 10}, {\"Gfg\" : [2, 0, 3], \"is\" : 11, \"best\" : 19}, {\"Gfg\" : [4, 6, 9], \"is\" : 16, \"best\" : 1}] # printing original listprint(\"The original list : \" + str(test_list)) # initializing K K = \"Gfg\" # initializing idx idx = 2 # initializing K2 K2 = \"best\" # using sorted() to perform sort in basis of 2 parameter key# inner is evaluated after the outer key in lambda orderres = sorted(sorted(test_list, key = lambda ele: ele[K2]), key = lambda ele: ele[K][idx]) # printing result print(\"The required sort order : \" + str(res))",
"e": 2954,
"s": 2171,
"text": null
},
{
"code": null,
"e": 3249,
"s": 2954,
"text": "The original list : [{‘Gfg’: [6, 7, 9], ‘is’: 9, ‘best’: 10}, {‘Gfg’: [2, 0, 3], ‘is’: 11, ‘best’: 19}, {‘Gfg’: [4, 6, 9], ‘is’: 16, ‘best’: 1}]The required sort order : [{‘Gfg’: [2, 0, 3], ‘is’: 11, ‘best’: 19}, {‘Gfg’: [4, 6, 9], ‘is’: 16, ‘best’: 1}, {‘Gfg’: [6, 7, 9], ‘is’: 9, ‘best’: 10}]"
},
{
"code": null,
"e": 3276,
"s": 3249,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 3297,
"s": 3276,
"text": "Python list-programs"
},
{
"code": null,
"e": 3304,
"s": 3297,
"text": "Python"
},
{
"code": null,
"e": 3320,
"s": 3304,
"text": "Python Programs"
}
] |
Printing Heart Pattern in C
|
In this program we will see how to print heart shaped pattern in C. The heart shape pattern will be look like this
Now if we analyze this pattern, we can find different section in this pattern. The base of the heart is an inverted triangle; the upper portion has two different peaks. Between these two peaks there is a gap. To make this pattern we have to manage these parts into our code to print the pattern like this.
Live Demo
#include<stdio.h>
int main() {
int a, b, line = 12;
for (a = line/2; a <= line; a = a+2) { //for the upper part of the heart
for (b = 1; b < line-a; b = b+2) //create space before the first peak
printf(" ");
for (b = 1; b <= a; b++) //print the first peak
printf("*");
for (b = 1; b <= line-a; b++) //create space before the first peak
printf(" ");
for (b = 1; b <= a-1; b++) //print the second peak
printf("*");
printf("\n");
}
for (a = line; a >= 0; a--) { //the base of the heart is inverted triangle
for (b = a; b < line; b++) //generate space before triangle
printf(" ");
for (b = 1; b <= ((a * 2) - 1); b++) //print the triangle
printf("*");
printf("\n");
}
}
|
[
{
"code": null,
"e": 1302,
"s": 1187,
"text": "In this program we will see how to print heart shaped pattern in C. The heart shape pattern will be look like this"
},
{
"code": null,
"e": 1608,
"s": 1302,
"text": "Now if we analyze this pattern, we can find different section in this pattern. The base of the heart is an inverted triangle; the upper portion has two different peaks. Between these two peaks there is a gap. To make this pattern we have to manage these parts into our code to print the pattern like this."
},
{
"code": null,
"e": 1619,
"s": 1608,
"text": " Live Demo"
},
{
"code": null,
"e": 2402,
"s": 1619,
"text": "#include<stdio.h>\nint main() {\n int a, b, line = 12;\n for (a = line/2; a <= line; a = a+2) { //for the upper part of the heart\n for (b = 1; b < line-a; b = b+2) //create space before the first peak\n printf(\" \");\n for (b = 1; b <= a; b++) //print the first peak\n printf(\"*\");\n for (b = 1; b <= line-a; b++) //create space before the first peak\n printf(\" \");\n for (b = 1; b <= a-1; b++) //print the second peak\n printf(\"*\");\n printf(\"\\n\");\n }\n for (a = line; a >= 0; a--) { //the base of the heart is inverted triangle\n for (b = a; b < line; b++) //generate space before triangle\n printf(\" \");\n for (b = 1; b <= ((a * 2) - 1); b++) //print the triangle\n printf(\"*\");\n printf(\"\\n\");\n }\n}"
}
] |
How to Build a Simple Alarm Setter App in Android?
|
06 Dec, 2021
In this article, we are going to see how to build a much interesting app named Alarm Setter. Alarm plays a vital role in our day-to-day life. Nowadays alarm has become our wake-up assistant. Every mobile phone is associated with an alarm app. We will create this app using android studio. Android Studio provides a great unified environment to build apps for Android phones, tablets, Android Wear, Android TV, and Android Auto because it provides a very large number of app building features and it is also very easy to use. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. In this file, we have added two items ‘TimePicker’ and ‘ToggleButton’. TimePicker is used to capture the alarm time and ToggleButton is added to set the alarm on or off. Initially, ToggleButton is set to off. It is set on when an alarm is set. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!--Added Time picker just to pick the alarm time--> <!--gravity is aligned to center--> <TimePicker android:id="@+id/timePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" /> <!--Added Toggle Button to set the alarm on or off--> <!--ByDefault toggleButton is set to false--> <ToggleButton android:id="@+id/toggleButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="20dp" android:checked="false" android:onClick="OnToggleClicked" /> <!--"OnToggleClicked" method will be implemented in MainActivity.java --> </LinearLayout>
Step 3: Working with the MainActivity.java file
Go to MainActivity.java Class. In MainActivity.java class onToggleClicked( ) method is implemented in which the current hour and the minute is set using the calendar. Alarm services are implemented using AlarmManager class. The alarm is set in such a way that it rings and vibrates repeatedly until the toggle button is turned off. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.app.AlarmManager;import android.app.PendingIntent;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.TimePicker;import android.widget.Toast;import android.widget.ToggleButton; import androidx.appcompat.app.AppCompatActivity; import java.util.Calendar; public class MainActivity extends AppCompatActivity { TimePicker alarmTimePicker; PendingIntent pendingIntent; AlarmManager alarmManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); alarmTimePicker = (TimePicker) findViewById(R.id.timePicker); alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); } // OnToggleClicked() method is implemented the time functionality public void OnToggleClicked(View view) { long time; if (((ToggleButton) view).isChecked()) { Toast.makeText(MainActivity.this, "ALARM ON", Toast.LENGTH_SHORT).show(); Calendar calendar = Calendar.getInstance(); // calendar is called to get current time in hour and minute calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour()); calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute()); // using intent i have class AlarmReceiver class which inherits // BroadcastReceiver Intent intent = new Intent(this, AlarmReceiver.class); // we call broadcast using pendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); time = (calendar.getTimeInMillis() - (calendar.getTimeInMillis() % 60000)); if (System.currentTimeMillis() > time) { // setting time as AM and PM if (calendar.AM_PM == 0) time = time + (1000 * 60 * 60 * 12); else time = time + (1000 * 60 * 60 * 24); } // Alarm rings continuously until toggle button is turned off alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, 10000, pendingIntent); // alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (time * 1000), pendingIntent); } else { alarmManager.cancel(pendingIntent); Toast.makeText(MainActivity.this, "ALARM OFF", Toast.LENGTH_SHORT).show(); } }}
Step 4: Working with BroadCastReceiver (AlarmReceiver) class
Create a new java class named “AlarmReceiver.java” at the same place where MainActivity.java class resides. In this class onReceive() method is implemented. Here we have added vibration functionality and a default ringtone that starts to vibrate and ring when the alarm time is scheduled. Below is the code for the AlarmReceiver.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.media.Ringtone;import android.media.RingtoneManager;import android.net.Uri;import android.os.Build;import android.os.Vibrator;import android.widget.Toast; import androidx.annotation.RequiresApi; public class AlarmReceiver extends BroadcastReceiver { @RequiresApi(api = Build.VERSION_CODES.Q) @Override // implement onReceive() method public void onReceive(Context context, Intent intent) { // we will use vibrator first Vibrator vibrator = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE); vibrator.vibrate(4000); Toast.makeText(context, "Alarm! Wake up! Wake up!", Toast.LENGTH_LONG).show(); Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); if (alarmUri == null) { alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); } // setting default ringtone Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri); // play ringtone ringtone.play(); }}
Step 5: Playing with colors
Go to the “values” folder first then choose the colors.xml file. In the colors.xml file, you can keep colors of your choice as many as you want to use in your app. You have to just give the name and put the color code of the respective colors. I have kept the AppBar color as “#0F9D58” which we have named as “colorPrimary”.
XML
<?xml version="1.0" encoding="utf-8"?><resources> <color name="colorPrimary">#0F9D58</color> <color name="colorPrimaryDark">#0F4C2E</color> <color name="colorAccent">#9D0F9B</color></resources>
Step 6: Changing theme of the app
Go to the “values” folder first then choose the themes.xml file. In the theme.xml file, we have used “Theme.AppCompat.Light.DarkActionBar” which is a light theme with a dark ActionBar. We can use a light theme with a light action bar using “Theme.AppCompat.Light.LightActionBar”, it all depends on our choice and need.
XML
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> </resources>
Step 7: Adding permission in “AndroidManifest.xml”
Go to the “AndroidManifest.xml” file. A BroadcastReceiver is registered in AndroidManifest.xml by adding a receiver section after the application section is over. Also, give permission to vibrate using:
<uses-permission android:name=”android.permission.VIBRATE” />
Output:
Here we have manually set the alarm time. You can also set it by adjusting the clock showing in front. You will have to wait for the alarm time. It will continuously show “Alarm! Wake up! Wake up!” and rings and vibrates until the toggle-button is turned off. You can get Source code on the given GitHub link below: https://github.com/Babitababy/Alarm_setter
varshagumber28
Picked
Android
Java
Project
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
How to Communicate Between Fragments in Android?
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine 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": "\n06 Dec, 2021"
},
{
"code": null,
"e": 746,
"s": 54,
"text": "In this article, we are going to see how to build a much interesting app named Alarm Setter. Alarm plays a vital role in our day-to-day life. Nowadays alarm has become our wake-up assistant. Every mobile phone is associated with an alarm app. We will create this app using android studio. Android Studio provides a great unified environment to build apps for Android phones, tablets, Android Wear, Android TV, and Android Auto because it provides a very large number of app building features and it is also very easy to use. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 775,
"s": 746,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 937,
"s": 775,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 985,
"s": 937,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1371,
"s": 985,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. In this file, we have added two items ‘TimePicker’ and ‘ToggleButton’. TimePicker is used to capture the alarm time and ToggleButton is added to set the alarm on or off. Initially, ToggleButton is set to off. It is set on when an alarm is set. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 1375,
"s": 1371,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <!--Added Time picker just to pick the alarm time--> <!--gravity is aligned to center--> <TimePicker android:id=\"@+id/timePicker\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" /> <!--Added Toggle Button to set the alarm on or off--> <!--ByDefault toggleButton is set to false--> <ToggleButton android:id=\"@+id/toggleButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_margin=\"20dp\" android:checked=\"false\" android:onClick=\"OnToggleClicked\" /> <!--\"OnToggleClicked\" method will be implemented in MainActivity.java --> </LinearLayout>",
"e": 2381,
"s": 1375,
"text": null
},
{
"code": null,
"e": 2429,
"s": 2381,
"text": "Step 3: Working with the MainActivity.java file"
},
{
"code": null,
"e": 2885,
"s": 2429,
"text": "Go to MainActivity.java Class. In MainActivity.java class onToggleClicked( ) method is implemented in which the current hour and the minute is set using the calendar. Alarm services are implemented using AlarmManager class. The alarm is set in such a way that it rings and vibrates repeatedly until the toggle button is turned off. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 2890,
"s": 2885,
"text": "Java"
},
{
"code": "import android.app.AlarmManager;import android.app.PendingIntent;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.TimePicker;import android.widget.Toast;import android.widget.ToggleButton; import androidx.appcompat.app.AppCompatActivity; import java.util.Calendar; public class MainActivity extends AppCompatActivity { TimePicker alarmTimePicker; PendingIntent pendingIntent; AlarmManager alarmManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); alarmTimePicker = (TimePicker) findViewById(R.id.timePicker); alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); } // OnToggleClicked() method is implemented the time functionality public void OnToggleClicked(View view) { long time; if (((ToggleButton) view).isChecked()) { Toast.makeText(MainActivity.this, \"ALARM ON\", Toast.LENGTH_SHORT).show(); Calendar calendar = Calendar.getInstance(); // calendar is called to get current time in hour and minute calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour()); calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute()); // using intent i have class AlarmReceiver class which inherits // BroadcastReceiver Intent intent = new Intent(this, AlarmReceiver.class); // we call broadcast using pendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); time = (calendar.getTimeInMillis() - (calendar.getTimeInMillis() % 60000)); if (System.currentTimeMillis() > time) { // setting time as AM and PM if (calendar.AM_PM == 0) time = time + (1000 * 60 * 60 * 12); else time = time + (1000 * 60 * 60 * 24); } // Alarm rings continuously until toggle button is turned off alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, 10000, pendingIntent); // alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (time * 1000), pendingIntent); } else { alarmManager.cancel(pendingIntent); Toast.makeText(MainActivity.this, \"ALARM OFF\", Toast.LENGTH_SHORT).show(); } }}",
"e": 5339,
"s": 2890,
"text": null
},
{
"code": null,
"e": 5400,
"s": 5339,
"text": "Step 4: Working with BroadCastReceiver (AlarmReceiver) class"
},
{
"code": null,
"e": 5814,
"s": 5400,
"text": "Create a new java class named “AlarmReceiver.java” at the same place where MainActivity.java class resides. In this class onReceive() method is implemented. Here we have added vibration functionality and a default ringtone that starts to vibrate and ring when the alarm time is scheduled. Below is the code for the AlarmReceiver.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 5819,
"s": 5814,
"text": "Java"
},
{
"code": "import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.media.Ringtone;import android.media.RingtoneManager;import android.net.Uri;import android.os.Build;import android.os.Vibrator;import android.widget.Toast; import androidx.annotation.RequiresApi; public class AlarmReceiver extends BroadcastReceiver { @RequiresApi(api = Build.VERSION_CODES.Q) @Override // implement onReceive() method public void onReceive(Context context, Intent intent) { // we will use vibrator first Vibrator vibrator = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE); vibrator.vibrate(4000); Toast.makeText(context, \"Alarm! Wake up! Wake up!\", Toast.LENGTH_LONG).show(); Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); if (alarmUri == null) { alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); } // setting default ringtone Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri); // play ringtone ringtone.play(); }}",
"e": 6973,
"s": 5819,
"text": null
},
{
"code": null,
"e": 7001,
"s": 6973,
"text": "Step 5: Playing with colors"
},
{
"code": null,
"e": 7327,
"s": 7001,
"text": "Go to the “values” folder first then choose the colors.xml file. In the colors.xml file, you can keep colors of your choice as many as you want to use in your app. You have to just give the name and put the color code of the respective colors. I have kept the AppBar color as “#0F9D58” which we have named as “colorPrimary”. "
},
{
"code": null,
"e": 7331,
"s": 7327,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"colorPrimary\">#0F9D58</color> <color name=\"colorPrimaryDark\">#0F4C2E</color> <color name=\"colorAccent\">#9D0F9B</color></resources>",
"e": 7534,
"s": 7331,
"text": null
},
{
"code": null,
"e": 7568,
"s": 7534,
"text": "Step 6: Changing theme of the app"
},
{
"code": null,
"e": 7888,
"s": 7568,
"text": "Go to the “values” folder first then choose the themes.xml file. In the theme.xml file, we have used “Theme.AppCompat.Light.DarkActionBar” which is a light theme with a dark ActionBar. We can use a light theme with a light action bar using “Theme.AppCompat.Light.LightActionBar”, it all depends on our choice and need. "
},
{
"code": null,
"e": 7892,
"s": 7888,
"text": "XML"
},
{
"code": "<resources> <!-- Base application theme. --> <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\"> <!-- Customize your theme here. --> <item name=\"colorPrimary\">@color/colorPrimary</item> <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item> <item name=\"colorAccent\">@color/colorAccent</item> </style> </resources>",
"e": 8271,
"s": 7892,
"text": null
},
{
"code": null,
"e": 8322,
"s": 8271,
"text": "Step 7: Adding permission in “AndroidManifest.xml”"
},
{
"code": null,
"e": 8525,
"s": 8322,
"text": "Go to the “AndroidManifest.xml” file. A BroadcastReceiver is registered in AndroidManifest.xml by adding a receiver section after the application section is over. Also, give permission to vibrate using:"
},
{
"code": null,
"e": 8587,
"s": 8525,
"text": "<uses-permission android:name=”android.permission.VIBRATE” />"
},
{
"code": null,
"e": 8595,
"s": 8587,
"text": "Output:"
},
{
"code": null,
"e": 8954,
"s": 8595,
"text": "Here we have manually set the alarm time. You can also set it by adjusting the clock showing in front. You will have to wait for the alarm time. It will continuously show “Alarm! Wake up! Wake up!” and rings and vibrates until the toggle-button is turned off. You can get Source code on the given GitHub link below: https://github.com/Babitababy/Alarm_setter"
},
{
"code": null,
"e": 8969,
"s": 8954,
"text": "varshagumber28"
},
{
"code": null,
"e": 8976,
"s": 8969,
"text": "Picked"
},
{
"code": null,
"e": 8984,
"s": 8976,
"text": "Android"
},
{
"code": null,
"e": 8989,
"s": 8984,
"text": "Java"
},
{
"code": null,
"e": 8997,
"s": 8989,
"text": "Project"
},
{
"code": null,
"e": 9002,
"s": 8997,
"text": "Java"
},
{
"code": null,
"e": 9010,
"s": 9002,
"text": "Android"
},
{
"code": null,
"e": 9108,
"s": 9010,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9177,
"s": 9108,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 9209,
"s": 9177,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 9258,
"s": 9209,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 9297,
"s": 9258,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 9339,
"s": 9297,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 9354,
"s": 9339,
"text": "Arrays in Java"
},
{
"code": null,
"e": 9398,
"s": 9354,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 9434,
"s": 9398,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 9485,
"s": 9434,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Number of cyclic elements in an array where we can jump according to value
|
20 May, 2021
Given a array arr[] of n integers. For every value arr[i], we can move to arr[i] + 1 clockwise considering array elements in cycle. We need to count cyclic elements in the array. An element is cyclic if starting from it and moving to arr[i] + 1 leads to same element.
Examples:
Input : arr[] = {1, 1, 1, 1}
Output : 4
All 4 elements are cyclic elements.
1 -> 3 -> 1
2 -> 4 -> 2
3 -> 1 -> 3
4 -> 2 -> 4
Input : arr[] = {3, 0, 0, 0}
Output : 1
There is one cyclic point 1,
1 -> 1
The path covered starting from 2 is
2 -> 3 -> 4 -> 1 -> 1.
The path covered starting from 3 is
2 -> 3 -> 4 -> 1 -> 1.
The path covered starting from 4 is
4 -> 1 -> 1
One simple solution is to check all elements one by one. We follow simple path starting from every element arr[i], we go to arr[i] + 1. If we come back to a visited element other than arr[i], we do not count arr[i]. Time complexity of this solution is O(n2)
An efficient solution is based on below steps. 1) Create a directed graph using array indexes as nodes. We add an edge from i to node (arr[i] + 1)%n. 2) Once a graph is created we find all strongly connected components using Kosaraju’s Algorithm 3) We finally return sum of counts of nodes in individual strongly connected component.
C++
Java
Python3
C#
Javascript
// C++ program to count cyclic points// in an array using Kosaraju's Algorithm#include <bits/stdc++.h>using namespace std; // Most of the code is taken from below link// https://www.geeksforgeeks.org/strongly-connected-components/class Graph { int V; list<int>* adj; void fillOrder(int v, bool visited[], stack<int>& Stack); int DFSUtil(int v, bool visited[]); public: Graph(int V); void addEdge(int v, int w); int countSCCNodes(); Graph getTranspose();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} // Counts number of nodes reachable// from vint Graph::DFSUtil(int v, bool visited[]){ visited[v] = true; int ans = 1; list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) ans += DFSUtil(*i, visited); return ans;} Graph Graph::getTranspose(){ Graph g(V); for (int v = 0; v < V; v++) { list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) g.adj[*i].push_back(v); } return g;} void Graph::addEdge(int v, int w){ adj[v].push_back(w);} void Graph::fillOrder(int v, bool visited[], stack<int>& Stack){ visited[v] = true; list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) fillOrder(*i, visited, Stack); Stack.push(v);} // This function mainly returns total count of// nodes in individual SCCs using Kosaraju's// algorithm.int Graph::countSCCNodes(){ int res = 0; stack<int> Stack; bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; for (int i = 0; i < V; i++) if (visited[i] == false) fillOrder(i, visited, Stack); Graph gr = getTranspose(); for (int i = 0; i < V; i++) visited[i] = false; while (Stack.empty() == false) { int v = Stack.top(); Stack.pop(); if (visited[v] == false) { int ans = gr.DFSUtil(v, visited); if (ans > 1) res += ans; } } return res;} // Returns count of cyclic elements in arr[]int countCyclic(int arr[], int n){ int res = 0; // Create a graph of array elements Graph g(n + 1); for (int i = 1; i <= n; i++) { int x = arr[i-1]; // If i + arr[i-1] jumps beyond last // element, we take mod considering // cyclic array int v = (x + i) % n + 1; // If there is a self loop, we // increment count of cyclic points. if (i == v) res++; g.addEdge(i, v); } // Add nodes of strongly connected components // of size more than 1. res += g.countSCCNodes(); return res;} // Driver codeint main(){ int arr[] = {1, 1, 1, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << countCyclic(arr, n); return 0;}
// Python3 program to count cyclic points// in an array using Kosaraju's Algorithm // Counts number of nodes reachable// from vimport java.io.*;import java.util.*;class GFG{ static boolean[] visited = new boolean[100]; static Stack<Integer> stack = new Stack<Integer>(); static ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(); static int DFSUtil(int v) { visited[v] = true; int ans = 1; for(int i: adj.get(v)) { if(!visited[i]) { ans += DFSUtil(i); } } return ans; } static void getTranspose() { for(int v = 0; v < 5; v++) { for(int i : adj.get(v)) { adj.get(i).add(v); } } } static void addEdge(int v, int w) { adj.get(v).add(w); } static void fillOrder(int v) { visited[v] = true; for(int i: adj.get(v)) { if(!visited[i]) { fillOrder(i); } } stack.add(v); } // This function mainly returns total count of // nodes in individual SCCs using Kosaraju's // algorithm. static int countSCCNodes() { int res = 0; // stack<int> Stack; // bool* visited = new bool[V]; for(int i = 0; i < 5; i++) { if(visited[i] == false) { fillOrder(i); } } getTranspose(); for(int i = 0; i < 5; i++) { visited[i] = false; } while(stack.size() > 0) { int v = stack.get(stack.size() - 1); stack.remove(stack.size() - 1); if (visited[v] == false) { int ans = DFSUtil(v); if (ans > 1) { res += ans; } } } return res; } // Returns count of cyclic elements in arr[] static int countCyclic(int[] arr, int n) { int res = 0; // Create a graph of array elements for(int i = 1; i < n + 1; i++) { int x = arr[i - 1]; // If i + arr[i-1] jumps beyond last // element, we take mod considering // cyclic array int v = (x + i) % n + 1; // If there is a self loop, we // increment count of cyclic points. if (i == v) res++; addEdge(i, v); } // Add nodes of strongly connected components // of size more than 1. res += countSCCNodes(); return res; } // Driver code public static void main (String[] args) { int arr[] = {1, 1, 1, 1}; int n = arr.length; for(int i = 0; i < 100; i++) { adj.add(new ArrayList<Integer>()); } System.out.println(countCyclic(arr, n)); }} // This code is contributed by avanitrachhadiya2155
# Python3 program to count cyclic points# in an array using Kosaraju's Algorithm # Counts number of nodes reachable# from vdef DFSUtil(v): global visited, adj visited[v] = True ans = 1 for i in adj[v]: if (not visited[i]): ans += DFSUtil(i) return ans def getTranspose(): global visited, adj for v in range(5): for i in adj[v]: adj[i].append(v) def addEdge(v, w): global visited, adj adj[v].append(w) def fillOrder(v): global Stack, adj, visited visited[v] = True for i in adj[v]: if (not visited[i]): fillOrder(i) Stack.append(v) # This function mainly returns total count of# nodes in individual SCCs using Kosaraju's# algorithm.def countSCCNodes(): global adj, visited, S res = 0 #stack<int> Stack; #bool* visited = new bool[V]; for i in range(5): if (visited[i] == False): fillOrder(i) getTranspose() for i in range(5): visited[i] = False while (len(Stack) > 0): v = Stack[-1] del Stack[-1] if (visited[v] == False): ans = DFSUtil(v) if (ans > 1): res += ans return res # Returns count of cyclic elements in arr[]def countCyclic(arr, n): global adj res = 0 # Create a graph of array elements for i in range(1, n + 1): x = arr[i - 1] # If i + arr[i-1] jumps beyond last # element, we take mod considering # cyclic array v = (x + i) % n + 1 # If there is a self loop, we # increment count of cyclic points. if (i == v): res += 1 addEdge(i, v) # Add nodes of strongly connected components # of size more than 1. res += countSCCNodes() return res # Driver codeif __name__ == '__main__': adj = [[] for i in range(100)] visited = [False for i in range(100)] arr = [ 1, 1, 1, 1 ] Stack = [] n = len(arr) print(countCyclic(arr, n)) # This code is contributed by mohit kumar 29
// C# program to count cyclic points// in an array using Kosaraju's Algorithm // Counts number of nodes reachable// from vusing System;using System.Collections.Generic;public class GFG{ static bool[] visited = new bool[100]; static List<int> stack = new List<int>(); static List<List<int>> adj = new List<List<int>>(); static int DFSUtil(int v) { visited[v] = true; int ans = 1; foreach(int i in adj[v]) { if(!visited[i]) { ans += DFSUtil(i); } } return ans; } static void getTranspose() { for(int v = 0; v < 5; v++) { foreach(int i in adj[v]) { adj[i].Add(v); } } } static void addEdge(int v, int w) { adj[v].Add(w); } static void fillOrder(int v) { visited[v] = true; foreach(int i in adj[v]) { if(!visited[i]) { fillOrder(i); } } stack.Add(v); } // This function mainly returns total count of // nodes in individual SCCs using Kosaraju's // algorithm. static int countSCCNodes() { int res = 0; // stack<int> Stack; // bool* visited = new bool[V]; for(int i = 0; i < 5; i++) { if(visited[i] == false) { fillOrder(i); } } getTranspose(); for(int i = 0; i < 5; i++) { visited[i] = false; } while(stack.Count > 0) { int v=stack[stack.Count - 1]; stack.Remove(stack.Count - 1); if (visited[v] == false) { int ans = DFSUtil(v); if (ans > 1) { res += ans; } } } return res; } // Returns count of cyclic elements in arr[] static int countCyclic(int[] arr, int n) { int res = 0; // Create a graph of array elements for(int i = 1; i < n + 1; i++) { int x = arr[i - 1]; // If i + arr[i-1] jumps beyond last // element, we take mod considering //cyclic array int v = (x + i) % n + 1; // If there is a self loop, we // increment count of cyclic points. if (i == v) res++; addEdge(i, v); } // Add nodes of strongly connected components // of size more than 1. res += countSCCNodes(); return res; } // Driver code static public void Main () { int[] arr = {1, 1, 1, 1}; int n = arr.Length; for(int i = 0; i < 100; i++) { adj.Add(new List<int>()); } Console.WriteLine(countCyclic(arr, n)); }} // This code is contributed by rag2127
<script>// Javascript program to count cyclic points// in an array using Kosaraju's Algorithm // Counts number of nodes reachable// from v let visited = new Array(100); for(let i=0;i<100;i++) { visited[i]=false; } let stack = []; let adj=[]; function DFSUtil(v){ visited[v] = true; let ans = 1; for(let i=0;i<adj[v].length;i++) { if(!visited[adj[v][i]]) { ans += DFSUtil(adj[v][i]); } } return ans;} function getTranspose(){ for(let v = 0; v < 5; v++) { for(let i=0;i<adj[v].length;i++) { adj[adj[v][i]].push(v); } }} function addEdge(v,w){ adj[v].push(w);} function fillOrder(v){ visited[v] = true; for(let i=0;i<adj[v].length;i++) { if(!visited[adj[v][i]]) { fillOrder(adj[v][i]); } } stack.push(v);} // This function mainly returns total count of // nodes in individual SCCs using Kosaraju's // algorithm.function countSCCNodes(){let res = 0; // stack<int> Stack; // bool* visited = new bool[V]; for(let i = 0; i < 5; i++) { if(visited[i] == false) { fillOrder(i); } } getTranspose(); for(let i = 0; i < 5; i++) { visited[i] = false; } while(stack.length > 0) { let v = stack[stack.length - 1]; stack.pop(); if (visited[v] == false) { let ans = DFSUtil(v); if (ans > 1) { res += ans; } } } return res;} // Returns count of cyclic elements in arr[]function countCyclic(arr,n){ let res = 0; // Create a graph of array elements for(let i = 1; i < n + 1; i++) { let x = arr[i - 1]; // If i + arr[i-1] jumps beyond last // element, we take mod considering // cyclic array let v = (x + i) % n + 1; // If there is a self loop, we // increment count of cyclic points. if (i == v) res++; addEdge(i, v); } // Add nodes of strongly connected components // of size more than 1. res += countSCCNodes(); return res;} // Driver codelet arr=[1, 1, 1, 1];let n = arr.length;for(let i = 0; i < 100; i++){ adj.push([]); }document.write(countCyclic(arr, n)); // This code is contributed by unknown2108</script>
Output:
4
Time Complexity : O(n) Auxiliary space : O(n) Note that there are only O(n) edges.
This article is contributed by Mohak Agrawal. 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.
mohit kumar 29
avanitrachhadiya2155
rag2127
unknown2108
graph-connectivity
Arrays
Graph
Arrays
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Breadth First Search or BFS for a Graph
Depth First Search or DFS for a Graph
Graph and its representations
Topological Sorting
Detect Cycle in a Directed Graph
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 May, 2021"
},
{
"code": null,
"e": 320,
"s": 52,
"text": "Given a array arr[] of n integers. For every value arr[i], we can move to arr[i] + 1 clockwise considering array elements in cycle. We need to count cyclic elements in the array. An element is cyclic if starting from it and moving to arr[i] + 1 leads to same element."
},
{
"code": null,
"e": 332,
"s": 320,
"text": "Examples: "
},
{
"code": null,
"e": 701,
"s": 332,
"text": "Input : arr[] = {1, 1, 1, 1}\nOutput : 4\nAll 4 elements are cyclic elements.\n1 -> 3 -> 1\n2 -> 4 -> 2\n3 -> 1 -> 3\n4 -> 2 -> 4\n\nInput : arr[] = {3, 0, 0, 0}\nOutput : 1\nThere is one cyclic point 1,\n1 -> 1\nThe path covered starting from 2 is\n2 -> 3 -> 4 -> 1 -> 1.\n\nThe path covered starting from 3 is\n2 -> 3 -> 4 -> 1 -> 1.\n\nThe path covered starting from 4 is\n4 -> 1 -> 1"
},
{
"code": null,
"e": 959,
"s": 701,
"text": "One simple solution is to check all elements one by one. We follow simple path starting from every element arr[i], we go to arr[i] + 1. If we come back to a visited element other than arr[i], we do not count arr[i]. Time complexity of this solution is O(n2)"
},
{
"code": null,
"e": 1293,
"s": 959,
"text": "An efficient solution is based on below steps. 1) Create a directed graph using array indexes as nodes. We add an edge from i to node (arr[i] + 1)%n. 2) Once a graph is created we find all strongly connected components using Kosaraju’s Algorithm 3) We finally return sum of counts of nodes in individual strongly connected component."
},
{
"code": null,
"e": 1297,
"s": 1293,
"text": "C++"
},
{
"code": null,
"e": 1302,
"s": 1297,
"text": "Java"
},
{
"code": null,
"e": 1310,
"s": 1302,
"text": "Python3"
},
{
"code": null,
"e": 1313,
"s": 1310,
"text": "C#"
},
{
"code": null,
"e": 1324,
"s": 1313,
"text": "Javascript"
},
{
"code": "// C++ program to count cyclic points// in an array using Kosaraju's Algorithm#include <bits/stdc++.h>using namespace std; // Most of the code is taken from below link// https://www.geeksforgeeks.org/strongly-connected-components/class Graph { int V; list<int>* adj; void fillOrder(int v, bool visited[], stack<int>& Stack); int DFSUtil(int v, bool visited[]); public: Graph(int V); void addEdge(int v, int w); int countSCCNodes(); Graph getTranspose();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} // Counts number of nodes reachable// from vint Graph::DFSUtil(int v, bool visited[]){ visited[v] = true; int ans = 1; list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) ans += DFSUtil(*i, visited); return ans;} Graph Graph::getTranspose(){ Graph g(V); for (int v = 0; v < V; v++) { list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) g.adj[*i].push_back(v); } return g;} void Graph::addEdge(int v, int w){ adj[v].push_back(w);} void Graph::fillOrder(int v, bool visited[], stack<int>& Stack){ visited[v] = true; list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) fillOrder(*i, visited, Stack); Stack.push(v);} // This function mainly returns total count of// nodes in individual SCCs using Kosaraju's// algorithm.int Graph::countSCCNodes(){ int res = 0; stack<int> Stack; bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; for (int i = 0; i < V; i++) if (visited[i] == false) fillOrder(i, visited, Stack); Graph gr = getTranspose(); for (int i = 0; i < V; i++) visited[i] = false; while (Stack.empty() == false) { int v = Stack.top(); Stack.pop(); if (visited[v] == false) { int ans = gr.DFSUtil(v, visited); if (ans > 1) res += ans; } } return res;} // Returns count of cyclic elements in arr[]int countCyclic(int arr[], int n){ int res = 0; // Create a graph of array elements Graph g(n + 1); for (int i = 1; i <= n; i++) { int x = arr[i-1]; // If i + arr[i-1] jumps beyond last // element, we take mod considering // cyclic array int v = (x + i) % n + 1; // If there is a self loop, we // increment count of cyclic points. if (i == v) res++; g.addEdge(i, v); } // Add nodes of strongly connected components // of size more than 1. res += g.countSCCNodes(); return res;} // Driver codeint main(){ int arr[] = {1, 1, 1, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << countCyclic(arr, n); return 0;}",
"e": 4192,
"s": 1324,
"text": null
},
{
"code": "// Python3 program to count cyclic points// in an array using Kosaraju's Algorithm // Counts number of nodes reachable// from vimport java.io.*;import java.util.*;class GFG{ static boolean[] visited = new boolean[100]; static Stack<Integer> stack = new Stack<Integer>(); static ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(); static int DFSUtil(int v) { visited[v] = true; int ans = 1; for(int i: adj.get(v)) { if(!visited[i]) { ans += DFSUtil(i); } } return ans; } static void getTranspose() { for(int v = 0; v < 5; v++) { for(int i : adj.get(v)) { adj.get(i).add(v); } } } static void addEdge(int v, int w) { adj.get(v).add(w); } static void fillOrder(int v) { visited[v] = true; for(int i: adj.get(v)) { if(!visited[i]) { fillOrder(i); } } stack.add(v); } // This function mainly returns total count of // nodes in individual SCCs using Kosaraju's // algorithm. static int countSCCNodes() { int res = 0; // stack<int> Stack; // bool* visited = new bool[V]; for(int i = 0; i < 5; i++) { if(visited[i] == false) { fillOrder(i); } } getTranspose(); for(int i = 0; i < 5; i++) { visited[i] = false; } while(stack.size() > 0) { int v = stack.get(stack.size() - 1); stack.remove(stack.size() - 1); if (visited[v] == false) { int ans = DFSUtil(v); if (ans > 1) { res += ans; } } } return res; } // Returns count of cyclic elements in arr[] static int countCyclic(int[] arr, int n) { int res = 0; // Create a graph of array elements for(int i = 1; i < n + 1; i++) { int x = arr[i - 1]; // If i + arr[i-1] jumps beyond last // element, we take mod considering // cyclic array int v = (x + i) % n + 1; // If there is a self loop, we // increment count of cyclic points. if (i == v) res++; addEdge(i, v); } // Add nodes of strongly connected components // of size more than 1. res += countSCCNodes(); return res; } // Driver code public static void main (String[] args) { int arr[] = {1, 1, 1, 1}; int n = arr.length; for(int i = 0; i < 100; i++) { adj.add(new ArrayList<Integer>()); } System.out.println(countCyclic(arr, n)); }} // This code is contributed by avanitrachhadiya2155",
"e": 6678,
"s": 4192,
"text": null
},
{
"code": "# Python3 program to count cyclic points# in an array using Kosaraju's Algorithm # Counts number of nodes reachable# from vdef DFSUtil(v): global visited, adj visited[v] = True ans = 1 for i in adj[v]: if (not visited[i]): ans += DFSUtil(i) return ans def getTranspose(): global visited, adj for v in range(5): for i in adj[v]: adj[i].append(v) def addEdge(v, w): global visited, adj adj[v].append(w) def fillOrder(v): global Stack, adj, visited visited[v] = True for i in adj[v]: if (not visited[i]): fillOrder(i) Stack.append(v) # This function mainly returns total count of# nodes in individual SCCs using Kosaraju's# algorithm.def countSCCNodes(): global adj, visited, S res = 0 #stack<int> Stack; #bool* visited = new bool[V]; for i in range(5): if (visited[i] == False): fillOrder(i) getTranspose() for i in range(5): visited[i] = False while (len(Stack) > 0): v = Stack[-1] del Stack[-1] if (visited[v] == False): ans = DFSUtil(v) if (ans > 1): res += ans return res # Returns count of cyclic elements in arr[]def countCyclic(arr, n): global adj res = 0 # Create a graph of array elements for i in range(1, n + 1): x = arr[i - 1] # If i + arr[i-1] jumps beyond last # element, we take mod considering # cyclic array v = (x + i) % n + 1 # If there is a self loop, we # increment count of cyclic points. if (i == v): res += 1 addEdge(i, v) # Add nodes of strongly connected components # of size more than 1. res += countSCCNodes() return res # Driver codeif __name__ == '__main__': adj = [[] for i in range(100)] visited = [False for i in range(100)] arr = [ 1, 1, 1, 1 ] Stack = [] n = len(arr) print(countCyclic(arr, n)) # This code is contributed by mohit kumar 29",
"e": 8777,
"s": 6678,
"text": null
},
{
"code": "// C# program to count cyclic points// in an array using Kosaraju's Algorithm // Counts number of nodes reachable// from vusing System;using System.Collections.Generic;public class GFG{ static bool[] visited = new bool[100]; static List<int> stack = new List<int>(); static List<List<int>> adj = new List<List<int>>(); static int DFSUtil(int v) { visited[v] = true; int ans = 1; foreach(int i in adj[v]) { if(!visited[i]) { ans += DFSUtil(i); } } return ans; } static void getTranspose() { for(int v = 0; v < 5; v++) { foreach(int i in adj[v]) { adj[i].Add(v); } } } static void addEdge(int v, int w) { adj[v].Add(w); } static void fillOrder(int v) { visited[v] = true; foreach(int i in adj[v]) { if(!visited[i]) { fillOrder(i); } } stack.Add(v); } // This function mainly returns total count of // nodes in individual SCCs using Kosaraju's // algorithm. static int countSCCNodes() { int res = 0; // stack<int> Stack; // bool* visited = new bool[V]; for(int i = 0; i < 5; i++) { if(visited[i] == false) { fillOrder(i); } } getTranspose(); for(int i = 0; i < 5; i++) { visited[i] = false; } while(stack.Count > 0) { int v=stack[stack.Count - 1]; stack.Remove(stack.Count - 1); if (visited[v] == false) { int ans = DFSUtil(v); if (ans > 1) { res += ans; } } } return res; } // Returns count of cyclic elements in arr[] static int countCyclic(int[] arr, int n) { int res = 0; // Create a graph of array elements for(int i = 1; i < n + 1; i++) { int x = arr[i - 1]; // If i + arr[i-1] jumps beyond last // element, we take mod considering //cyclic array int v = (x + i) % n + 1; // If there is a self loop, we // increment count of cyclic points. if (i == v) res++; addEdge(i, v); } // Add nodes of strongly connected components // of size more than 1. res += countSCCNodes(); return res; } // Driver code static public void Main () { int[] arr = {1, 1, 1, 1}; int n = arr.Length; for(int i = 0; i < 100; i++) { adj.Add(new List<int>()); } Console.WriteLine(countCyclic(arr, n)); }} // This code is contributed by rag2127",
"e": 11180,
"s": 8777,
"text": null
},
{
"code": "<script>// Javascript program to count cyclic points// in an array using Kosaraju's Algorithm // Counts number of nodes reachable// from v let visited = new Array(100); for(let i=0;i<100;i++) { visited[i]=false; } let stack = []; let adj=[]; function DFSUtil(v){ visited[v] = true; let ans = 1; for(let i=0;i<adj[v].length;i++) { if(!visited[adj[v][i]]) { ans += DFSUtil(adj[v][i]); } } return ans;} function getTranspose(){ for(let v = 0; v < 5; v++) { for(let i=0;i<adj[v].length;i++) { adj[adj[v][i]].push(v); } }} function addEdge(v,w){ adj[v].push(w);} function fillOrder(v){ visited[v] = true; for(let i=0;i<adj[v].length;i++) { if(!visited[adj[v][i]]) { fillOrder(adj[v][i]); } } stack.push(v);} // This function mainly returns total count of // nodes in individual SCCs using Kosaraju's // algorithm.function countSCCNodes(){let res = 0; // stack<int> Stack; // bool* visited = new bool[V]; for(let i = 0; i < 5; i++) { if(visited[i] == false) { fillOrder(i); } } getTranspose(); for(let i = 0; i < 5; i++) { visited[i] = false; } while(stack.length > 0) { let v = stack[stack.length - 1]; stack.pop(); if (visited[v] == false) { let ans = DFSUtil(v); if (ans > 1) { res += ans; } } } return res;} // Returns count of cyclic elements in arr[]function countCyclic(arr,n){ let res = 0; // Create a graph of array elements for(let i = 1; i < n + 1; i++) { let x = arr[i - 1]; // If i + arr[i-1] jumps beyond last // element, we take mod considering // cyclic array let v = (x + i) % n + 1; // If there is a self loop, we // increment count of cyclic points. if (i == v) res++; addEdge(i, v); } // Add nodes of strongly connected components // of size more than 1. res += countSCCNodes(); return res;} // Driver codelet arr=[1, 1, 1, 1];let n = arr.length;for(let i = 0; i < 100; i++){ adj.push([]); }document.write(countCyclic(arr, n)); // This code is contributed by unknown2108</script>",
"e": 13452,
"s": 11180,
"text": null
},
{
"code": null,
"e": 13461,
"s": 13452,
"text": "Output: "
},
{
"code": null,
"e": 13463,
"s": 13461,
"text": "4"
},
{
"code": null,
"e": 13546,
"s": 13463,
"text": "Time Complexity : O(n) Auxiliary space : O(n) Note that there are only O(n) edges."
},
{
"code": null,
"e": 13967,
"s": 13546,
"text": "This article is contributed by Mohak Agrawal. 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. "
},
{
"code": null,
"e": 13982,
"s": 13967,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 14003,
"s": 13982,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 14011,
"s": 14003,
"text": "rag2127"
},
{
"code": null,
"e": 14023,
"s": 14011,
"text": "unknown2108"
},
{
"code": null,
"e": 14042,
"s": 14023,
"text": "graph-connectivity"
},
{
"code": null,
"e": 14049,
"s": 14042,
"text": "Arrays"
},
{
"code": null,
"e": 14055,
"s": 14049,
"text": "Graph"
},
{
"code": null,
"e": 14062,
"s": 14055,
"text": "Arrays"
},
{
"code": null,
"e": 14068,
"s": 14062,
"text": "Graph"
},
{
"code": null,
"e": 14166,
"s": 14068,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14234,
"s": 14166,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 14278,
"s": 14234,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 14310,
"s": 14278,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 14358,
"s": 14310,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 14372,
"s": 14358,
"text": "Linear Search"
},
{
"code": null,
"e": 14412,
"s": 14372,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 14450,
"s": 14412,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 14480,
"s": 14450,
"text": "Graph and its representations"
},
{
"code": null,
"e": 14500,
"s": 14480,
"text": "Topological Sorting"
}
] |
K-Means Clustering in Julia
|
12 Oct, 2020
Clustering is the task of grouping a set of objects(all values in a column) in such a way that objects in the same group are more similar to each other than to those in other groups. K-means clustering is one of the simplest and popular unsupervised machine learning algorithms.
Unsupervised algorithms make inferences from datasets using only input vectors without referring to known, or labeled, outcomes.
Define a target number k, which refers to the number of centroids you need in the dataset. A centroid is the imaginary or real location representing the center of the cluster.
Every data point is allocated to each of the clusters by reducing the in-cluster sum of squares. K-means algorithm identifies k number of centroids, and then allocates every data point to the nearest cluster while keeping the centroids as small as possible.
Note: Means in k-means refers to averaging of the data.
How it is achieved in Julia?
In Julia, it can be achieved with the help of some algorithms. K means is one such algorithm. This can simply be achieved with the help of inbuilt functions like kmeans().
This function divides the data into clusters having similar features: Data, no. of clusters we require, iter: keyword if we want to know how many iterations did it take to create clusters are passed as arguments in this function.
Packages involved:
Dataframe
Clustering
Plots
RDatasets
RDatasets package provides access to many of the classical data sets that are available in R.
Julia
# syntax for loading the packagesusing Pkg # to create dataframes and loadPkg.add("DataFrames")using DataFrames # to use the above function kmeans()Pkg.add("Clustering")using Clustering # to visualise our clusters formedPkg.add("Plots")using Plots # RDatasets to load the already made datasetsPkg.add("RDatasets")using RDatasets
Functions involved:
dataset(): We can access Fisher’s iris data set using this function and passing the arguments as “datasets” and “iris”.
Matrix(): Constructs an uninitialized Matrix{T} of size m×n.
collect(): It returns an array of all items in the specified collection or iterator.
scatter(): It is used to return scatter plot of dataset.
rand(): Pick a random element or array of random elements from the set of values specified and dimensions and no of numbers is passed as an argument.
nclusters(R): This function is used to match the number of clusters formed to the number of clusters we’ve passed in kmeans() function here R represents the results of returned clusters from kmeans().
Following are the steps involved to perform clustering in Existing Dataset:
Step 1: In the dataset() function passing the datasets and iris as arguments and storing the data in the dataframe iris.
Julia
# loading the data and storing it in iris dataframeiris = dataset("datasets", "iris");
Step 2: Now after storing the data in the dataframe we need to create a 2D Matrix which can be achieved with help of Matrix() function.
Step 3: Now storing the matrix in the features dataframe which represents the total rows and columns required to form a cluster of the fetched array with help of the collect() function.
Julia
# Fetching the each value of data # using collect() function and # storing in featuresfeatures = collect(Matrix(iris[:, 1:4])');
Step 4: Now applying the function kmeans() and passing the features and no. of clusters as arguments.
Julia
# running K-means for the 4 clustersresult = kmeans(features, 4);
Step 5: Plotting the clusters with help of scatter() function to get scatter plot of 4 clusters here with different colors.
Julia
# plot with the point color mapped # to the assigned cluster indexscatter(iris.PetalLength, iris.PetalWidth, marker_z = result.assignments, color =:blue, legend = false)
Final Code:
Julia
# loading the data and storing it in iris dataframeiris = dataset("datasets", "iris"); # Fetching the each value of data # using collect() function and # storing in featuresfeatures = collect(Matrix(iris[:, 1:4])'); # running K-means for the 4 clustersresult = kmeans(features, 4); # plot with the point color mapped# to the assigned cluster indexscatter(iris.PetalLength, iris.PetalWidth, marker_z = result.assignments, color =:blue, legend = false)
Output:
Following are the steps involved to perform clustering after creating a Dataset:
Step 1: Forming a dataset with random numbers using rand() function and storing it into the dataframe also passing the dimensions required for the random numbers.
Julia
# make a random dataset with # 1000 random 5-dimensional pointsX = rand(5, 1000)
Step 2: Now simply apply the kmeans() function and pass the random numbers dataframe, to display the iterations pass the argument display=:iter, also we need to pass the value for maxiter maximum iterations this function allowed to do.
Julia
# cluster X into 20 clusters using K-meansR = kmeans(X, 15; maxiter = 200, display=:iter)
Step 3: Verify the numbers of clusters formed with nclusters() function by passing the results of kmeans() as an argument, and we will get bool values true or false.
Julia
# verify the number of clustersnclusters(R) == 15
Step 4: We can now get the assigned points to the clusters with help of assignments() function and passing the (R) returned clusters from kmeans().
Julia
# get the assignments of points to clustersa = assignments(R)
Step 5: We can also get the sizes of the clusters with help of simple function counts(R)
Julia
# get the cluster sizesc = counts(R)
Step 6: At last we can get values of cluster centers with R as object and accessing centers.
Julia
# get the cluster centersM = R.centers
Final Code:
Julia
# make a random dataset with # 1000 random 5-dimensional pointsX = rand(5, 1000) # cluster X into 20 clusters using K-meansR = kmeans(X, 15; maxiter = 200, display=:iter) # verify the number of clustersnclusters(R) == 15 # get the assignments of points to clusters# a = assignments(R) # get the cluster sizes# c = counts(R) # get the cluster centersM = R.centers
Output:
Julia Data-science
Julia-Machine-learning
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Storing Output on a File in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Manipulating matrices in Julia
Exception handling in Julia
Formatting of Strings in Julia
Creating array with repeated elements in Julia - repeat() Method
while loop in Julia
Tuples in Julia
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Oct, 2020"
},
{
"code": null,
"e": 307,
"s": 28,
"text": "Clustering is the task of grouping a set of objects(all values in a column) in such a way that objects in the same group are more similar to each other than to those in other groups. K-means clustering is one of the simplest and popular unsupervised machine learning algorithms."
},
{
"code": null,
"e": 436,
"s": 307,
"text": "Unsupervised algorithms make inferences from datasets using only input vectors without referring to known, or labeled, outcomes."
},
{
"code": null,
"e": 612,
"s": 436,
"text": "Define a target number k, which refers to the number of centroids you need in the dataset. A centroid is the imaginary or real location representing the center of the cluster."
},
{
"code": null,
"e": 870,
"s": 612,
"text": "Every data point is allocated to each of the clusters by reducing the in-cluster sum of squares. K-means algorithm identifies k number of centroids, and then allocates every data point to the nearest cluster while keeping the centroids as small as possible."
},
{
"code": null,
"e": 926,
"s": 870,
"text": "Note: Means in k-means refers to averaging of the data."
},
{
"code": null,
"e": 955,
"s": 926,
"text": "How it is achieved in Julia?"
},
{
"code": null,
"e": 1128,
"s": 955,
"text": "In Julia, it can be achieved with the help of some algorithms. K means is one such algorithm. This can simply be achieved with the help of inbuilt functions like kmeans(). "
},
{
"code": null,
"e": 1358,
"s": 1128,
"text": "This function divides the data into clusters having similar features: Data, no. of clusters we require, iter: keyword if we want to know how many iterations did it take to create clusters are passed as arguments in this function."
},
{
"code": null,
"e": 1378,
"s": 1358,
"text": "Packages involved: "
},
{
"code": null,
"e": 1388,
"s": 1378,
"text": "Dataframe"
},
{
"code": null,
"e": 1399,
"s": 1388,
"text": "Clustering"
},
{
"code": null,
"e": 1405,
"s": 1399,
"text": "Plots"
},
{
"code": null,
"e": 1415,
"s": 1405,
"text": "RDatasets"
},
{
"code": null,
"e": 1509,
"s": 1415,
"text": "RDatasets package provides access to many of the classical data sets that are available in R."
},
{
"code": null,
"e": 1515,
"s": 1509,
"text": "Julia"
},
{
"code": "# syntax for loading the packagesusing Pkg # to create dataframes and loadPkg.add(\"DataFrames\")using DataFrames # to use the above function kmeans()Pkg.add(\"Clustering\")using Clustering # to visualise our clusters formedPkg.add(\"Plots\")using Plots # RDatasets to load the already made datasetsPkg.add(\"RDatasets\")using RDatasets",
"e": 1848,
"s": 1515,
"text": null
},
{
"code": null,
"e": 1868,
"s": 1848,
"text": "Functions involved:"
},
{
"code": null,
"e": 1988,
"s": 1868,
"text": "dataset(): We can access Fisher’s iris data set using this function and passing the arguments as “datasets” and “iris”."
},
{
"code": null,
"e": 2050,
"s": 1988,
"text": "Matrix(): Constructs an uninitialized Matrix{T} of size m×n. "
},
{
"code": null,
"e": 2135,
"s": 2050,
"text": "collect(): It returns an array of all items in the specified collection or iterator."
},
{
"code": null,
"e": 2192,
"s": 2135,
"text": "scatter(): It is used to return scatter plot of dataset."
},
{
"code": null,
"e": 2342,
"s": 2192,
"text": "rand(): Pick a random element or array of random elements from the set of values specified and dimensions and no of numbers is passed as an argument."
},
{
"code": null,
"e": 2543,
"s": 2342,
"text": "nclusters(R): This function is used to match the number of clusters formed to the number of clusters we’ve passed in kmeans() function here R represents the results of returned clusters from kmeans()."
},
{
"code": null,
"e": 2620,
"s": 2543,
"text": "Following are the steps involved to perform clustering in Existing Dataset: "
},
{
"code": null,
"e": 2741,
"s": 2620,
"text": "Step 1: In the dataset() function passing the datasets and iris as arguments and storing the data in the dataframe iris."
},
{
"code": null,
"e": 2747,
"s": 2741,
"text": "Julia"
},
{
"code": "# loading the data and storing it in iris dataframeiris = dataset(\"datasets\", \"iris\");",
"e": 2834,
"s": 2747,
"text": null
},
{
"code": null,
"e": 2970,
"s": 2834,
"text": "Step 2: Now after storing the data in the dataframe we need to create a 2D Matrix which can be achieved with help of Matrix() function."
},
{
"code": null,
"e": 3156,
"s": 2970,
"text": "Step 3: Now storing the matrix in the features dataframe which represents the total rows and columns required to form a cluster of the fetched array with help of the collect() function."
},
{
"code": null,
"e": 3162,
"s": 3156,
"text": "Julia"
},
{
"code": "# Fetching the each value of data # using collect() function and # storing in featuresfeatures = collect(Matrix(iris[:, 1:4])');",
"e": 3291,
"s": 3162,
"text": null
},
{
"code": null,
"e": 3393,
"s": 3291,
"text": "Step 4: Now applying the function kmeans() and passing the features and no. of clusters as arguments."
},
{
"code": null,
"e": 3399,
"s": 3393,
"text": "Julia"
},
{
"code": "# running K-means for the 4 clustersresult = kmeans(features, 4);",
"e": 3466,
"s": 3399,
"text": null
},
{
"code": null,
"e": 3590,
"s": 3466,
"text": "Step 5: Plotting the clusters with help of scatter() function to get scatter plot of 4 clusters here with different colors."
},
{
"code": null,
"e": 3596,
"s": 3590,
"text": "Julia"
},
{
"code": "# plot with the point color mapped # to the assigned cluster indexscatter(iris.PetalLength, iris.PetalWidth, marker_z = result.assignments, color =:blue, legend = false)",
"e": 3781,
"s": 3596,
"text": null
},
{
"code": null,
"e": 3793,
"s": 3781,
"text": "Final Code:"
},
{
"code": null,
"e": 3799,
"s": 3793,
"text": "Julia"
},
{
"code": "# loading the data and storing it in iris dataframeiris = dataset(\"datasets\", \"iris\"); # Fetching the each value of data # using collect() function and # storing in featuresfeatures = collect(Matrix(iris[:, 1:4])'); # running K-means for the 4 clustersresult = kmeans(features, 4); # plot with the point color mapped# to the assigned cluster indexscatter(iris.PetalLength, iris.PetalWidth, marker_z = result.assignments, color =:blue, legend = false)",
"e": 4269,
"s": 3799,
"text": null
},
{
"code": null,
"e": 4277,
"s": 4269,
"text": "Output:"
},
{
"code": null,
"e": 4407,
"s": 4325,
"text": "Following are the steps involved to perform clustering after creating a Dataset: "
},
{
"code": null,
"e": 4570,
"s": 4407,
"text": "Step 1: Forming a dataset with random numbers using rand() function and storing it into the dataframe also passing the dimensions required for the random numbers."
},
{
"code": null,
"e": 4576,
"s": 4570,
"text": "Julia"
},
{
"code": "# make a random dataset with # 1000 random 5-dimensional pointsX = rand(5, 1000)",
"e": 4657,
"s": 4576,
"text": null
},
{
"code": null,
"e": 4893,
"s": 4657,
"text": "Step 2: Now simply apply the kmeans() function and pass the random numbers dataframe, to display the iterations pass the argument display=:iter, also we need to pass the value for maxiter maximum iterations this function allowed to do."
},
{
"code": null,
"e": 4899,
"s": 4893,
"text": "Julia"
},
{
"code": "# cluster X into 20 clusters using K-meansR = kmeans(X, 15; maxiter = 200, display=:iter)",
"e": 5007,
"s": 4899,
"text": null
},
{
"code": null,
"e": 5173,
"s": 5007,
"text": "Step 3: Verify the numbers of clusters formed with nclusters() function by passing the results of kmeans() as an argument, and we will get bool values true or false."
},
{
"code": null,
"e": 5179,
"s": 5173,
"text": "Julia"
},
{
"code": "# verify the number of clustersnclusters(R) == 15",
"e": 5229,
"s": 5179,
"text": null
},
{
"code": null,
"e": 5377,
"s": 5229,
"text": "Step 4: We can now get the assigned points to the clusters with help of assignments() function and passing the (R) returned clusters from kmeans()."
},
{
"code": null,
"e": 5383,
"s": 5377,
"text": "Julia"
},
{
"code": "# get the assignments of points to clustersa = assignments(R) ",
"e": 5446,
"s": 5383,
"text": null
},
{
"code": null,
"e": 5535,
"s": 5446,
"text": "Step 5: We can also get the sizes of the clusters with help of simple function counts(R)"
},
{
"code": null,
"e": 5541,
"s": 5535,
"text": "Julia"
},
{
"code": "# get the cluster sizesc = counts(R)",
"e": 5578,
"s": 5541,
"text": null
},
{
"code": null,
"e": 5671,
"s": 5578,
"text": "Step 6: At last we can get values of cluster centers with R as object and accessing centers."
},
{
"code": null,
"e": 5677,
"s": 5671,
"text": "Julia"
},
{
"code": "# get the cluster centersM = R.centers",
"e": 5716,
"s": 5677,
"text": null
},
{
"code": null,
"e": 5728,
"s": 5716,
"text": "Final Code:"
},
{
"code": null,
"e": 5734,
"s": 5728,
"text": "Julia"
},
{
"code": "# make a random dataset with # 1000 random 5-dimensional pointsX = rand(5, 1000) # cluster X into 20 clusters using K-meansR = kmeans(X, 15; maxiter = 200, display=:iter) # verify the number of clustersnclusters(R) == 15 # get the assignments of points to clusters# a = assignments(R) # get the cluster sizes# c = counts(R) # get the cluster centersM = R.centers",
"e": 6104,
"s": 5734,
"text": null
},
{
"code": null,
"e": 6112,
"s": 6104,
"text": "Output:"
},
{
"code": null,
"e": 6131,
"s": 6112,
"text": "Julia Data-science"
},
{
"code": null,
"e": 6154,
"s": 6131,
"text": "Julia-Machine-learning"
},
{
"code": null,
"e": 6160,
"s": 6154,
"text": "Julia"
},
{
"code": null,
"e": 6258,
"s": 6160,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6275,
"s": 6258,
"text": "Vectors in Julia"
},
{
"code": null,
"e": 6335,
"s": 6275,
"text": "Getting rounded value of a number in Julia - round() Method"
},
{
"code": null,
"e": 6369,
"s": 6335,
"text": "Storing Output on a File in Julia"
},
{
"code": null,
"e": 6430,
"s": 6369,
"text": "Reshaping array dimensions in Julia | Array reshape() Method"
},
{
"code": null,
"e": 6461,
"s": 6430,
"text": "Manipulating matrices in Julia"
},
{
"code": null,
"e": 6489,
"s": 6461,
"text": "Exception handling in Julia"
},
{
"code": null,
"e": 6520,
"s": 6489,
"text": "Formatting of Strings in Julia"
},
{
"code": null,
"e": 6585,
"s": 6520,
"text": "Creating array with repeated elements in Julia - repeat() Method"
},
{
"code": null,
"e": 6605,
"s": 6585,
"text": "while loop in Julia"
}
] |
Program to find remainder without using modulo or % operator in C++
|
In this problem, we are given two numbers, N and D. Our task is to create a Program to find remainder without using modulo or % operator in C++.
Problem description − We need to find the remainder that will be left after dividing the number N by D. But we cannot use the modulo or % operator for this.
Let’s take an example to understand the problem
N = 53 D = 3
2
To find the remainder, a simple approach is to find the number less than N
which is the multiple of D. And the substrate the number from N. To return
the remainder.
Program to illustrate the working of our solution
Live Demo
#include <iostream>
using namespace std;
int findRem(int N, int D) {
int i ;
for(i = 0; ;i++) {
if(D * i >= N)
break;
}
return N - (D * (i-1));
}
int main(){
int N = 45, D = 6 ;
cout<<"The remainder after dividing "<<N<<" by "<<D<<" is"<<findRem(N, D);
return 0;
}
The remainder after dividing 45 by 6 is 3
Another solution is by using the integer value of the quotient of the dividing
which can be extracted directly by initializing it to an int value in C++. Then
multiplying it with D. And subtracting the value from N gives the remainder.
Program to illustrate the working our solution
Live Demo
#include <iostream>
using namespace std;
int findRem(int N, int D) {
int Q = N/D;
int R = N - (D * Q);
return R;
}
int main(){
int N = 45, D = 6 ;
cout<<"The remainder after dividing "<<N<<" by "<<D<<" is"<<findRem(N, D);
return 0;
}
The remainder after dividing 45 by 6 is 3
|
[
{
"code": null,
"e": 1332,
"s": 1187,
"text": "In this problem, we are given two numbers, N and D. Our task is to create a Program to find remainder without using modulo or % operator in C++."
},
{
"code": null,
"e": 1489,
"s": 1332,
"text": "Problem description − We need to find the remainder that will be left after dividing the number N by D. But we cannot use the modulo or % operator for this."
},
{
"code": null,
"e": 1537,
"s": 1489,
"text": "Let’s take an example to understand the problem"
},
{
"code": null,
"e": 1550,
"s": 1537,
"text": "N = 53 D = 3"
},
{
"code": null,
"e": 1552,
"s": 1550,
"text": "2"
},
{
"code": null,
"e": 1717,
"s": 1552,
"text": "To find the remainder, a simple approach is to find the number less than N\nwhich is the multiple of D. And the substrate the number from N. To return\nthe remainder."
},
{
"code": null,
"e": 1767,
"s": 1717,
"text": "Program to illustrate the working of our solution"
},
{
"code": null,
"e": 1778,
"s": 1767,
"text": " Live Demo"
},
{
"code": null,
"e": 2079,
"s": 1778,
"text": "#include <iostream>\nusing namespace std;\nint findRem(int N, int D) {\n int i ;\n for(i = 0; ;i++) {\n if(D * i >= N)\n break;\n }\n return N - (D * (i-1));\n}\nint main(){\n int N = 45, D = 6 ;\n cout<<\"The remainder after dividing \"<<N<<\" by \"<<D<<\" is\"<<findRem(N, D);\n return 0;\n}"
},
{
"code": null,
"e": 2121,
"s": 2079,
"text": "The remainder after dividing 45 by 6 is 3"
},
{
"code": null,
"e": 2357,
"s": 2121,
"text": "Another solution is by using the integer value of the quotient of the dividing\nwhich can be extracted directly by initializing it to an int value in C++. Then\nmultiplying it with D. And subtracting the value from N gives the remainder."
},
{
"code": null,
"e": 2404,
"s": 2357,
"text": "Program to illustrate the working our solution"
},
{
"code": null,
"e": 2415,
"s": 2404,
"text": " Live Demo"
},
{
"code": null,
"e": 2667,
"s": 2415,
"text": "#include <iostream>\nusing namespace std;\nint findRem(int N, int D) {\n int Q = N/D;\n int R = N - (D * Q);\n return R;\n}\nint main(){\n int N = 45, D = 6 ;\n cout<<\"The remainder after dividing \"<<N<<\" by \"<<D<<\" is\"<<findRem(N, D);\n return 0;\n}"
},
{
"code": null,
"e": 2709,
"s": 2667,
"text": "The remainder after dividing 45 by 6 is 3"
}
] |
Normalization vs Standardization
|
12 Nov, 2021
Feature scaling is one of the most important data preprocessing step in machine learning. Algorithms that compute the distance between the features are biased towards numerically larger values if the data is not scaled.
Tree-based algorithms are fairly insensitive to the scale of the features. Also, feature scaling helps machine learning, and deep learning algorithms train and converge faster.
There are some feature scaling techniques such as Normalization and Standardization that are the most popular and at the same time, the most confusing ones.
Let’s resolve that confusion.
Normalization or Min-Max Scaling is used to transform features to be on a similar scale. The new point is calculated as:
X_new = (X - X_min)/(X_max - X_min)
This scales the range to [0, 1] or sometimes [-1, 1]. Geometrically speaking, transformation squishes the n-dimensional data into an n-dimensional unit hypercube. Normalization is useful when there are no outliers as it cannot cope up with them. Usually, we would scale age and not incomes because only a few people have high incomes but the age is close to uniform.
Standardization or Z-Score Normalization is the transformation of features by subtracting from mean and dividing by standard deviation. This is often called as Z-score.
X_new = (X - mean)/Std
Standardization can be helpful in cases where the data follows a Gaussian distribution. However, this does not have to be necessarily true. Geometrically speaking, it translates the data to the mean vector of original data to the origin and squishes or expands the points if std is 1 respectively. We can see that we are just changing mean and standard deviation to a standard normal distribution which is still normal thus the shape of the distribution is not affected.
Standardization does not get affected by outliers because there is no predefined range of transformed features.
Difference between Normalization and Standardization
chhabradhanvi
Difference Between
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Similarities and Difference between Java and C++
Difference between Compile-time and Run-time Polymorphism in Java
Difference between Internal and External fragmentation
Naive Bayes Classifiers
ML | Linear Regression
Linear Regression (Python Implementation)
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n12 Nov, 2021"
},
{
"code": null,
"e": 273,
"s": 53,
"text": "Feature scaling is one of the most important data preprocessing step in machine learning. Algorithms that compute the distance between the features are biased towards numerically larger values if the data is not scaled."
},
{
"code": null,
"e": 450,
"s": 273,
"text": "Tree-based algorithms are fairly insensitive to the scale of the features. Also, feature scaling helps machine learning, and deep learning algorithms train and converge faster."
},
{
"code": null,
"e": 607,
"s": 450,
"text": "There are some feature scaling techniques such as Normalization and Standardization that are the most popular and at the same time, the most confusing ones."
},
{
"code": null,
"e": 637,
"s": 607,
"text": "Let’s resolve that confusion."
},
{
"code": null,
"e": 758,
"s": 637,
"text": "Normalization or Min-Max Scaling is used to transform features to be on a similar scale. The new point is calculated as:"
},
{
"code": null,
"e": 794,
"s": 758,
"text": "X_new = (X - X_min)/(X_max - X_min)"
},
{
"code": null,
"e": 1161,
"s": 794,
"text": "This scales the range to [0, 1] or sometimes [-1, 1]. Geometrically speaking, transformation squishes the n-dimensional data into an n-dimensional unit hypercube. Normalization is useful when there are no outliers as it cannot cope up with them. Usually, we would scale age and not incomes because only a few people have high incomes but the age is close to uniform."
},
{
"code": null,
"e": 1330,
"s": 1161,
"text": "Standardization or Z-Score Normalization is the transformation of features by subtracting from mean and dividing by standard deviation. This is often called as Z-score."
},
{
"code": null,
"e": 1353,
"s": 1330,
"text": "X_new = (X - mean)/Std"
},
{
"code": null,
"e": 1824,
"s": 1353,
"text": "Standardization can be helpful in cases where the data follows a Gaussian distribution. However, this does not have to be necessarily true. Geometrically speaking, it translates the data to the mean vector of original data to the origin and squishes or expands the points if std is 1 respectively. We can see that we are just changing mean and standard deviation to a standard normal distribution which is still normal thus the shape of the distribution is not affected."
},
{
"code": null,
"e": 1936,
"s": 1824,
"text": "Standardization does not get affected by outliers because there is no predefined range of transformed features."
},
{
"code": null,
"e": 1989,
"s": 1936,
"text": "Difference between Normalization and Standardization"
},
{
"code": null,
"e": 2003,
"s": 1989,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 2022,
"s": 2003,
"text": "Difference Between"
},
{
"code": null,
"e": 2039,
"s": 2022,
"text": "Machine Learning"
},
{
"code": null,
"e": 2056,
"s": 2039,
"text": "Machine Learning"
},
{
"code": null,
"e": 2154,
"s": 2056,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2215,
"s": 2154,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2283,
"s": 2215,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 2332,
"s": 2283,
"text": "Similarities and Difference between Java and C++"
},
{
"code": null,
"e": 2398,
"s": 2332,
"text": "Difference between Compile-time and Run-time Polymorphism in Java"
},
{
"code": null,
"e": 2453,
"s": 2398,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 2477,
"s": 2453,
"text": "Naive Bayes Classifiers"
},
{
"code": null,
"e": 2500,
"s": 2477,
"text": "ML | Linear Regression"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.