title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to upload a file in Selenium with no text box?
|
We can upload a file in Selenium with no text box. This is achieved with the help of the sendKeys method. It is applied on the web element which performs the task of selecting the path of the file to be uploaded.
As we make an attempt to upload, we shall click on the Browse button. If we investigate the HTML code for this, we shall be able to locate the attribute type having the value file. Moreover, the file path to be uploaded should be accurate.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class FileUpload{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String u = "https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm";
driver.get(u);
driver.manage().timeouts().implicitlyWait(6, TimeUnit.SECONDS);
// identify element
WebElement m=driver.findElement(By.xpath("//input[@name='photo']"));
// file selection field with file path
m.sendKeys("C:\\Users\\ghs6kor\\Tulips.jpg");
}
}
|
[
{
"code": null,
"e": 1275,
"s": 1062,
"text": "We can upload a file in Selenium with no text box. This is achieved with the help of the sendKeys method. It is applied on the web element which performs the task of selecting the path of the file to be uploaded."
},
{
"code": null,
"e": 1515,
"s": 1275,
"text": "As we make an attempt to upload, we shall click on the Browse button. If we investigate the HTML code for this, we shall be able to locate the attribute type having the value file. Moreover, the file path to be uploaded should be accurate."
},
{
"code": null,
"e": 1536,
"s": 1515,
"text": "Code Implementation."
},
{
"code": null,
"e": 2340,
"s": 1536,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class FileUpload{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String u = \"https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm\";\n driver.get(u);\n driver.manage().timeouts().implicitlyWait(6, TimeUnit.SECONDS);\n // identify element\n WebElement m=driver.findElement(By.xpath(\"//input[@name='photo']\"));\n // file selection field with file path\n m.sendKeys(\"C:\\\\Users\\\\ghs6kor\\\\Tulips.jpg\");\n }\n}"
}
] |
Check if a triangle of positive area is possible with the given angles - GeeksforGeeks
|
25 Mar, 2021
Given three angles. The task is to check if it is possible to have a triangle of positive area with these angles. If it is possible print “YES” else print “NO”.Examples:
Input : ang1 = 50, ang2 = 60, ang3 = 70
Output : YES
Input : ang1 = 50, ang2 = 65, ang3 = 80
Output : NO
Approach: We can form a valid triangle if the below conditions satisfies:
The sum of the three given angles equals to 180.
The sum of any two angles is greater than equal to the third one.
None of the given angles is zero.
Below is the implementation of the above approach:
C++
Java
Python
C#
PHP
Javascript
// C++ program to check if a triangle// of positive area is possible with// the given angles#include <bits/stdc++.h>using namespace std; string isTriangleExists(int a, int b, int c){ // Checking if the sum of three // angles is 180 and none of // the angles is zero if(a != 0 && b != 0 && c != 0 && (a + b + c)== 180) // Checking if sum of any two angles // is greater than equal to the third one if((a + b)>= c || (b + c)>= a || (a + c)>= b) return "YES"; else return "NO"; else return "NO";}// Driver Codeint main(){int a=50, b=60, c = 70;cout << isTriangleExists(a, b, c) << endl;return 0;}// This code is contributed by mits
// Java program to check if a triangle// of positive area is possible with// the given angles class GFG{static String isTriangleExists(int a, int b, int c){ // Checking if the sum of three // angles is 180 and none of // the angles is zero if(a != 0 && b != 0 && c != 0 && (a + b + c)== 180) // Checking if sum of any two angles // is greater than equal to the third one if((a + b)>= c || (b + c)>= a || (a + c)>= b) return "YES"; else return "NO"; else return "NO";}// Driver Codepublic static void main(String[] args){int a=50, b=60, c = 70;System.out.println(isTriangleExists(a, b, c));}}// This code is contributed by mits
# Python program to check if a triangle# of positive area is possible with# the given angles def isTriangleExists(a, b, c): # Checking if the sum of three # angles is 180 and none of # the angles is zero if(a != 0 and b != 0 and c != 0 and (a + b + c)== 180): # Checking if sum of any two angles # is greater than equal to the third one if((a + b)>= c or (b + c)>= a or (a + c)>= b): return "YES" else: return "NO" else: return "NO" # Driver Codea, b, c = 50, 60, 70 print(isTriangleExists(50, 60, 70))
// C# program to check if a triangle// of positive area is possible with// the given anglesclass GFG{static string isTriangleExists(int a, int b, int c){ // Checking if the sum of three // angles is 180 and none of // the angles is zero if(a != 0 && b != 0 && c != 0 && (a + b + c) == 180) // Checking if sum of any two // angles is greater than equal // to the third one if((a + b) >= c || (b + c) >= a || (a + c) >= b) return "YES"; else return "NO"; else return "NO";} // Driver Codestatic void Main(){ int a = 50, b = 60, c = 70; System.Console.WriteLine(isTriangleExists(a, b, c));}} // This code is contributed by mits
<?php// PHP program to check if a triangle// of positive area is possible with// the given angles function isTriangleExists($a, $b, $c){ // Checking if the sum of three // angles is 180 and none of // the angles is zero if($a != 0 && $b != 0 && $c != 0 && ($a + $b + $c) == 180) // Checking if sum of any two // angles is greater than equal // to the third one if(($a + $b)>= $c || ($b + $c)>= $a || ($a + $c)>= $b) return "YES"; else return "NO"; else return "NO";} // Driver Code$a = 50;$b = 60;$c = 70;echo isTriangleExists($a, $b, $c); // This code is contributed by mits?>
<script>// javascript program to check if a triangle// of positive area is possible with// the given angles function isTriangleExists(a , b , c){ // Checking if the sum of three // angles is 180 and none of // the angles is zero if (a != 0 && b != 0 && c != 0 && (a + b + c) == 180) // Checking if sum of any two angles // is greater than equal to the third one if ((a + b) >= c || (b + c) >= a || (a + c) >= b) return "YES"; else return "NO"; else return "NO"; } // Driver Code var a = 50, b = 60, c = 70; document.write(isTriangleExists(a, b, c)); // This code is contributed by Rajput-Ji</script>
YES
Mithun Kumar
Rajput-Ji
Mathematical
Python
Python Programs
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find GCD or HCF of two numbers
Modulo Operator (%) in C/C++ with Examples
Merge two sorted arrays
Prime Numbers
Program to find sum of elements in a given array
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": 24880,
"s": 24852,
"text": "\n25 Mar, 2021"
},
{
"code": null,
"e": 25052,
"s": 24880,
"text": "Given three angles. The task is to check if it is possible to have a triangle of positive area with these angles. If it is possible print “YES” else print “NO”.Examples: "
},
{
"code": null,
"e": 25159,
"s": 25052,
"text": "Input : ang1 = 50, ang2 = 60, ang3 = 70 \nOutput : YES\n\nInput : ang1 = 50, ang2 = 65, ang3 = 80\nOutput : NO"
},
{
"code": null,
"e": 25237,
"s": 25161,
"text": "Approach: We can form a valid triangle if the below conditions satisfies: "
},
{
"code": null,
"e": 25286,
"s": 25237,
"text": "The sum of the three given angles equals to 180."
},
{
"code": null,
"e": 25352,
"s": 25286,
"text": "The sum of any two angles is greater than equal to the third one."
},
{
"code": null,
"e": 25386,
"s": 25352,
"text": "None of the given angles is zero."
},
{
"code": null,
"e": 25439,
"s": 25386,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25443,
"s": 25439,
"text": "C++"
},
{
"code": null,
"e": 25448,
"s": 25443,
"text": "Java"
},
{
"code": null,
"e": 25455,
"s": 25448,
"text": "Python"
},
{
"code": null,
"e": 25458,
"s": 25455,
"text": "C#"
},
{
"code": null,
"e": 25462,
"s": 25458,
"text": "PHP"
},
{
"code": null,
"e": 25473,
"s": 25462,
"text": "Javascript"
},
{
"code": "// C++ program to check if a triangle// of positive area is possible with// the given angles#include <bits/stdc++.h>using namespace std; string isTriangleExists(int a, int b, int c){ // Checking if the sum of three // angles is 180 and none of // the angles is zero if(a != 0 && b != 0 && c != 0 && (a + b + c)== 180) // Checking if sum of any two angles // is greater than equal to the third one if((a + b)>= c || (b + c)>= a || (a + c)>= b) return \"YES\"; else return \"NO\"; else return \"NO\";}// Driver Codeint main(){int a=50, b=60, c = 70;cout << isTriangleExists(a, b, c) << endl;return 0;}// This code is contributed by mits",
"e": 26174,
"s": 25473,
"text": null
},
{
"code": "// Java program to check if a triangle// of positive area is possible with// the given angles class GFG{static String isTriangleExists(int a, int b, int c){ // Checking if the sum of three // angles is 180 and none of // the angles is zero if(a != 0 && b != 0 && c != 0 && (a + b + c)== 180) // Checking if sum of any two angles // is greater than equal to the third one if((a + b)>= c || (b + c)>= a || (a + c)>= b) return \"YES\"; else return \"NO\"; else return \"NO\";}// Driver Codepublic static void main(String[] args){int a=50, b=60, c = 70;System.out.println(isTriangleExists(a, b, c));}}// This code is contributed by mits",
"e": 26873,
"s": 26174,
"text": null
},
{
"code": "# Python program to check if a triangle# of positive area is possible with# the given angles def isTriangleExists(a, b, c): # Checking if the sum of three # angles is 180 and none of # the angles is zero if(a != 0 and b != 0 and c != 0 and (a + b + c)== 180): # Checking if sum of any two angles # is greater than equal to the third one if((a + b)>= c or (b + c)>= a or (a + c)>= b): return \"YES\" else: return \"NO\" else: return \"NO\" # Driver Codea, b, c = 50, 60, 70 print(isTriangleExists(50, 60, 70))",
"e": 27448,
"s": 26873,
"text": null
},
{
"code": "// C# program to check if a triangle// of positive area is possible with// the given anglesclass GFG{static string isTriangleExists(int a, int b, int c){ // Checking if the sum of three // angles is 180 and none of // the angles is zero if(a != 0 && b != 0 && c != 0 && (a + b + c) == 180) // Checking if sum of any two // angles is greater than equal // to the third one if((a + b) >= c || (b + c) >= a || (a + c) >= b) return \"YES\"; else return \"NO\"; else return \"NO\";} // Driver Codestatic void Main(){ int a = 50, b = 60, c = 70; System.Console.WriteLine(isTriangleExists(a, b, c));}} // This code is contributed by mits",
"e": 28258,
"s": 27448,
"text": null
},
{
"code": "<?php// PHP program to check if a triangle// of positive area is possible with// the given angles function isTriangleExists($a, $b, $c){ // Checking if the sum of three // angles is 180 and none of // the angles is zero if($a != 0 && $b != 0 && $c != 0 && ($a + $b + $c) == 180) // Checking if sum of any two // angles is greater than equal // to the third one if(($a + $b)>= $c || ($b + $c)>= $a || ($a + $c)>= $b) return \"YES\"; else return \"NO\"; else return \"NO\";} // Driver Code$a = 50;$b = 60;$c = 70;echo isTriangleExists($a, $b, $c); // This code is contributed by mits?>",
"e": 28939,
"s": 28258,
"text": null
},
{
"code": "<script>// javascript program to check if a triangle// of positive area is possible with// the given angles function isTriangleExists(a , b , c){ // Checking if the sum of three // angles is 180 and none of // the angles is zero if (a != 0 && b != 0 && c != 0 && (a + b + c) == 180) // Checking if sum of any two angles // is greater than equal to the third one if ((a + b) >= c || (b + c) >= a || (a + c) >= b) return \"YES\"; else return \"NO\"; else return \"NO\"; } // Driver Code var a = 50, b = 60, c = 70; document.write(isTriangleExists(a, b, c)); // This code is contributed by Rajput-Ji</script>",
"e": 29684,
"s": 28939,
"text": null
},
{
"code": null,
"e": 29688,
"s": 29684,
"text": "YES"
},
{
"code": null,
"e": 29703,
"s": 29690,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 29713,
"s": 29703,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 29726,
"s": 29713,
"text": "Mathematical"
},
{
"code": null,
"e": 29733,
"s": 29726,
"text": "Python"
},
{
"code": null,
"e": 29749,
"s": 29733,
"text": "Python Programs"
},
{
"code": null,
"e": 29762,
"s": 29749,
"text": "Mathematical"
},
{
"code": null,
"e": 29860,
"s": 29762,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29869,
"s": 29860,
"text": "Comments"
},
{
"code": null,
"e": 29882,
"s": 29869,
"text": "Old Comments"
},
{
"code": null,
"e": 29924,
"s": 29882,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 29967,
"s": 29924,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 29991,
"s": 29967,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 30005,
"s": 29991,
"text": "Prime Numbers"
},
{
"code": null,
"e": 30054,
"s": 30005,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 30082,
"s": 30054,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 30132,
"s": 30082,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 30154,
"s": 30132,
"text": "Python map() function"
}
] |
How to Automatically Close Alerts using Twitter Bootstrap ? - GeeksforGeeks
|
01 Jun, 2020
All modern web application uses alerts to show messages to the user. These alerts have a close button to close them or can be closed automatically using Twitter Bootstrap. In this post, we will create automatically closing of alerts using twitter Bootstrap.
Basic idea is to use jQuery setTimeout() method to close the alert after specified time.
Syntax:
setTimeout(function, delay)
Note: Delay is defined in milliseconds. 1 second is equal to 1000 milliseconds.
Example 1: In this example, alert is accessed in script using the id and then alert is closed after 5 seconds.
HTML
<!DOCTYPE html><html> <head> <title> How to Automatically Close Alerts using Twitter Bootstrap ? </title> <!-- Including Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <!-- Including jQuery --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"> </script> <!-- Including Bootstrap JS --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script></head> <body> <h3>Automatically closing the alert</h3> <!-- Showing alert --> <div id="alert" class="alert alert-danger"> This alert will automatically close in 5 seconds. </div> <script type="text/javascript"> setTimeout(function () { // Closing the alert $('#alert').alert('close'); }, 5000); </script></body> </html>
Example 2: In this example, alert is accessed in script using it’s class and alert closes after 2 seconds.
HTML
<!DOCTYPE html><html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <title> How to Automatically Close Alerts using Twitter Bootstrap ? </title> <!-- Including Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <!-- Including jQuery --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"> </script> <!-- Including Bootstrap JS --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script></head> <body> <h3>Automatically closing the alert</h3> <!-- Showing alert --> <div class="alert alert-danger"> This alert will automatically close in 2 seconds. </div> <script type="text/javascript"> setTimeout(function () { // Closing the alert $('.alert').alert('close'); }, 2000); </script></body> </html>
Example 3: In this example, bootstrap hide class is dynamically added to alert to close the alert after 5 seconds. The addClass() is the method that is used to add class to any element using JavaScript.
HTML
<!DOCTYPE html><html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <title> How to Automatically Close Alerts using Twitter Bootstrap ? </title> <!-- Including Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <!-- Including jQuery --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"> </script> <!-- Including Bootstrap JS --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script></head> <body> <h3>Automatically closing the alert</h3> <!-- Showing alert --> <div id="alert" class="alert alert-danger"> This alert will automatically close in 5 seconds. </div> <script type="text/javascript"> setTimeout(function () { // Adding the class dynamically $('#alert').addClass('hide'); }, 5000); </script></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.
Bootstrap-Misc
HTML-Misc
Bootstrap
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 set Bootstrap Timepicker using datetimepicker library ?
How to Show Images on Click using HTML ?
How to Use Bootstrap with React?
Difference between Bootstrap 4 and Bootstrap 5
How to keep gap between columns using Bootstrap?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 26459,
"s": 26431,
"text": "\n01 Jun, 2020"
},
{
"code": null,
"e": 26717,
"s": 26459,
"text": "All modern web application uses alerts to show messages to the user. These alerts have a close button to close them or can be closed automatically using Twitter Bootstrap. In this post, we will create automatically closing of alerts using twitter Bootstrap."
},
{
"code": null,
"e": 26806,
"s": 26717,
"text": "Basic idea is to use jQuery setTimeout() method to close the alert after specified time."
},
{
"code": null,
"e": 26814,
"s": 26806,
"text": "Syntax:"
},
{
"code": null,
"e": 26843,
"s": 26814,
"text": "setTimeout(function, delay)\n"
},
{
"code": null,
"e": 26923,
"s": 26843,
"text": "Note: Delay is defined in milliseconds. 1 second is equal to 1000 milliseconds."
},
{
"code": null,
"e": 27034,
"s": 26923,
"text": "Example 1: In this example, alert is accessed in script using the id and then alert is closed after 5 seconds."
},
{
"code": null,
"e": 27039,
"s": 27034,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to Automatically Close Alerts using Twitter Bootstrap ? </title> <!-- Including Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <!-- Including jQuery --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js\"> </script> <!-- Including Bootstrap JS --> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script></head> <body> <h3>Automatically closing the alert</h3> <!-- Showing alert --> <div id=\"alert\" class=\"alert alert-danger\"> This alert will automatically close in 5 seconds. </div> <script type=\"text/javascript\"> setTimeout(function () { // Closing the alert $('#alert').alert('close'); }, 5000); </script></body> </html>",
"e": 27972,
"s": 27039,
"text": null
},
{
"code": null,
"e": 28079,
"s": 27972,
"text": "Example 2: In this example, alert is accessed in script using it’s class and alert closes after 2 seconds."
},
{
"code": null,
"e": 28084,
"s": 28079,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" /> <title> How to Automatically Close Alerts using Twitter Bootstrap ? </title> <!-- Including Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <!-- Including jQuery --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js\"> </script> <!-- Including Bootstrap JS --> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script></head> <body> <h3>Automatically closing the alert</h3> <!-- Showing alert --> <div class=\"alert alert-danger\"> This alert will automatically close in 2 seconds. </div> <script type=\"text/javascript\"> setTimeout(function () { // Closing the alert $('.alert').alert('close'); }, 2000); </script></body> </html>",
"e": 29092,
"s": 28084,
"text": null
},
{
"code": null,
"e": 29295,
"s": 29092,
"text": "Example 3: In this example, bootstrap hide class is dynamically added to alert to close the alert after 5 seconds. The addClass() is the method that is used to add class to any element using JavaScript."
},
{
"code": null,
"e": 29300,
"s": 29295,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" /> <title> How to Automatically Close Alerts using Twitter Bootstrap ? </title> <!-- Including Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <!-- Including jQuery --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js\"> </script> <!-- Including Bootstrap JS --> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script></head> <body> <h3>Automatically closing the alert</h3> <!-- Showing alert --> <div id=\"alert\" class=\"alert alert-danger\"> This alert will automatically close in 5 seconds. </div> <script type=\"text/javascript\"> setTimeout(function () { // Adding the class dynamically $('#alert').addClass('hide'); }, 5000); </script></body> </html>",
"e": 30321,
"s": 29300,
"text": null
},
{
"code": null,
"e": 30329,
"s": 30321,
"text": "Output:"
},
{
"code": null,
"e": 30466,
"s": 30329,
"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": 30481,
"s": 30466,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 30491,
"s": 30481,
"text": "HTML-Misc"
},
{
"code": null,
"e": 30501,
"s": 30491,
"text": "Bootstrap"
},
{
"code": null,
"e": 30506,
"s": 30501,
"text": "HTML"
},
{
"code": null,
"e": 30523,
"s": 30506,
"text": "Web Technologies"
},
{
"code": null,
"e": 30550,
"s": 30523,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30555,
"s": 30550,
"text": "HTML"
},
{
"code": null,
"e": 30653,
"s": 30555,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30716,
"s": 30653,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 30757,
"s": 30716,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 30790,
"s": 30757,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 30837,
"s": 30790,
"text": "Difference between Bootstrap 4 and Bootstrap 5"
},
{
"code": null,
"e": 30886,
"s": 30837,
"text": "How to keep gap between columns using Bootstrap?"
},
{
"code": null,
"e": 30936,
"s": 30886,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 30998,
"s": 30936,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31046,
"s": 30998,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 31099,
"s": 31046,
"text": "Hide or show elements in HTML using display property"
}
] |
Java String substring() Method example.
|
The substring(int beginIndex, int endIndex) method of the String class. It returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
Live Demo
import java.lang.*;
public class StringDemo {
public static void main(String[] args) {
String str = "This is tutorials point";
String substr = "";
// prints the substring after index 8 till index 17
substr = str.substring(8, 17);
System.out.println("substring = " + substr);
// prints the substring after index 0 till index 8
substr = str.substring(0, 8);
System.out.println("substring = " + substr);
}
}
substring = tutorials
substring = This is
|
[
{
"code": null,
"e": 1352,
"s": 1062,
"text": "The substring(int beginIndex, int endIndex) method of the String class. It returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex."
},
{
"code": null,
"e": 1362,
"s": 1352,
"text": "Live Demo"
},
{
"code": null,
"e": 1770,
"s": 1362,
"text": "import java.lang.*;\n\npublic class StringDemo {\npublic static void main(String[] args) {\nString str = \"This is tutorials point\";\nString substr = \"\";\n\n// prints the substring after index 8 till index 17\nsubstr = str.substring(8, 17);\nSystem.out.println(\"substring = \" + substr);\n\n// prints the substring after index 0 till index 8\nsubstr = str.substring(0, 8);\nSystem.out.println(\"substring = \" + substr);\n}\n}"
},
{
"code": null,
"e": 1812,
"s": 1770,
"text": "substring = tutorials\nsubstring = This is"
}
] |
Tryit Editor v3.7
|
Tryit: Using justify-content: flex-end
|
[] |
Apache Pig - Execution
|
In the previous chapter, we explained how to install Apache Pig. In this chapter, we will discuss how to execute Apache Pig.
You can run Apache Pig in two modes, namely, Local Mode and HDFS mode.
In this mode, all the files are installed and run from your local host and local file system. There is no need of Hadoop or HDFS. This mode is generally used for testing purpose.
MapReduce mode is where we load or process the data that exists in the Hadoop File System (HDFS) using Apache Pig. In this mode, whenever we execute the Pig Latin statements to process the data, a MapReduce job is invoked in the back-end to perform a particular operation on the data that exists in the HDFS.
Apache Pig scripts can be executed in three ways, namely, interactive mode, batch mode, and embedded mode.
Interactive Mode (Grunt shell) − You can run Apache Pig in interactive mode using the Grunt shell. In this shell, you can enter the Pig Latin statements and get the output (using Dump operator).
Interactive Mode (Grunt shell) − You can run Apache Pig in interactive mode using the Grunt shell. In this shell, you can enter the Pig Latin statements and get the output (using Dump operator).
Batch Mode (Script) − You can run Apache Pig in Batch mode by writing the Pig Latin script in a single file with .pig extension.
Batch Mode (Script) − You can run Apache Pig in Batch mode by writing the Pig Latin script in a single file with .pig extension.
Embedded Mode (UDF) − Apache Pig provides the provision of defining our own functions (User Defined Functions) in programming languages such as Java, and using them in our script.
Embedded Mode (UDF) − Apache Pig provides the provision of defining our own functions (User Defined Functions) in programming languages such as Java, and using them in our script.
You can invoke the Grunt shell in a desired mode (local/MapReduce) using the −x option as shown below.
Command −
$ ./pig –x local
Command −
$ ./pig -x mapreduce
Output −
Output −
Either of these commands gives you the Grunt shell prompt as shown below.
grunt>
You can exit the Grunt shell using ‘ctrl + d’.
After invoking the Grunt shell, you can execute a Pig script by directly entering the Pig Latin statements in it.
grunt> customers = LOAD 'customers.txt' USING PigStorage(',');
You can write an entire Pig Latin script in a file and execute it using the –x command. Let us suppose we have a Pig script in a file named sample_script.pig as shown below.
student = LOAD 'hdfs://localhost:9000/pig_data/student.txt' USING
PigStorage(',') as (id:int,name:chararray,city:chararray);
Dump student;
Now, you can execute the script in the above file as shown below.
Note − We will discuss in detail how to run a Pig script in Bach mode and in embedded mode in subsequent chapters.
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": 2809,
"s": 2684,
"text": "In the previous chapter, we explained how to install Apache Pig. In this chapter, we will discuss how to execute Apache Pig."
},
{
"code": null,
"e": 2880,
"s": 2809,
"text": "You can run Apache Pig in two modes, namely, Local Mode and HDFS mode."
},
{
"code": null,
"e": 3059,
"s": 2880,
"text": "In this mode, all the files are installed and run from your local host and local file system. There is no need of Hadoop or HDFS. This mode is generally used for testing purpose."
},
{
"code": null,
"e": 3368,
"s": 3059,
"text": "MapReduce mode is where we load or process the data that exists in the Hadoop File System (HDFS) using Apache Pig. In this mode, whenever we execute the Pig Latin statements to process the data, a MapReduce job is invoked in the back-end to perform a particular operation on the data that exists in the HDFS."
},
{
"code": null,
"e": 3475,
"s": 3368,
"text": "Apache Pig scripts can be executed in three ways, namely, interactive mode, batch mode, and embedded mode."
},
{
"code": null,
"e": 3670,
"s": 3475,
"text": "Interactive Mode (Grunt shell) − You can run Apache Pig in interactive mode using the Grunt shell. In this shell, you can enter the Pig Latin statements and get the output (using Dump operator)."
},
{
"code": null,
"e": 3865,
"s": 3670,
"text": "Interactive Mode (Grunt shell) − You can run Apache Pig in interactive mode using the Grunt shell. In this shell, you can enter the Pig Latin statements and get the output (using Dump operator)."
},
{
"code": null,
"e": 3994,
"s": 3865,
"text": "Batch Mode (Script) − You can run Apache Pig in Batch mode by writing the Pig Latin script in a single file with .pig extension."
},
{
"code": null,
"e": 4123,
"s": 3994,
"text": "Batch Mode (Script) − You can run Apache Pig in Batch mode by writing the Pig Latin script in a single file with .pig extension."
},
{
"code": null,
"e": 4303,
"s": 4123,
"text": "Embedded Mode (UDF) − Apache Pig provides the provision of defining our own functions (User Defined Functions) in programming languages such as Java, and using them in our script."
},
{
"code": null,
"e": 4483,
"s": 4303,
"text": "Embedded Mode (UDF) − Apache Pig provides the provision of defining our own functions (User Defined Functions) in programming languages such as Java, and using them in our script."
},
{
"code": null,
"e": 4586,
"s": 4483,
"text": "You can invoke the Grunt shell in a desired mode (local/MapReduce) using the −x option as shown below."
},
{
"code": null,
"e": 4596,
"s": 4586,
"text": "Command −"
},
{
"code": null,
"e": 4613,
"s": 4596,
"text": "$ ./pig –x local"
},
{
"code": null,
"e": 4623,
"s": 4613,
"text": "Command −"
},
{
"code": null,
"e": 4644,
"s": 4623,
"text": "$ ./pig -x mapreduce"
},
{
"code": null,
"e": 4653,
"s": 4644,
"text": "Output −"
},
{
"code": null,
"e": 4662,
"s": 4653,
"text": "Output −"
},
{
"code": null,
"e": 4736,
"s": 4662,
"text": "Either of these commands gives you the Grunt shell prompt as shown below."
},
{
"code": null,
"e": 4743,
"s": 4736,
"text": "grunt>"
},
{
"code": null,
"e": 4790,
"s": 4743,
"text": "You can exit the Grunt shell using ‘ctrl + d’."
},
{
"code": null,
"e": 4904,
"s": 4790,
"text": "After invoking the Grunt shell, you can execute a Pig script by directly entering the Pig Latin statements in it."
},
{
"code": null,
"e": 4967,
"s": 4904,
"text": "grunt> customers = LOAD 'customers.txt' USING PigStorage(',');"
},
{
"code": null,
"e": 5141,
"s": 4967,
"text": "You can write an entire Pig Latin script in a file and execute it using the –x command. Let us suppose we have a Pig script in a file named sample_script.pig as shown below."
},
{
"code": null,
"e": 5286,
"s": 5141,
"text": "student = LOAD 'hdfs://localhost:9000/pig_data/student.txt' USING\n PigStorage(',') as (id:int,name:chararray,city:chararray);\n \nDump student;"
},
{
"code": null,
"e": 5352,
"s": 5286,
"text": "Now, you can execute the script in the above file as shown below."
},
{
"code": null,
"e": 5467,
"s": 5352,
"text": "Note − We will discuss in detail how to run a Pig script in Bach mode and in embedded mode in subsequent chapters."
},
{
"code": null,
"e": 5502,
"s": 5467,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5521,
"s": 5502,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5556,
"s": 5521,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5577,
"s": 5556,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 5610,
"s": 5577,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5623,
"s": 5610,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5658,
"s": 5623,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5676,
"s": 5658,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5709,
"s": 5676,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5727,
"s": 5709,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5760,
"s": 5727,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5778,
"s": 5760,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5785,
"s": 5778,
"text": " Print"
},
{
"code": null,
"e": 5796,
"s": 5785,
"text": " Add Notes"
}
] |
DB2 - Roles
|
A role is a database object that groups multiple privileges that can be assigned to users, groups, PUBLIC or other roles by using GRANT statement.
A role cannot own database objects.
Permissions and roles granted to groups are not considered when you create the following database objects.
Package Containing static SQL
Views
Materialized Query Tables (MQT)
Triggers
SQL Routines
Package Containing static SQL
Views
Materialized Query Tables (MQT)
Triggers
SQL Routines
Syntax: [To create a new role]
db2 create role <role_name>
Example: [To create a new role named ‘sales’ to add some table to be managed by some user or group]
db2 create role sales
Output:
DB20000I The SQL command completed successfully.
Syntax: [To grant permission of a role to a table]
db2 grant select on table <table_name> to role <role_name>
Example: [To add permission to manage a table ‘shope.books’ to role ‘sales’]
db2 grant select on table shope.books to role sales
Output:
DB20000I The SQL command completed successfully.
Security administrator grants role to the required users. (Before you use this command, you need to create the users.)
Syntax: [To add users to a role]
db2 grant role <role_name> to user <username>
Example: [To add a user ‘mastanvali’ to a role ‘sales’]
db2 grant sales to user mastanvali
Output:
DB20000I The SQL command completed successfully.
For creating a hierarchies for roles, each role is granted permissions/ membership with another role.
Syntax: [before this syntax create a new role with name of “production”]
db2 grant role <roll_name> to role <role_name>
Example: [To provide permission of a role ‘sales’ to another role ‘production’]
db2 grant sales to role production
10 Lectures
1.5 hours
Nishant Malik
41 Lectures
8.5 hours
Parth Panjabi
53 Lectures
11.5 hours
Parth Panjabi
33 Lectures
7 hours
Parth Panjabi
44 Lectures
3 hours
Arnab Chakraborty
178 Lectures
14.5 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2075,
"s": 1928,
"text": "A role is a database object that groups multiple privileges that can be assigned to users, groups, PUBLIC or other roles by using GRANT statement."
},
{
"code": null,
"e": 2111,
"s": 2075,
"text": "A role cannot own database objects."
},
{
"code": null,
"e": 2311,
"s": 2111,
"text": "Permissions and roles granted to groups are not considered when you create the following database objects.\n\nPackage Containing static SQL\nViews\nMaterialized Query Tables (MQT)\nTriggers\nSQL Routines\n\n"
},
{
"code": null,
"e": 2341,
"s": 2311,
"text": "Package Containing static SQL"
},
{
"code": null,
"e": 2347,
"s": 2341,
"text": "Views"
},
{
"code": null,
"e": 2379,
"s": 2347,
"text": "Materialized Query Tables (MQT)"
},
{
"code": null,
"e": 2388,
"s": 2379,
"text": "Triggers"
},
{
"code": null,
"e": 2401,
"s": 2388,
"text": "SQL Routines"
},
{
"code": null,
"e": 2432,
"s": 2401,
"text": "Syntax: [To create a new role]"
},
{
"code": null,
"e": 2461,
"s": 2432,
"text": "db2 create role <role_name> "
},
{
"code": null,
"e": 2561,
"s": 2461,
"text": "Example: [To create a new role named ‘sales’ to add some table to be managed by some user or group]"
},
{
"code": null,
"e": 2584,
"s": 2561,
"text": "db2 create role sales "
},
{
"code": null,
"e": 2592,
"s": 2584,
"text": "Output:"
},
{
"code": null,
"e": 2642,
"s": 2592,
"text": "DB20000I The SQL command completed successfully. "
},
{
"code": null,
"e": 2693,
"s": 2642,
"text": "Syntax: [To grant permission of a role to a table]"
},
{
"code": null,
"e": 2753,
"s": 2693,
"text": "db2 grant select on table <table_name> to role <role_name> "
},
{
"code": null,
"e": 2830,
"s": 2753,
"text": "Example: [To add permission to manage a table ‘shope.books’ to role ‘sales’]"
},
{
"code": null,
"e": 2883,
"s": 2830,
"text": "db2 grant select on table shope.books to role sales "
},
{
"code": null,
"e": 2891,
"s": 2883,
"text": "Output:"
},
{
"code": null,
"e": 2942,
"s": 2891,
"text": "DB20000I The SQL command completed successfully. "
},
{
"code": null,
"e": 3061,
"s": 2942,
"text": "Security administrator grants role to the required users. (Before you use this command, you need to create the users.)"
},
{
"code": null,
"e": 3094,
"s": 3061,
"text": "Syntax: [To add users to a role]"
},
{
"code": null,
"e": 3141,
"s": 3094,
"text": "db2 grant role <role_name> to user <username> "
},
{
"code": null,
"e": 3197,
"s": 3141,
"text": "Example: [To add a user ‘mastanvali’ to a role ‘sales’]"
},
{
"code": null,
"e": 3234,
"s": 3197,
"text": "db2 grant sales to user mastanvali "
},
{
"code": null,
"e": 3242,
"s": 3234,
"text": "Output:"
},
{
"code": null,
"e": 3293,
"s": 3242,
"text": "DB20000I The SQL command completed successfully. "
},
{
"code": null,
"e": 3395,
"s": 3293,
"text": "For creating a hierarchies for roles, each role is granted permissions/ membership with another role."
},
{
"code": null,
"e": 3468,
"s": 3395,
"text": "Syntax: [before this syntax create a new role with name of “production”]"
},
{
"code": null,
"e": 3515,
"s": 3468,
"text": "db2 grant role <roll_name> to role <role_name>"
},
{
"code": null,
"e": 3595,
"s": 3515,
"text": "Example: [To provide permission of a role ‘sales’ to another role ‘production’]"
},
{
"code": null,
"e": 3631,
"s": 3595,
"text": "db2 grant sales to role production "
},
{
"code": null,
"e": 3666,
"s": 3631,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3681,
"s": 3666,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3716,
"s": 3681,
"text": "\n 41 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3731,
"s": 3716,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 3767,
"s": 3731,
"text": "\n 53 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 3782,
"s": 3767,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 3815,
"s": 3782,
"text": "\n 33 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3830,
"s": 3815,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 3863,
"s": 3830,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3882,
"s": 3863,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3919,
"s": 3882,
"text": "\n 178 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 3938,
"s": 3919,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3945,
"s": 3938,
"text": " Print"
},
{
"code": null,
"e": 3956,
"s": 3945,
"text": " Add Notes"
}
] |
Python | sympy.factorint() method - GeeksforGeeks
|
05 Sep, 2019
With the help of sympy.factorint() method, we can find the factors and their corresponding multiplicities of a given integer. For input less than 2, factorint() behaves as follows:
– returns the empty factorization {}.
– returns .
– adds to the factors and then factors .
Syntax:factorint(n)
Parameter:n – It denotes an integer.
Returns:Returns a dictionary containing the prime factors of n as keysand their respective multiplicities as values.
Example #1:
# import factorint() method from sympyfrom sympy import factorint n = 2**3 * 3**4 * 5**6 # Use factorint() method factor_dict = factorint(n) print("Dictionary containing factors of {} with respective multiplicities : {}". format(n, factor_dict))
Output:
Dictionary containing factors of 10125000
with respective multiplicities : {2: 3, 3: 4, 5: 6}
Example #2:
# import factorint() method from sympyfrom sympy import factorint n = 6**4 * 13 # Use factorint() method factor_dict = factorint(n) print("Dictionary containing factors of {} with respective multiplicities : {}". format(n, factor_dict))
Output:
Dictionary containing factors of 16848
with respective multiplicities : {2: 4, 3: 4, 13: 1}
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25719,
"s": 25691,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 25900,
"s": 25719,
"text": "With the help of sympy.factorint() method, we can find the factors and their corresponding multiplicities of a given integer. For input less than 2, factorint() behaves as follows:"
},
{
"code": null,
"e": 25939,
"s": 25900,
"text": " – returns the empty factorization {}."
},
{
"code": null,
"e": 25952,
"s": 25939,
"text": " – returns ."
},
{
"code": null,
"e": 25995,
"s": 25952,
"text": " – adds to the factors and then factors ."
},
{
"code": null,
"e": 26015,
"s": 25995,
"text": "Syntax:factorint(n)"
},
{
"code": null,
"e": 26052,
"s": 26015,
"text": "Parameter:n – It denotes an integer."
},
{
"code": null,
"e": 26169,
"s": 26052,
"text": "Returns:Returns a dictionary containing the prime factors of n as keysand their respective multiplicities as values."
},
{
"code": null,
"e": 26181,
"s": 26169,
"text": "Example #1:"
},
{
"code": "# import factorint() method from sympyfrom sympy import factorint n = 2**3 * 3**4 * 5**6 # Use factorint() method factor_dict = factorint(n) print(\"Dictionary containing factors of {} with respective multiplicities : {}\". format(n, factor_dict))",
"e": 26440,
"s": 26181,
"text": null
},
{
"code": null,
"e": 26448,
"s": 26440,
"text": "Output:"
},
{
"code": null,
"e": 26544,
"s": 26448,
"text": "Dictionary containing factors of 10125000 \nwith respective multiplicities : {2: 3, 3: 4, 5: 6}\n"
},
{
"code": null,
"e": 26556,
"s": 26544,
"text": "Example #2:"
},
{
"code": "# import factorint() method from sympyfrom sympy import factorint n = 6**4 * 13 # Use factorint() method factor_dict = factorint(n) print(\"Dictionary containing factors of {} with respective multiplicities : {}\". format(n, factor_dict))",
"e": 26806,
"s": 26556,
"text": null
},
{
"code": null,
"e": 26814,
"s": 26806,
"text": "Output:"
},
{
"code": null,
"e": 26908,
"s": 26814,
"text": "Dictionary containing factors of 16848 \nwith respective multiplicities : {2: 4, 3: 4, 13: 1}\n"
},
{
"code": null,
"e": 26915,
"s": 26908,
"text": "Python"
},
{
"code": null,
"e": 27013,
"s": 26915,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27031,
"s": 27013,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27066,
"s": 27031,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27098,
"s": 27066,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27120,
"s": 27098,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27162,
"s": 27120,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27192,
"s": 27162,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27218,
"s": 27192,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27247,
"s": 27218,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27291,
"s": 27247,
"text": "Reading and Writing to text files in Python"
}
] |
Kotlin Map : mapOf()
|
19 Nov, 2021
Kotlin map is a collection which contains pairs of objects. Map holds the data in the form of pairs which consists of a key and a value. Map keys are unique and the map holds only one value for each key. Kotlin distinguishes between immutable and mutable maps. Immutable maps created with mapOf() means these are read-only and and mutable maps created with mutableMapOf() means we can perform read and write both.Syntax :
fun <K, V> mapOf(vararg pairs: Pair<K, V>): Map<K, V>
The first value of the pair is the key and the second is the value of the corresponding key .
If multiple pair have same key then map will return the last pair value.
The map entries is traversed in the specified order.
Kotlin program of mapOf()
Java
fun main(args: Array<String>){ //declaring a map of integer to string val map = mapOf(1 to "Geeks", 2 to "for" , 3 to "Geeks") //printing the map println( map)}
Output:
{1=Geeks, 2=for, 3=Geeks}
Java
fun main(args: Array<String>){ //declaring a map of integer to string val map = mapOf(1 to "One", 2 to "Two" , 3 to "Three", 4 to "Four") println("Map Entries : "+map) println("Map Keys: "+map.keys ) println("Map Values: "+map.values )}
Output:
Map Entries : {1=One, 2=Two, 3=Three, 4=Four}
Map Keys: [1, 2, 3, 4]
Map Values: [One, Two, Three, Four]
We can determine the size of map using two methods. By using the size property of the map and by using the count() method.
Java
fun main() { val ranks = mapOf(1 to "India",2 to "Australia",3 to "England",4 to "Africa") //method 1 println("The size of the map is: "+ranks.size) //method 2 println("The size of the map is: "+ranks.count())}
Output:
The size of the map is: 4
The size of the map is: 4
We can create an empty serialize-able map using mapOf()Example 2 of mapOf()
Java
fun main(args: Array<String>){ //here we have created an empty map using mapOf() val map1 = mapOf<String , Int>() println("Entries: " + map1.entries) //entries of map println("Keys:" + map1.keys) //keys of map println("Values:" + map1.values) //values of map }
Output:
Entries: []
Keys:[]
Values:[]
We can retrieve values from a map using different methods discussed in the below program.
Java
fun main() { val ranks = mapOf(1 to "India",2 to "Australia",3 to "England",4 to "Africa") //method 1 println("Team having rank #1 is: "+ranks[1]) //method 2 println("Team having rank #3 is: "+ranks.getValue(3)) //method 3 println("Team having rank #4 is: "+ranks.getOrDefault(4, 0)) // method 4 val team = ranks.getOrElse(2 ,{ 0 }) println(team)}
Output:
Team having rank #1 is: India
Team having rank #3 is: England
Team having rank #4 is: Africa
Australia
We can determine that a map contains a key or value using the containsKey() and containsValue() methods respectively.
Java
fun main() { val colorsTopToBottom = mapOf("red" to 1, "orange" to 2, "yellow" to 3, "green" to 4 , "blue" to 5, "indigo" to 6, "violet" to 7) var color = "yellow" if (colorsTopToBottom.containsKey(color)) { println("Yes, it contains color $color") } else { println("No, it does not contain color $color") } val value = 8 if (colorsTopToBottom.containsValue(value)) { println("Yes, it contains value $value") } else { println("No, it does not contain value $value") }}
Output:
Yes, it contains color yellow
No, it does not contain value 8
If two values have same key value , then the map will contain the last value of the those numbers.Example 3 of mapOf()
Java
fun main(args: Array<String>){ //lets make two values with same key val map = mapOf(1 to "geeks1",2 to "for" , 1 to "geeks2") // return the map entries println("Entries of map : " + map.entries)}
Output:
Entries of map : [1=geeks2, 2=for]
Explanation : Here key value 1 has been initialized with two values : geeks1 and geeks2, but as we know that mapOf() can have only one value for one key item, therefore the last value is only stored by the map and geeks1 is eliminated.
surindertarika1234
Kotlin Collections
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n19 Nov, 2021"
},
{
"code": null,
"e": 476,
"s": 53,
"text": "Kotlin map is a collection which contains pairs of objects. Map holds the data in the form of pairs which consists of a key and a value. Map keys are unique and the map holds only one value for each key. Kotlin distinguishes between immutable and mutable maps. Immutable maps created with mapOf() means these are read-only and and mutable maps created with mutableMapOf() means we can perform read and write both.Syntax : "
},
{
"code": null,
"e": 531,
"s": 476,
"text": "fun <K, V> mapOf(vararg pairs: Pair<K, V>): Map<K, V> "
},
{
"code": null,
"e": 625,
"s": 531,
"text": "The first value of the pair is the key and the second is the value of the corresponding key ."
},
{
"code": null,
"e": 698,
"s": 625,
"text": "If multiple pair have same key then map will return the last pair value."
},
{
"code": null,
"e": 751,
"s": 698,
"text": "The map entries is traversed in the specified order."
},
{
"code": null,
"e": 778,
"s": 751,
"text": "Kotlin program of mapOf() "
},
{
"code": null,
"e": 783,
"s": 778,
"text": "Java"
},
{
"code": "fun main(args: Array<String>){ //declaring a map of integer to string val map = mapOf(1 to \"Geeks\", 2 to \"for\" , 3 to \"Geeks\") //printing the map println( map)}",
"e": 956,
"s": 783,
"text": null
},
{
"code": null,
"e": 965,
"s": 956,
"text": "Output: "
},
{
"code": null,
"e": 991,
"s": 965,
"text": "{1=Geeks, 2=for, 3=Geeks}"
},
{
"code": null,
"e": 996,
"s": 991,
"text": "Java"
},
{
"code": "fun main(args: Array<String>){ //declaring a map of integer to string val map = mapOf(1 to \"One\", 2 to \"Two\" , 3 to \"Three\", 4 to \"Four\") println(\"Map Entries : \"+map) println(\"Map Keys: \"+map.keys ) println(\"Map Values: \"+map.values )}",
"e": 1251,
"s": 996,
"text": null
},
{
"code": null,
"e": 1260,
"s": 1251,
"text": "Output: "
},
{
"code": null,
"e": 1366,
"s": 1260,
"text": "Map Entries : {1=One, 2=Two, 3=Three, 4=Four}\nMap Keys: [1, 2, 3, 4]\nMap Values: [One, Two, Three, Four] "
},
{
"code": null,
"e": 1490,
"s": 1366,
"text": "We can determine the size of map using two methods. By using the size property of the map and by using the count() method. "
},
{
"code": null,
"e": 1495,
"s": 1490,
"text": "Java"
},
{
"code": "fun main() { val ranks = mapOf(1 to \"India\",2 to \"Australia\",3 to \"England\",4 to \"Africa\") //method 1 println(\"The size of the map is: \"+ranks.size) //method 2 println(\"The size of the map is: \"+ranks.count())}",
"e": 1722,
"s": 1495,
"text": null
},
{
"code": null,
"e": 1731,
"s": 1722,
"text": "Output: "
},
{
"code": null,
"e": 1784,
"s": 1731,
"text": "The size of the map is: 4\nThe size of the map is: 4 "
},
{
"code": null,
"e": 1861,
"s": 1784,
"text": "We can create an empty serialize-able map using mapOf()Example 2 of mapOf() "
},
{
"code": null,
"e": 1866,
"s": 1861,
"text": "Java"
},
{
"code": "fun main(args: Array<String>){ //here we have created an empty map using mapOf() val map1 = mapOf<String , Int>() println(\"Entries: \" + map1.entries) //entries of map println(\"Keys:\" + map1.keys) //keys of map println(\"Values:\" + map1.values) //values of map }",
"e": 2156,
"s": 1866,
"text": null
},
{
"code": null,
"e": 2165,
"s": 2156,
"text": "Output: "
},
{
"code": null,
"e": 2196,
"s": 2165,
"text": "Entries: []\nKeys:[]\nValues:[] "
},
{
"code": null,
"e": 2287,
"s": 2196,
"text": "We can retrieve values from a map using different methods discussed in the below program. "
},
{
"code": null,
"e": 2292,
"s": 2287,
"text": "Java"
},
{
"code": "fun main() { val ranks = mapOf(1 to \"India\",2 to \"Australia\",3 to \"England\",4 to \"Africa\") //method 1 println(\"Team having rank #1 is: \"+ranks[1]) //method 2 println(\"Team having rank #3 is: \"+ranks.getValue(3)) //method 3 println(\"Team having rank #4 is: \"+ranks.getOrDefault(4, 0)) // method 4 val team = ranks.getOrElse(2 ,{ 0 }) println(team)}",
"e": 2673,
"s": 2292,
"text": null
},
{
"code": null,
"e": 2682,
"s": 2673,
"text": "Output: "
},
{
"code": null,
"e": 2785,
"s": 2682,
"text": "Team having rank #1 is: India\nTeam having rank #3 is: England\nTeam having rank #4 is: Africa\nAustralia"
},
{
"code": null,
"e": 2904,
"s": 2785,
"text": "We can determine that a map contains a key or value using the containsKey() and containsValue() methods respectively. "
},
{
"code": null,
"e": 2909,
"s": 2904,
"text": "Java"
},
{
"code": "fun main() { val colorsTopToBottom = mapOf(\"red\" to 1, \"orange\" to 2, \"yellow\" to 3, \"green\" to 4 , \"blue\" to 5, \"indigo\" to 6, \"violet\" to 7) var color = \"yellow\" if (colorsTopToBottom.containsKey(color)) { println(\"Yes, it contains color $color\") } else { println(\"No, it does not contain color $color\") } val value = 8 if (colorsTopToBottom.containsValue(value)) { println(\"Yes, it contains value $value\") } else { println(\"No, it does not contain value $value\") }}",
"e": 3440,
"s": 2909,
"text": null
},
{
"code": null,
"e": 3449,
"s": 3440,
"text": "Output: "
},
{
"code": null,
"e": 3512,
"s": 3449,
"text": "Yes, it contains color yellow\nNo, it does not contain value 8 "
},
{
"code": null,
"e": 3632,
"s": 3512,
"text": "If two values have same key value , then the map will contain the last value of the those numbers.Example 3 of mapOf() "
},
{
"code": null,
"e": 3637,
"s": 3632,
"text": "Java"
},
{
"code": "fun main(args: Array<String>){ //lets make two values with same key val map = mapOf(1 to \"geeks1\",2 to \"for\" , 1 to \"geeks2\") // return the map entries println(\"Entries of map : \" + map.entries)}",
"e": 3845,
"s": 3637,
"text": null
},
{
"code": null,
"e": 3855,
"s": 3845,
"text": "Output: "
},
{
"code": null,
"e": 3890,
"s": 3855,
"text": "Entries of map : [1=geeks2, 2=for]"
},
{
"code": null,
"e": 4126,
"s": 3890,
"text": "Explanation : Here key value 1 has been initialized with two values : geeks1 and geeks2, but as we know that mapOf() can have only one value for one key item, therefore the last value is only stored by the map and geeks1 is eliminated."
},
{
"code": null,
"e": 4145,
"s": 4126,
"text": "surindertarika1234"
},
{
"code": null,
"e": 4164,
"s": 4145,
"text": "Kotlin Collections"
},
{
"code": null,
"e": 4171,
"s": 4164,
"text": "Picked"
},
{
"code": null,
"e": 4178,
"s": 4171,
"text": "Kotlin"
}
] |
How to get the address for an element in Python array?
|
23 Aug, 2021
In this article we are going to discuss about getting the address of an particular element in the Python array. In python we can create the array using numpy. Numpy stands for numeric python used to create and process arrays. We have to import numpy module
import numpy as np
Syntax to create array:
np.ndarray([element1,element2,....,element n])
we can get the address by using data through array index.
Syntax:
array[index].data
It will return the memory of that element present at the given index. Given below are implementations for the same.
Example: Python code to create an array of 10 elements and access the memory of some elements
Python3
# import numpy moduleimport numpy as np # create an array of 10 elementsa = np.array([1, 2, 3, 4, 5, 6, 7, 34, 56, 78]) # get index 4 element addressprint("The element present at 4 th index - element", a[4], ":", a[4].data) # get index 5 element addressprint("The element present at 5 th index - element", a[5], ":", a[5].data) # get index 1 element addressprint("The element present at 1 st index - element", a[1], ":", a[1].data) # get index 0 element addressprint("The element present at 0 th index - element", a[0], ":", a[0].data)
Output:
The element present at 4 th index – element 5 : <memory at 0x7f9e01221680>
The element present at 5 th index – element 6 : <memory at 0x7f9e01221680>
The element present at 1 st index – element 2 : <memory at 0x7f9e01221680>
The element present at 0 th index – element 1 : <memory at 0x7f9e01221680>
We can get all the memory details by using this method so obviously memory address will also be returned.
Syntax:
arr[index].__array_interface__
Example: Python code to get the address details of array elements
Python3
# import numpy moduleimport numpy as np # create an array of 10 elementsa = np.array([1, 2, 3, 4, 5, 6, 7, 34, 56, 78]) # get index 4 element addressprint("The element present at 4 th index - element", a[4], ":", a[4].__array_interface__) # get index 5 element addressprint("The element present at 5 th index - element", a[5], ":", a[5].__array_interface__) # get index 1 element addressprint("The element present at 1 st index - element", a[1], ":", a[1].__array_interface__) # get index 0 element addressprint("The element present at 0 th index - element", a[0], ":", a[0].__array_interface__)
Output:
The element present at 4 th index – element 5 : {‘data’: (94734975551568, False), ‘strides’: None, ‘descr’: [(”, ‘<i8’)], ‘typestr’: ‘<i8’, ‘shape’: (), ‘version’: 3, ‘__ref’: array(5)}
The element present at 5 th index – element 6 : {‘data’: (94734975551568, False), ‘strides’: None, ‘descr’: [(”, ‘<i8’)], ‘typestr’: ‘<i8’, ‘shape’: (), ‘version’: 3, ‘__ref’: array(6)}
The element present at 1 st index – element 2 : {‘data’: (94734975551568, False), ‘strides’: None, ‘descr’: [(”, ‘<i8’)], ‘typestr’: ‘<i8’, ‘shape’: (), ‘version’: 3, ‘__ref’: array(2)}
The element present at 0 th index – element 1 : {‘data’: (94734975551568, False), ‘strides’: None, ‘descr’: [(”, ‘<i8’)], ‘typestr’: ‘<i8’, ‘shape’: (), ‘version’: 3, ‘__ref’: array(1)}
Picked
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 285,
"s": 28,
"text": "In this article we are going to discuss about getting the address of an particular element in the Python array. In python we can create the array using numpy. Numpy stands for numeric python used to create and process arrays. We have to import numpy module"
},
{
"code": null,
"e": 304,
"s": 285,
"text": "import numpy as np"
},
{
"code": null,
"e": 328,
"s": 304,
"text": "Syntax to create array:"
},
{
"code": null,
"e": 375,
"s": 328,
"text": "np.ndarray([element1,element2,....,element n])"
},
{
"code": null,
"e": 433,
"s": 375,
"text": "we can get the address by using data through array index."
},
{
"code": null,
"e": 441,
"s": 433,
"text": "Syntax:"
},
{
"code": null,
"e": 459,
"s": 441,
"text": "array[index].data"
},
{
"code": null,
"e": 575,
"s": 459,
"text": "It will return the memory of that element present at the given index. Given below are implementations for the same."
},
{
"code": null,
"e": 669,
"s": 575,
"text": "Example: Python code to create an array of 10 elements and access the memory of some elements"
},
{
"code": null,
"e": 677,
"s": 669,
"text": "Python3"
},
{
"code": "# import numpy moduleimport numpy as np # create an array of 10 elementsa = np.array([1, 2, 3, 4, 5, 6, 7, 34, 56, 78]) # get index 4 element addressprint(\"The element present at 4 th index - element\", a[4], \":\", a[4].data) # get index 5 element addressprint(\"The element present at 5 th index - element\", a[5], \":\", a[5].data) # get index 1 element addressprint(\"The element present at 1 st index - element\", a[1], \":\", a[1].data) # get index 0 element addressprint(\"The element present at 0 th index - element\", a[0], \":\", a[0].data)",
"e": 1240,
"s": 677,
"text": null
},
{
"code": null,
"e": 1248,
"s": 1240,
"text": "Output:"
},
{
"code": null,
"e": 1324,
"s": 1248,
"text": "The element present at 4 th index – element 5 : <memory at 0x7f9e01221680>"
},
{
"code": null,
"e": 1399,
"s": 1324,
"text": "The element present at 5 th index – element 6 : <memory at 0x7f9e01221680>"
},
{
"code": null,
"e": 1474,
"s": 1399,
"text": "The element present at 1 st index – element 2 : <memory at 0x7f9e01221680>"
},
{
"code": null,
"e": 1550,
"s": 1474,
"text": "The element present at 0 th index – element 1 : <memory at 0x7f9e01221680>"
},
{
"code": null,
"e": 1656,
"s": 1550,
"text": "We can get all the memory details by using this method so obviously memory address will also be returned."
},
{
"code": null,
"e": 1664,
"s": 1656,
"text": "Syntax:"
},
{
"code": null,
"e": 1695,
"s": 1664,
"text": "arr[index].__array_interface__"
},
{
"code": null,
"e": 1761,
"s": 1695,
"text": "Example: Python code to get the address details of array elements"
},
{
"code": null,
"e": 1769,
"s": 1761,
"text": "Python3"
},
{
"code": "# import numpy moduleimport numpy as np # create an array of 10 elementsa = np.array([1, 2, 3, 4, 5, 6, 7, 34, 56, 78]) # get index 4 element addressprint(\"The element present at 4 th index - element\", a[4], \":\", a[4].__array_interface__) # get index 5 element addressprint(\"The element present at 5 th index - element\", a[5], \":\", a[5].__array_interface__) # get index 1 element addressprint(\"The element present at 1 st index - element\", a[1], \":\", a[1].__array_interface__) # get index 0 element addressprint(\"The element present at 0 th index - element\", a[0], \":\", a[0].__array_interface__)",
"e": 2392,
"s": 1769,
"text": null
},
{
"code": null,
"e": 2400,
"s": 2392,
"text": "Output:"
},
{
"code": null,
"e": 2587,
"s": 2400,
"text": "The element present at 4 th index – element 5 : {‘data’: (94734975551568, False), ‘strides’: None, ‘descr’: [(”, ‘<i8’)], ‘typestr’: ‘<i8’, ‘shape’: (), ‘version’: 3, ‘__ref’: array(5)}"
},
{
"code": null,
"e": 2773,
"s": 2587,
"text": "The element present at 5 th index – element 6 : {‘data’: (94734975551568, False), ‘strides’: None, ‘descr’: [(”, ‘<i8’)], ‘typestr’: ‘<i8’, ‘shape’: (), ‘version’: 3, ‘__ref’: array(6)}"
},
{
"code": null,
"e": 2959,
"s": 2773,
"text": "The element present at 1 st index – element 2 : {‘data’: (94734975551568, False), ‘strides’: None, ‘descr’: [(”, ‘<i8’)], ‘typestr’: ‘<i8’, ‘shape’: (), ‘version’: 3, ‘__ref’: array(2)}"
},
{
"code": null,
"e": 3146,
"s": 2959,
"text": "The element present at 0 th index – element 1 : {‘data’: (94734975551568, False), ‘strides’: None, ‘descr’: [(”, ‘<i8’)], ‘typestr’: ‘<i8’, ‘shape’: (), ‘version’: 3, ‘__ref’: array(1)}"
},
{
"code": null,
"e": 3153,
"s": 3146,
"text": "Picked"
},
{
"code": null,
"e": 3166,
"s": 3153,
"text": "Python-numpy"
},
{
"code": null,
"e": 3173,
"s": 3166,
"text": "Python"
},
{
"code": null,
"e": 3271,
"s": 3173,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3303,
"s": 3271,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3330,
"s": 3303,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3351,
"s": 3330,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3374,
"s": 3351,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3430,
"s": 3374,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3461,
"s": 3430,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3503,
"s": 3461,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3545,
"s": 3503,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3584,
"s": 3545,
"text": "Python | Get unique values from a list"
}
] |
Find the number of occurrences of a character upto preceding position
|
11 Jun, 2021
Given a string S of length N and an integer P(1≤P≤N) denoting the position of a character in the string. The task is to find the number of occurrences of the character present at the position P upto P-1 index.
Examples:
Input : S = “ababababab”, P = 9 Output : 4 Character at P is ‘a’. Number of occurrences of ‘a’ upto 8th index is 4
Input : S = “geeksforgeeks”, P = 9 Output : 1
Naive Approach :A naive approach is to iterate over the string till Position-1 searching for a similar character. Whenever a similar character occurs increment counter variable by one.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// CPP program to find the number of occurrences// of a character at position P upto p-1#include <bits/stdc++.h>using namespace std; // Function to find the number of occurrences// of a character at position P upto p-1int Occurrence(string s, int position){ int count = 0; for (int i = 0; i < position - 1; i++) if (s[i] == s[position - 1]) count++; // Return the required count return count;} // Driver codeint main(){ string s = "ababababab"; int p = 9; // Function call cout << Occurrence(s, p); return 0;}
// Java program to find the number of occurrences// of a character at position P upto p-1class GFG{ // Function to find the number of occurrences// of a character at position P upto p-1static int Occurrence(String s, int position){ int count = 0; for (int i = 0; i < position - 1; i++) if (s.charAt(i) == s.charAt(position - 1)) count++; // Return the required count return count;} // Driver codepublic static void main(String[] args){ String s = "ababababab"; int p = 9; // Function call System.out.println(Occurrence(s, p));}} // This code is contributed by 29AjayKumar
# Python3 program to find the# number of occurrences of# a character at position P upto p-1 # Function to find the number of occurrences# of a character at position P upto p-1def Occurrence(s, position): count = 0 for i in range(position - 1): if (s[i] == s[position - 1]): count += 1 # Return the required count return count # Driver codes = "ababababab"; p = 9 # Function callprint(Occurrence(s, p)) # This code is contributed by Mohit Kumar
// C# program to find the number of occurrences// of a character at position P upto p-1using System; class GFG{ // Function to find the number of occurrences// of a character at position P upto p-1static int Occurrence(String s, int position){ int count = 0; for (int i = 0; i < position - 1; i++) if (s[i] == s[position - 1]) count++; // Return the required count return count;} // Driver codepublic static void Main(String[] args){ String s = "ababababab"; int p = 9; // Function call Console.WriteLine(Occurrence(s, p));}} // This code is contributed by PrinciRaj1992
<script>// Javascript program to find the number of occurrences// of a character at position P upto p-1 // Function to find the number of occurrences// of a character at position P upto p-1function Occurrence(s,position){ let count = 0; for (let i = 0; i < position - 1; i++) if (s[i] == s[position - 1]) count++; // Return the required count return count;} // Driver codelet s = "ababababab"; let p = 9; // Function calldocument.write(Occurrence(s, p)); // This code is contributed by unknown2108</script>
4
Time Complexity : O(N) for each query.
Efficient Approach: In case, if there are multiple such queries and we are given a unique index P for every query then an efficient approach is to use a frequency array for storing the character count in each iteration of the string.
Below is the implementation of the above approach :
C++
Java
Python3
C#
Javascript
// CPP program to find the number of occurrences// of a character at position P upto p-1#include <bits/stdc++.h>using namespace std; // Function to find the number of occurrences// of a character at position P upto p-1int countOccurrence(string s, int position){ int alpha[26] = { 0 }, b[s.size()] = { 0 }; // Iterate over the string for (int i = 0; i < s.size(); i++) { // Store the Occurrence of same character b[i] = alpha[(int)s[i] - 97]; // Increase its frequency alpha[(int)s[i] - 97]++; } // Return the required count return b[position - 1];} // Driver codeint main(){ string s = "ababababab"; int p = 9; // Function call cout << countOccurrence(s, p); return 0;}
// Java program to find the number of occurrences// of a character at position P upto p-1import java.util.*; class GFG{ // Function to find the number of occurrences// of a character at position P upto p-1static int countOccurrence(String s, int position){ int []alpha = new int[26]; int []b = new int[s.length()]; // Iterate over the string for (int i = 0; i < s.length(); i++) { // Store the Occurrence of same character b[i] = alpha[(int)s.charAt(i) - 97]; // Increase its frequency alpha[(int)s.charAt(i) - 97]++; } // Return the required count return b[position - 1];} // Driver codepublic static void main(String[] args){ String s = "ababababab"; int p = 9; // Function call System.out.println(countOccurrence(s, p));}} // This code is contributed by 29AjayKumar
# Python3 program to find the number of occurrences# of a character at position P upto p-1 # Function to find the number of occurrences# of a character at position P upto p-1def countOccurrence(s, position): alpha = [0] * 26 b = [0] * len(s) # Iterate over the string for i in range(0, len(s)): # Store the Occurrence of same character b[i] = alpha[ord(s[i]) - 97] # Increase its frequency alpha[ord(s[i]) - 97] = alpha[ord(s[i]) - 97] + 1 # Return the required count return b[position - 1] # Driver codes = "ababababab" p = 9 # Function callprint(countOccurrence(s, p)) # This code is contributed by Sanjit_Prasad
// C# program to find the number of occurrences// of a character at position P upto p-1using System; class GFG{ // Function to find the number of occurrences// of a character at position P upto p-1static int countOccurrence(String s, int position){ int []alpha = new int[26]; int []b = new int[s.Length]; // Iterate over the string for (int i = 0; i < s.Length; i++) { // Store the Occurrence of same character b[i] = alpha[(int)s[i] - 97]; // Increase its frequency alpha[(int)s[i] - 97]++; } // Return the required count return b[position - 1];} // Driver codepublic static void Main(String[] args){ String s = "ababababab"; int p = 9; // Function call Console.WriteLine(countOccurrence(s, p));}} // This code is contributed by PrinciRaj1992
<script> // Javascript program to find the number of occurrences// of a character at position P upto p-1 // Function to find the number of occurrences// of a character at position P upto p-1function countOccurrence(s, position){ let alpha = new Array(26); for(let i = 0; i < 26; i++) { alpha[i] = 0; } let b = new Array(s.length); // Iterate over the string for(let i = 0; i < s.length; i++) { // Store the Occurrence of same character b[i] = alpha[s[i].charCodeAt(0) - 97]; // Increase its frequency alpha[s[i].charCodeAt(0) - 97]++; } // Return the required count return b[position - 1];} // Driver codelet s = "ababababab"; p = 9; // Function calldocument.write(countOccurrence(s, p)); // This code is contributed by patel2127 </script>
4
mohit kumar 29
shubham_singh
29AjayKumar
princiraj1992
Sanjit_Prasad
nidhi_biet
unknown2108
patel2127
frequency-counting
prefix
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 238,
"s": 28,
"text": "Given a string S of length N and an integer P(1≤P≤N) denoting the position of a character in the string. The task is to find the number of occurrences of the character present at the position P upto P-1 index."
},
{
"code": null,
"e": 249,
"s": 238,
"text": "Examples: "
},
{
"code": null,
"e": 364,
"s": 249,
"text": "Input : S = “ababababab”, P = 9 Output : 4 Character at P is ‘a’. Number of occurrences of ‘a’ upto 8th index is 4"
},
{
"code": null,
"e": 410,
"s": 364,
"text": "Input : S = “geeksforgeeks”, P = 9 Output : 1"
},
{
"code": null,
"e": 596,
"s": 410,
"text": "Naive Approach :A naive approach is to iterate over the string till Position-1 searching for a similar character. Whenever a similar character occurs increment counter variable by one. "
},
{
"code": null,
"e": 649,
"s": 596,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 653,
"s": 649,
"text": "C++"
},
{
"code": null,
"e": 658,
"s": 653,
"text": "Java"
},
{
"code": null,
"e": 666,
"s": 658,
"text": "Python3"
},
{
"code": null,
"e": 669,
"s": 666,
"text": "C#"
},
{
"code": null,
"e": 680,
"s": 669,
"text": "Javascript"
},
{
"code": "// CPP program to find the number of occurrences// of a character at position P upto p-1#include <bits/stdc++.h>using namespace std; // Function to find the number of occurrences// of a character at position P upto p-1int Occurrence(string s, int position){ int count = 0; for (int i = 0; i < position - 1; i++) if (s[i] == s[position - 1]) count++; // Return the required count return count;} // Driver codeint main(){ string s = \"ababababab\"; int p = 9; // Function call cout << Occurrence(s, p); return 0;}",
"e": 1239,
"s": 680,
"text": null
},
{
"code": "// Java program to find the number of occurrences// of a character at position P upto p-1class GFG{ // Function to find the number of occurrences// of a character at position P upto p-1static int Occurrence(String s, int position){ int count = 0; for (int i = 0; i < position - 1; i++) if (s.charAt(i) == s.charAt(position - 1)) count++; // Return the required count return count;} // Driver codepublic static void main(String[] args){ String s = \"ababababab\"; int p = 9; // Function call System.out.println(Occurrence(s, p));}} // This code is contributed by 29AjayKumar",
"e": 1856,
"s": 1239,
"text": null
},
{
"code": "# Python3 program to find the# number of occurrences of# a character at position P upto p-1 # Function to find the number of occurrences# of a character at position P upto p-1def Occurrence(s, position): count = 0 for i in range(position - 1): if (s[i] == s[position - 1]): count += 1 # Return the required count return count # Driver codes = \"ababababab\"; p = 9 # Function callprint(Occurrence(s, p)) # This code is contributed by Mohit Kumar",
"e": 2331,
"s": 1856,
"text": null
},
{
"code": "// C# program to find the number of occurrences// of a character at position P upto p-1using System; class GFG{ // Function to find the number of occurrences// of a character at position P upto p-1static int Occurrence(String s, int position){ int count = 0; for (int i = 0; i < position - 1; i++) if (s[i] == s[position - 1]) count++; // Return the required count return count;} // Driver codepublic static void Main(String[] args){ String s = \"ababababab\"; int p = 9; // Function call Console.WriteLine(Occurrence(s, p));}} // This code is contributed by PrinciRaj1992",
"e": 2951,
"s": 2331,
"text": null
},
{
"code": "<script>// Javascript program to find the number of occurrences// of a character at position P upto p-1 // Function to find the number of occurrences// of a character at position P upto p-1function Occurrence(s,position){ let count = 0; for (let i = 0; i < position - 1; i++) if (s[i] == s[position - 1]) count++; // Return the required count return count;} // Driver codelet s = \"ababababab\"; let p = 9; // Function calldocument.write(Occurrence(s, p)); // This code is contributed by unknown2108</script>",
"e": 3494,
"s": 2951,
"text": null
},
{
"code": null,
"e": 3496,
"s": 3494,
"text": "4"
},
{
"code": null,
"e": 3537,
"s": 3498,
"text": "Time Complexity : O(N) for each query."
},
{
"code": null,
"e": 3771,
"s": 3537,
"text": "Efficient Approach: In case, if there are multiple such queries and we are given a unique index P for every query then an efficient approach is to use a frequency array for storing the character count in each iteration of the string."
},
{
"code": null,
"e": 3824,
"s": 3771,
"text": "Below is the implementation of the above approach : "
},
{
"code": null,
"e": 3828,
"s": 3824,
"text": "C++"
},
{
"code": null,
"e": 3833,
"s": 3828,
"text": "Java"
},
{
"code": null,
"e": 3841,
"s": 3833,
"text": "Python3"
},
{
"code": null,
"e": 3844,
"s": 3841,
"text": "C#"
},
{
"code": null,
"e": 3855,
"s": 3844,
"text": "Javascript"
},
{
"code": "// CPP program to find the number of occurrences// of a character at position P upto p-1#include <bits/stdc++.h>using namespace std; // Function to find the number of occurrences// of a character at position P upto p-1int countOccurrence(string s, int position){ int alpha[26] = { 0 }, b[s.size()] = { 0 }; // Iterate over the string for (int i = 0; i < s.size(); i++) { // Store the Occurrence of same character b[i] = alpha[(int)s[i] - 97]; // Increase its frequency alpha[(int)s[i] - 97]++; } // Return the required count return b[position - 1];} // Driver codeint main(){ string s = \"ababababab\"; int p = 9; // Function call cout << countOccurrence(s, p); return 0;}",
"e": 4593,
"s": 3855,
"text": null
},
{
"code": "// Java program to find the number of occurrences// of a character at position P upto p-1import java.util.*; class GFG{ // Function to find the number of occurrences// of a character at position P upto p-1static int countOccurrence(String s, int position){ int []alpha = new int[26]; int []b = new int[s.length()]; // Iterate over the string for (int i = 0; i < s.length(); i++) { // Store the Occurrence of same character b[i] = alpha[(int)s.charAt(i) - 97]; // Increase its frequency alpha[(int)s.charAt(i) - 97]++; } // Return the required count return b[position - 1];} // Driver codepublic static void main(String[] args){ String s = \"ababababab\"; int p = 9; // Function call System.out.println(countOccurrence(s, p));}} // This code is contributed by 29AjayKumar",
"e": 5431,
"s": 4593,
"text": null
},
{
"code": "# Python3 program to find the number of occurrences# of a character at position P upto p-1 # Function to find the number of occurrences# of a character at position P upto p-1def countOccurrence(s, position): alpha = [0] * 26 b = [0] * len(s) # Iterate over the string for i in range(0, len(s)): # Store the Occurrence of same character b[i] = alpha[ord(s[i]) - 97] # Increase its frequency alpha[ord(s[i]) - 97] = alpha[ord(s[i]) - 97] + 1 # Return the required count return b[position - 1] # Driver codes = \"ababababab\" p = 9 # Function callprint(countOccurrence(s, p)) # This code is contributed by Sanjit_Prasad",
"e": 6108,
"s": 5431,
"text": null
},
{
"code": "// C# program to find the number of occurrences// of a character at position P upto p-1using System; class GFG{ // Function to find the number of occurrences// of a character at position P upto p-1static int countOccurrence(String s, int position){ int []alpha = new int[26]; int []b = new int[s.Length]; // Iterate over the string for (int i = 0; i < s.Length; i++) { // Store the Occurrence of same character b[i] = alpha[(int)s[i] - 97]; // Increase its frequency alpha[(int)s[i] - 97]++; } // Return the required count return b[position - 1];} // Driver codepublic static void Main(String[] args){ String s = \"ababababab\"; int p = 9; // Function call Console.WriteLine(countOccurrence(s, p));}} // This code is contributed by PrinciRaj1992",
"e": 6925,
"s": 6108,
"text": null
},
{
"code": "<script> // Javascript program to find the number of occurrences// of a character at position P upto p-1 // Function to find the number of occurrences// of a character at position P upto p-1function countOccurrence(s, position){ let alpha = new Array(26); for(let i = 0; i < 26; i++) { alpha[i] = 0; } let b = new Array(s.length); // Iterate over the string for(let i = 0; i < s.length; i++) { // Store the Occurrence of same character b[i] = alpha[s[i].charCodeAt(0) - 97]; // Increase its frequency alpha[s[i].charCodeAt(0) - 97]++; } // Return the required count return b[position - 1];} // Driver codelet s = \"ababababab\"; p = 9; // Function calldocument.write(countOccurrence(s, p)); // This code is contributed by patel2127 </script>",
"e": 7748,
"s": 6925,
"text": null
},
{
"code": null,
"e": 7750,
"s": 7748,
"text": "4"
},
{
"code": null,
"e": 7767,
"s": 7752,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 7781,
"s": 7767,
"text": "shubham_singh"
},
{
"code": null,
"e": 7793,
"s": 7781,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7807,
"s": 7793,
"text": "princiraj1992"
},
{
"code": null,
"e": 7821,
"s": 7807,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 7832,
"s": 7821,
"text": "nidhi_biet"
},
{
"code": null,
"e": 7844,
"s": 7832,
"text": "unknown2108"
},
{
"code": null,
"e": 7854,
"s": 7844,
"text": "patel2127"
},
{
"code": null,
"e": 7873,
"s": 7854,
"text": "frequency-counting"
},
{
"code": null,
"e": 7880,
"s": 7873,
"text": "prefix"
},
{
"code": null,
"e": 7888,
"s": 7880,
"text": "Strings"
},
{
"code": null,
"e": 7896,
"s": 7888,
"text": "Strings"
}
] |
Design a Student Grade Calculator using JavaScript
|
26 Aug, 2021
Student Grade Calculator (SGC) can be used to calculate a percentage based on the marks of students. (SGC) is a fairly reliable indicator of student results.
Formula:
percentage = ( totalgrades / 400 ) * 100 ;
Approach: SGC is a percentage calculator from a student’s marks. To find out SGC we will take input from the user (for the four subjects) stored in Chemistry, Hindi, and Math variables for further calculation. The calculation process is simple, we will simply First we will add all the input marks and store them in the total grades variable after that we will divide it by the sum of maximum marks of each subject. and later on we will let one more variable named as grades which will store the grades. Now as per the percentage calculated, it will execute the respective if-else statement. Printing in the result is a percentage and the grade of the student. Using HTML we are giving desired structure, option for the input, and submit button. With the help of CSS, we are beautifying our structure by giving colors and desired font, etc. In the JavaScript section, we are processing the taken input and after calculating, the respective output is printed.
Steps to create the calculator:
First, we will make a function named as calculate.
Initializing all the variables and storing the values input by the user.
Now converting the values in float data type.
Then we use simple mathematics to perform the calculation.
Then we have implemented the if-else condition.
Then we check the condition for empty inputs and if it is not empty then we will execute our output.
Example: Now let’s start the implementation of the student’s grades calculator.
index.html
<!DOCTYPE html><html> <head> <title>student calculate</title> <!-- link for font --> <link href="https://fonts.googleapis.com/css?family=Righteous&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="style.css" /> </head> <body> <!-- main html --> <div class="container"> <h1>Student grade calculator</h1> <div class="screen-body-item"> <div class="app"> <div class="form-group"> <!-- option for taking the input --> <input type="text" class="form-control" placeholder="CHEMISTRY" id="chemistry" /> </div> <div class="form-group"> <input type="text" class="form-control" placeholder="HINDI" id="hindi" /> </div> <div class="form-group"> <input type="text" class="form-control" placeholder="MATHS" id="maths" /> </div> <div class="form-group"> <input type="text" class="form-control" placeholder="PHYSICS" id="phy" /> </div> <div> <input type="button" value="show Percentage" class="form-button" onclick="calculate()" /> </div> </div> </div> <!-- for showing the result--> <div class="form-group showdata"> <p id="showdata"></p> </div> </div> <!--adding external javascript file--> <script src="script.js"></script> </body></html>
style.css
style.css
* { margin: 0; padding: 0; box-sizing: border-box;}body { background: #006600; font-size: 12px;} .container { flex: 0 1 700px; margin: auto; padding: 10px;} .screen-body-item { flex: 1; padding: 50px;}input { margin: 10px 10px 10px;}.showdata { color: black; font-size: 1.2rem; padding-top: 10px; padding-bottom: 10px;}
script.js
// Function for calculating gradesconst calculate = () => { // Getting input from user into height variable. let chemistry = document.querySelector("#chemistry").value; let hindi = document.querySelector("#hindi").value; let maths = document.querySelector("#maths").value; let phy = document.querySelector("#phy").value; let grades = ""; // Input is string so typecasting is necessary. */ let totalgrades = parseFloat(chemistry) + parseFloat(hindi) + parseFloat(maths) + parseFloat(phy); // Checking the condition for the providing the // grade to student based on percentage let percentage = (totalgrades / 400) * 100; if (percentage <= 100 && percentage >= 80) { grades = "A"; } else if (percentage <= 79 && percentage >= 60) { grades = "B"; } else if (percentage <= 59 && percentage >= 40) { grades = "C"; } else { grades = "F"; } // Checking the values are empty if empty than // show please fill them if (chemistry == "" || hindi == "" || maths == "" || phy == "") { document.querySelector("#showdata").innerHTML = "Please enter all the fields"; } else { // Checking the condition for the fail and pass if (percentage >= 39.5) { document.querySelector( "#showdata" ).innerHTML = ` Out of 400 your total is ${totalgrades} and percentage is ${percentage}%. <br> Your grade is ${grades}. You are Pass. `; } else { document.querySelector( "#showdata" ).innerHTML = ` Out of 400 your total is ${totalgrades} and percentage is ${percentage}%. <br> Your grade is ${grades}. You are Fail. `; } }};
Output:
surindertarika1234
CSS-Properties
CSS-Questions
HTML-Basics
HTML-Questions
HTML-Tags
JavaScript-Methods
JavaScript-Questions
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Aug, 2021"
},
{
"code": null,
"e": 186,
"s": 28,
"text": "Student Grade Calculator (SGC) can be used to calculate a percentage based on the marks of students. (SGC) is a fairly reliable indicator of student results."
},
{
"code": null,
"e": 195,
"s": 186,
"text": "Formula:"
},
{
"code": null,
"e": 240,
"s": 195,
"text": "percentage = ( totalgrades / 400 ) * 100 ;"
},
{
"code": null,
"e": 1199,
"s": 240,
"text": "Approach: SGC is a percentage calculator from a student’s marks. To find out SGC we will take input from the user (for the four subjects) stored in Chemistry, Hindi, and Math variables for further calculation. The calculation process is simple, we will simply First we will add all the input marks and store them in the total grades variable after that we will divide it by the sum of maximum marks of each subject. and later on we will let one more variable named as grades which will store the grades. Now as per the percentage calculated, it will execute the respective if-else statement. Printing in the result is a percentage and the grade of the student. Using HTML we are giving desired structure, option for the input, and submit button. With the help of CSS, we are beautifying our structure by giving colors and desired font, etc. In the JavaScript section, we are processing the taken input and after calculating, the respective output is printed."
},
{
"code": null,
"e": 1231,
"s": 1199,
"text": "Steps to create the calculator:"
},
{
"code": null,
"e": 1282,
"s": 1231,
"text": "First, we will make a function named as calculate."
},
{
"code": null,
"e": 1355,
"s": 1282,
"text": "Initializing all the variables and storing the values input by the user."
},
{
"code": null,
"e": 1401,
"s": 1355,
"text": "Now converting the values in float data type."
},
{
"code": null,
"e": 1460,
"s": 1401,
"text": "Then we use simple mathematics to perform the calculation."
},
{
"code": null,
"e": 1508,
"s": 1460,
"text": "Then we have implemented the if-else condition."
},
{
"code": null,
"e": 1609,
"s": 1508,
"text": "Then we check the condition for empty inputs and if it is not empty then we will execute our output."
},
{
"code": null,
"e": 1691,
"s": 1611,
"text": "Example: Now let’s start the implementation of the student’s grades calculator."
},
{
"code": null,
"e": 1702,
"s": 1691,
"text": "index.html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>student calculate</title> <!-- link for font --> <link href=\"https://fonts.googleapis.com/css?family=Righteous&display=swap\" rel=\"stylesheet\" /> <link rel=\"stylesheet\" href=\"style.css\" /> </head> <body> <!-- main html --> <div class=\"container\"> <h1>Student grade calculator</h1> <div class=\"screen-body-item\"> <div class=\"app\"> <div class=\"form-group\"> <!-- option for taking the input --> <input type=\"text\" class=\"form-control\" placeholder=\"CHEMISTRY\" id=\"chemistry\" /> </div> <div class=\"form-group\"> <input type=\"text\" class=\"form-control\" placeholder=\"HINDI\" id=\"hindi\" /> </div> <div class=\"form-group\"> <input type=\"text\" class=\"form-control\" placeholder=\"MATHS\" id=\"maths\" /> </div> <div class=\"form-group\"> <input type=\"text\" class=\"form-control\" placeholder=\"PHYSICS\" id=\"phy\" /> </div> <div> <input type=\"button\" value=\"show Percentage\" class=\"form-button\" onclick=\"calculate()\" /> </div> </div> </div> <!-- for showing the result--> <div class=\"form-group showdata\"> <p id=\"showdata\"></p> </div> </div> <!--adding external javascript file--> <script src=\"script.js\"></script> </body></html>",
"e": 3410,
"s": 1702,
"text": null
},
{
"code": null,
"e": 3420,
"s": 3410,
"text": "style.css"
},
{
"code": null,
"e": 3430,
"s": 3420,
"text": "style.css"
},
{
"code": "* { margin: 0; padding: 0; box-sizing: border-box;}body { background: #006600; font-size: 12px;} .container { flex: 0 1 700px; margin: auto; padding: 10px;} .screen-body-item { flex: 1; padding: 50px;}input { margin: 10px 10px 10px;}.showdata { color: black; font-size: 1.2rem; padding-top: 10px; padding-bottom: 10px;}",
"e": 3767,
"s": 3430,
"text": null
},
{
"code": null,
"e": 3777,
"s": 3767,
"text": "script.js"
},
{
"code": "// Function for calculating gradesconst calculate = () => { // Getting input from user into height variable. let chemistry = document.querySelector(\"#chemistry\").value; let hindi = document.querySelector(\"#hindi\").value; let maths = document.querySelector(\"#maths\").value; let phy = document.querySelector(\"#phy\").value; let grades = \"\"; // Input is string so typecasting is necessary. */ let totalgrades = parseFloat(chemistry) + parseFloat(hindi) + parseFloat(maths) + parseFloat(phy); // Checking the condition for the providing the // grade to student based on percentage let percentage = (totalgrades / 400) * 100; if (percentage <= 100 && percentage >= 80) { grades = \"A\"; } else if (percentage <= 79 && percentage >= 60) { grades = \"B\"; } else if (percentage <= 59 && percentage >= 40) { grades = \"C\"; } else { grades = \"F\"; } // Checking the values are empty if empty than // show please fill them if (chemistry == \"\" || hindi == \"\" || maths == \"\" || phy == \"\") { document.querySelector(\"#showdata\").innerHTML = \"Please enter all the fields\"; } else { // Checking the condition for the fail and pass if (percentage >= 39.5) { document.querySelector( \"#showdata\" ).innerHTML = ` Out of 400 your total is ${totalgrades} and percentage is ${percentage}%. <br> Your grade is ${grades}. You are Pass. `; } else { document.querySelector( \"#showdata\" ).innerHTML = ` Out of 400 your total is ${totalgrades} and percentage is ${percentage}%. <br> Your grade is ${grades}. You are Fail. `; } }};",
"e": 5445,
"s": 3777,
"text": null
},
{
"code": null,
"e": 5453,
"s": 5445,
"text": "Output:"
},
{
"code": null,
"e": 5472,
"s": 5453,
"text": "surindertarika1234"
},
{
"code": null,
"e": 5487,
"s": 5472,
"text": "CSS-Properties"
},
{
"code": null,
"e": 5501,
"s": 5487,
"text": "CSS-Questions"
},
{
"code": null,
"e": 5513,
"s": 5501,
"text": "HTML-Basics"
},
{
"code": null,
"e": 5528,
"s": 5513,
"text": "HTML-Questions"
},
{
"code": null,
"e": 5538,
"s": 5528,
"text": "HTML-Tags"
},
{
"code": null,
"e": 5557,
"s": 5538,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 5578,
"s": 5557,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 5582,
"s": 5578,
"text": "CSS"
},
{
"code": null,
"e": 5587,
"s": 5582,
"text": "HTML"
},
{
"code": null,
"e": 5598,
"s": 5587,
"text": "JavaScript"
},
{
"code": null,
"e": 5615,
"s": 5598,
"text": "Web Technologies"
},
{
"code": null,
"e": 5620,
"s": 5615,
"text": "HTML"
},
{
"code": null,
"e": 5718,
"s": 5620,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5757,
"s": 5718,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 5796,
"s": 5757,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 5835,
"s": 5796,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 5864,
"s": 5835,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 5901,
"s": 5864,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 5925,
"s": 5901,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 5978,
"s": 5925,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 6038,
"s": 5978,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 6099,
"s": 6038,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Python | Combinations of elements till size N in list
|
27 Aug, 2019
The problem of finding the combinations of list elements of specific size has been discussed. But sometimes, we require more and we wish to have all the combinations of elements of all sizes till N. Let’s discuss certain ways in which this function can be performed.
Method #1 : Using list comprehension + combinations()This task can be performed using the list comprehension which can perform the task of varying the combination length and combination() can perform the actual task of finding combinations.
# Python3 code to demonstrate working of# Combinations of elements till size N in list# Using list comprehension + combinations()from itertools import combinations # initializing listtest_list = [4, 5, 6, 7, 3, 8] # printing original listprint("The original list is : " + str(test_list)) # Combinations of elements till size N in list# Using list comprehension + combinations()res = [com for sub in range(3) for com in combinations(test_list, sub + 1)] # Printing resultprint("The combinations of elements till length N : " + str(res))
The original list is : [4, 5, 6, 7, 3, 8]The combinations of elements till length N : [(4, ), (5, ), (6, ), (7, ), (3, ), (8, ), (4, 5), (4, 6), (4, 7), (4, 3), (4, 8), (5, 6), (5, 7), (5, 3), (5, 8), (6, 7), (6, 3), (6, 8), (7, 3), (7, 8), (3, 8), (4, 5, 6), (4, 5, 7), (4, 5, 3), (4, 5, 8), (4, 6, 7), (4, 6, 3), (4, 6, 8), (4, 7, 3), (4, 7, 8), (4, 3, 8), (5, 6, 7), (5, 6, 3), (5, 6, 8), (5, 7, 3), (5, 7, 8), (5, 3, 8), (6, 7, 3), (6, 7, 8), (6, 3, 8), (7, 3, 8)]
Method 2 : Using loop + extend() + combinations()This method is similar to above method, just the loop is being using to iterate for combination size and extend() performs the task of adding the combinations one after another to final result.
# Python3 code to demonstrate working of# Combinations of elements till size N in list# Using loop + extend() + combinations()from itertools import combinations # initializing listtest_list = [4, 5, 6, 7, 3, 8] # printing original listprint("The original list is : " + str(test_list)) # Combinations of elements till size N in list# Using loop + extend() + combinations()res = []for sub in range(3): res.extend(combinations(test_list, sub + 1)) # Printing resultprint("The combinations of elements till length N : " + str(res))
The original list is : [4, 5, 6, 7, 3, 8]The combinations of elements till length N : [(4, ), (5, ), (6, ), (7, ), (3, ), (8, ), (4, 5), (4, 6), (4, 7), (4, 3), (4, 8), (5, 6), (5, 7), (5, 3), (5, 8), (6, 7), (6, 3), (6, 8), (7, 3), (7, 8), (3, 8), (4, 5, 6), (4, 5, 7), (4, 5, 3), (4, 5, 8), (4, 6, 7), (4, 6, 3), (4, 6, 8), (4, 7, 3), (4, 7, 8), (4, 3, 8), (5, 6, 7), (5, 6, 3), (5, 6, 8), (5, 7, 3), (5, 7, 8), (5, 3, 8), (6, 7, 3), (6, 7, 8), (6, 3, 8), (7, 3, 8)]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Aug, 2019"
},
{
"code": null,
"e": 295,
"s": 28,
"text": "The problem of finding the combinations of list elements of specific size has been discussed. But sometimes, we require more and we wish to have all the combinations of elements of all sizes till N. Let’s discuss certain ways in which this function can be performed."
},
{
"code": null,
"e": 536,
"s": 295,
"text": "Method #1 : Using list comprehension + combinations()This task can be performed using the list comprehension which can perform the task of varying the combination length and combination() can perform the actual task of finding combinations."
},
{
"code": "# Python3 code to demonstrate working of# Combinations of elements till size N in list# Using list comprehension + combinations()from itertools import combinations # initializing listtest_list = [4, 5, 6, 7, 3, 8] # printing original listprint(\"The original list is : \" + str(test_list)) # Combinations of elements till size N in list# Using list comprehension + combinations()res = [com for sub in range(3) for com in combinations(test_list, sub + 1)] # Printing resultprint(\"The combinations of elements till length N : \" + str(res))",
"e": 1078,
"s": 536,
"text": null
},
{
"code": null,
"e": 1547,
"s": 1078,
"text": "The original list is : [4, 5, 6, 7, 3, 8]The combinations of elements till length N : [(4, ), (5, ), (6, ), (7, ), (3, ), (8, ), (4, 5), (4, 6), (4, 7), (4, 3), (4, 8), (5, 6), (5, 7), (5, 3), (5, 8), (6, 7), (6, 3), (6, 8), (7, 3), (7, 8), (3, 8), (4, 5, 6), (4, 5, 7), (4, 5, 3), (4, 5, 8), (4, 6, 7), (4, 6, 3), (4, 6, 8), (4, 7, 3), (4, 7, 8), (4, 3, 8), (5, 6, 7), (5, 6, 3), (5, 6, 8), (5, 7, 3), (5, 7, 8), (5, 3, 8), (6, 7, 3), (6, 7, 8), (6, 3, 8), (7, 3, 8)]"
},
{
"code": null,
"e": 1792,
"s": 1549,
"text": "Method 2 : Using loop + extend() + combinations()This method is similar to above method, just the loop is being using to iterate for combination size and extend() performs the task of adding the combinations one after another to final result."
},
{
"code": "# Python3 code to demonstrate working of# Combinations of elements till size N in list# Using loop + extend() + combinations()from itertools import combinations # initializing listtest_list = [4, 5, 6, 7, 3, 8] # printing original listprint(\"The original list is : \" + str(test_list)) # Combinations of elements till size N in list# Using loop + extend() + combinations()res = []for sub in range(3): res.extend(combinations(test_list, sub + 1)) # Printing resultprint(\"The combinations of elements till length N : \" + str(res))",
"e": 2329,
"s": 1792,
"text": null
},
{
"code": null,
"e": 2798,
"s": 2329,
"text": "The original list is : [4, 5, 6, 7, 3, 8]The combinations of elements till length N : [(4, ), (5, ), (6, ), (7, ), (3, ), (8, ), (4, 5), (4, 6), (4, 7), (4, 3), (4, 8), (5, 6), (5, 7), (5, 3), (5, 8), (6, 7), (6, 3), (6, 8), (7, 3), (7, 8), (3, 8), (4, 5, 6), (4, 5, 7), (4, 5, 3), (4, 5, 8), (4, 6, 7), (4, 6, 3), (4, 6, 8), (4, 7, 3), (4, 7, 8), (4, 3, 8), (5, 6, 7), (5, 6, 3), (5, 6, 8), (5, 7, 3), (5, 7, 8), (5, 3, 8), (6, 7, 3), (6, 7, 8), (6, 3, 8), (7, 3, 8)]"
},
{
"code": null,
"e": 2819,
"s": 2798,
"text": "Python list-programs"
},
{
"code": null,
"e": 2826,
"s": 2819,
"text": "Python"
},
{
"code": null,
"e": 2842,
"s": 2826,
"text": "Python Programs"
},
{
"code": null,
"e": 2940,
"s": 2842,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2972,
"s": 2940,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2999,
"s": 2972,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3020,
"s": 2999,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3043,
"s": 3020,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3099,
"s": 3043,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3121,
"s": 3099,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3160,
"s": 3121,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3198,
"s": 3160,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3247,
"s": 3198,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Difference between forEach() and map() loop in JavaScript
|
01 Jun, 2022
When we work with an array, it is an essential step to iterate on the array to access elements and performing some kind of functionality on those elements to accomplish any task.For example, If you have an array of marks obtained by 20 students and you want to calculate their GPA, if you have an array of images and you want to render it on the frontend, etc. To manage such cases, you must have proper knowledge of how to access the element of the array and how to operate on them.
Other than the basic language constructs i.e. for loop, while loop, and do-while loop, there are two widely used methods for iteration.
.forEach() and .map(): These are the methods that are used to iterate on an array, more technically they invoke the provided callback function for every element of an array.
Syntax:
forEach((currentElement, indexOfElement, array) => { ... } )
map((currentElement, indexOfElement, array) => { ... } )
Parameters:
currentElement: This is the current element that is being processed in the callback.
indexOfElement: The index of that current element inside the array.
array: The array on which the whole operation is being performed.
Example 1: Our objective is to create such a type of functionality that can give square values of the elements of a given array. We have created two arrays, one is working with the forEach() and the other with the map(), and both producing the same result. The element and index are being accessed inside the callback function and we are assigning the square of each element at that index.
JavaScript
<script> /* forEach method */ let myArray1 = [1, 2, 3, 4]; myArray1.forEach((element, index) => { myArray1[index] = element * element; }) console.log(myArray1); /* map method */ let myArray2 = [1, 2, 3, 4]; myArray2.map((element, index) => { myArray2[index] = element * element; }) console.log(myArray2);</script>
Output: With the output image below, we can deduce the working of both methods.
Example 2: We are performing the same functionality but the returned value of forEach() is “undefined” and the returned value of the map() method is an array.
JavaScript
<script> let myArray = [1, 2, 3, 4]; const returnValue = myArray.forEach((element) => { return element * element; }); console.log(returnValue);</script>
Output:
Example 3: The following example demonstrates the map() method.
JavaScript
<script> let myArray = [1, 2, 3, 4]; const returnValue = myArray.map((element) => { return element * element; }) console.log(returnValue);</script>
Output:
Example 4: In this example, we are going to apply the chaining technique, the return value is being operated on the next instance method. We have used the array reverse() method for simplicity but it can be anything i.e sort, find, reduce, filter, etc. Even custom methods can be used for chaining.
JavaScript
<script> let myArray = [1, 2, 3, 4]; const returnValue = myArray.forEach((element) => { return element * element; }).reverse(); console.log(returnValue);</script>
Output: The forEach() method is returning “undefined” and the next instance method(reverse) can be invoked by an array. TypeError is being thrown by JavaScript.
Example 5: The following code demonstrates the reverse() method for the result obtained from the map() method as implemented in the above code.
JavaScript
<script> let myArray = [1, 2, 3, 4]; const returnValue = myArray.map((element) => { return element * element; }).reverse(); console.log(returnValue);</script>
Output: Here the map method returns an array that invokes the next instance method and which later provides the final returnValue(reverse of the invoking array).
Differences between forEach() and map() methods:
Its supported browsers are -:
Chrome , Internet Explorer 9-11 , Opera Mini , Safari , Microsoft Edge , Firefox
Its supported browsers are -:
Chrome , Internet Explorer 9-11 , Opera Mini , Safari , Microsoft Edge , Firefox
Conclusion: As they are working with very few differences, also the execution speed is not significant to consider so it is time to think about, which one to choose? If you want the benefits of the return value or somehow you don’t want to change the original array then proceed with the map() otherwise if you are just interested to iterate or perform the non-transformation process on the array, forEach() could be the better choice.
mayank007rawa
javascript-array
JavaScript-Methods
JavaScript-Questions
Picked
Difference Between
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Similarities and Difference between Java and C++
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Roadmap to Learn JavaScript For Beginners
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n01 Jun, 2022"
},
{
"code": null,
"e": 538,
"s": 53,
"text": "When we work with an array, it is an essential step to iterate on the array to access elements and performing some kind of functionality on those elements to accomplish any task.For example, If you have an array of marks obtained by 20 students and you want to calculate their GPA, if you have an array of images and you want to render it on the frontend, etc. To manage such cases, you must have proper knowledge of how to access the element of the array and how to operate on them. "
},
{
"code": null,
"e": 674,
"s": 538,
"text": "Other than the basic language constructs i.e. for loop, while loop, and do-while loop, there are two widely used methods for iteration."
},
{
"code": null,
"e": 848,
"s": 674,
"text": ".forEach() and .map(): These are the methods that are used to iterate on an array, more technically they invoke the provided callback function for every element of an array."
},
{
"code": null,
"e": 856,
"s": 848,
"text": "Syntax:"
},
{
"code": null,
"e": 917,
"s": 856,
"text": "forEach((currentElement, indexOfElement, array) => { ... } )"
},
{
"code": null,
"e": 974,
"s": 917,
"text": "map((currentElement, indexOfElement, array) => { ... } )"
},
{
"code": null,
"e": 986,
"s": 974,
"text": "Parameters:"
},
{
"code": null,
"e": 1071,
"s": 986,
"text": "currentElement: This is the current element that is being processed in the callback."
},
{
"code": null,
"e": 1139,
"s": 1071,
"text": "indexOfElement: The index of that current element inside the array."
},
{
"code": null,
"e": 1205,
"s": 1139,
"text": "array: The array on which the whole operation is being performed."
},
{
"code": null,
"e": 1595,
"s": 1205,
"text": "Example 1: Our objective is to create such a type of functionality that can give square values of the elements of a given array. We have created two arrays, one is working with the forEach() and the other with the map(), and both producing the same result. The element and index are being accessed inside the callback function and we are assigning the square of each element at that index."
},
{
"code": null,
"e": 1606,
"s": 1595,
"text": "JavaScript"
},
{
"code": "<script> /* forEach method */ let myArray1 = [1, 2, 3, 4]; myArray1.forEach((element, index) => { myArray1[index] = element * element; }) console.log(myArray1); /* map method */ let myArray2 = [1, 2, 3, 4]; myArray2.map((element, index) => { myArray2[index] = element * element; }) console.log(myArray2);</script>",
"e": 1965,
"s": 1606,
"text": null
},
{
"code": null,
"e": 2045,
"s": 1965,
"text": "Output: With the output image below, we can deduce the working of both methods."
},
{
"code": null,
"e": 2205,
"s": 2045,
"text": "Example 2: We are performing the same functionality but the returned value of forEach() is “undefined” and the returned value of the map() method is an array. "
},
{
"code": null,
"e": 2216,
"s": 2205,
"text": "JavaScript"
},
{
"code": "<script> let myArray = [1, 2, 3, 4]; const returnValue = myArray.forEach((element) => { return element * element; }); console.log(returnValue);</script>",
"e": 2389,
"s": 2216,
"text": null
},
{
"code": null,
"e": 2397,
"s": 2389,
"text": "Output:"
},
{
"code": null,
"e": 2461,
"s": 2397,
"text": "Example 3: The following example demonstrates the map() method."
},
{
"code": null,
"e": 2472,
"s": 2461,
"text": "JavaScript"
},
{
"code": "<script> let myArray = [1, 2, 3, 4]; const returnValue = myArray.map((element) => { return element * element; }) console.log(returnValue);</script>",
"e": 2640,
"s": 2472,
"text": null
},
{
"code": null,
"e": 2648,
"s": 2640,
"text": "Output:"
},
{
"code": null,
"e": 2949,
"s": 2648,
"text": "Example 4: In this example, we are going to apply the chaining technique, the return value is being operated on the next instance method. We have used the array reverse() method for simplicity but it can be anything i.e sort, find, reduce, filter, etc. Even custom methods can be used for chaining. "
},
{
"code": null,
"e": 2960,
"s": 2949,
"text": "JavaScript"
},
{
"code": "<script> let myArray = [1, 2, 3, 4]; const returnValue = myArray.forEach((element) => { return element * element; }).reverse(); console.log(returnValue);</script>",
"e": 3143,
"s": 2960,
"text": null
},
{
"code": null,
"e": 3308,
"s": 3143,
"text": "Output: The forEach() method is returning “undefined” and the next instance method(reverse) can be invoked by an array. TypeError is being thrown by JavaScript. "
},
{
"code": null,
"e": 3452,
"s": 3308,
"text": "Example 5: The following code demonstrates the reverse() method for the result obtained from the map() method as implemented in the above code."
},
{
"code": null,
"e": 3463,
"s": 3452,
"text": "JavaScript"
},
{
"code": "<script> let myArray = [1, 2, 3, 4]; const returnValue = myArray.map((element) => { return element * element; }).reverse(); console.log(returnValue);</script>",
"e": 3642,
"s": 3463,
"text": null
},
{
"code": null,
"e": 3804,
"s": 3642,
"text": "Output: Here the map method returns an array that invokes the next instance method and which later provides the final returnValue(reverse of the invoking array)."
},
{
"code": null,
"e": 3853,
"s": 3804,
"text": "Differences between forEach() and map() methods:"
},
{
"code": null,
"e": 3883,
"s": 3853,
"text": "Its supported browsers are -:"
},
{
"code": null,
"e": 3964,
"s": 3883,
"text": "Chrome , Internet Explorer 9-11 , Opera Mini , Safari , Microsoft Edge , Firefox"
},
{
"code": null,
"e": 3994,
"s": 3964,
"text": "Its supported browsers are -:"
},
{
"code": null,
"e": 4075,
"s": 3994,
"text": "Chrome , Internet Explorer 9-11 , Opera Mini , Safari , Microsoft Edge , Firefox"
},
{
"code": null,
"e": 4511,
"s": 4075,
"text": "Conclusion: As they are working with very few differences, also the execution speed is not significant to consider so it is time to think about, which one to choose? If you want the benefits of the return value or somehow you don’t want to change the original array then proceed with the map() otherwise if you are just interested to iterate or perform the non-transformation process on the array, forEach() could be the better choice."
},
{
"code": null,
"e": 4525,
"s": 4511,
"text": "mayank007rawa"
},
{
"code": null,
"e": 4542,
"s": 4525,
"text": "javascript-array"
},
{
"code": null,
"e": 4561,
"s": 4542,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 4582,
"s": 4561,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 4589,
"s": 4582,
"text": "Picked"
},
{
"code": null,
"e": 4608,
"s": 4589,
"text": "Difference Between"
},
{
"code": null,
"e": 4619,
"s": 4608,
"text": "JavaScript"
},
{
"code": null,
"e": 4636,
"s": 4619,
"text": "Web Technologies"
},
{
"code": null,
"e": 4734,
"s": 4636,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4795,
"s": 4734,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4863,
"s": 4795,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 4912,
"s": 4863,
"text": "Similarities and Difference between Java and C++"
},
{
"code": null,
"e": 4967,
"s": 4912,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 5033,
"s": 4967,
"text": "Difference between Compile-time and Run-time Polymorphism in Java"
},
{
"code": null,
"e": 5094,
"s": 5033,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5166,
"s": 5094,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 5206,
"s": 5166,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5259,
"s": 5206,
"text": "Hide or show elements in HTML using display property"
}
] |
Find all possible coordinates of parallelogram
|
22 Jun, 2022
Find the all the possible coordinate from the given three coordinates to make a parallelogram of a non-zero area.Let’s call A,B,C are the three given points. We can have only the three possible situations:
(1) AB and AC are sides, and BC a diagonal
(2) AB and BC are sides, and AC a diagonal
(3) BC and AC are sides, and AB a diagonal
Hence, we can say that only 3 coordinates are possible from which we can generate a parallelogram if three coordinates are given.To prove that all the three points are different let’s suppose it’s wrong. Without losing of generality suppose that the points got in cases AD and BC are equal.
Consider the system of two equations for the equality of these points:
Bx + Cx - Ax = Ax + Cx - Bx
By + Cy - Ay = Ay + Cy - By
It can be simplified as-
Ax = Bx
Ay = By
And we got a contradiction, as all the points A, B, C are distinct.
Examples:
Input : A = (0 0)
B = (1 0)
C = (0 1)
Output : 1 -1
-1 1
1 1
Input : A = (-1 -1)
B = (0 1)
C = (1 1)
Output : -2 -1
0 -1
2 3
Since the opposite sides are equal, AD = BC and AB = CD, we can calculate the co-ordinates of the missing point (D) as:
AD = BC
(Dx - Ax, Dy - Ay) = (Cx - Bx, Cy - By)
Dx = Ax + Cx - Bx
Dy = Ay + Cy - By
The cases where the diagonals are AD and BC, CD and AB are processed in the same way.Reference: https://math.stackexchange.com/questions/1322535/how-many-different-parallelograms-can-be-drawn-if-given-three-co-ordinates-in-3d
Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to all possible points// of a parallelogram#include <bits/stdc++.h>using namespace std; // main methodint main(){ int ax = 5, ay = 0; //coordinates of A int bx = 1, by = 1; //coordinates of B int cx = 2, cy = 5; //coordinates of C cout << ax + bx - cx << ", " << ay + by - cy <<endl; cout << ax + cx - bx << ", " << ay + cy - by <<endl; cout << cx + bx - ax << ", " << cy + by - ax <<endl; return 0;}
// Java program to all possible// points of a parallelogrampublic class ParallelogramPoints{ // Driver code public static void main(String[] s) { int ax = 5, ay = 0; //coordinates of A int bx = 1, by = 1; //coordinates of B int cx = 2, cy = 5; //coordinates of C System.out.println(ax + bx - cx + ", " + (ay + by - cy)); System.out.println(ax + cx - bx + ", " + (ay + cy - by)); System.out.println(cx + bx - ax + ", " + (cy + by - ax)); }} // This code is contributed by Prerna Saini
# Python3 program to find all possible points# of a parallelogram ax = 5ay = 0 #coordinates of Abx = 1by = 1 #coordinates of Bcx = 2cy = 5 #coordinates of Cprint(ax + bx - cx, ", ", ay + by - cy)print(ax + cx - bx, ", ", ay + cy - by)print(cx + bx - ax, ", ", cy + by - ax)
// C# program to all possible// points of a parallelogramusing System; public class ParallelogramPoints{ // Driver code public static void Main() { //coordinates of A int ax = 5, ay = 0; //coordinates of B int bx = 1, by = 1; //coordinates of C int cx = 2, cy = 5; Console.WriteLine(ax + bx - cx + ", " + (ay + by - cy)); Console.WriteLine(ax + cx - bx + ", " + (ay + cy - by)); Console.WriteLine(cx + bx - ax + ", " + (cy + by - ax)); }} // This code is contributed by vt_m.
<?php// PHP program to all// possible points// of a parallelogram // Driver Code //coordinates of A$ax = 5; $ay = 0; //coordinates of B$bx = 1; $by = 1; //coordinates of C$cx = 2; $cy = 5; echo $ax + $bx - $cx , ", " , $ay + $by - $cy ,"\n"; echo $ax + $cx - $bx , ", " , $ay + $cy - $by,"\n" ; echo $cx + $bx - $ax , ", " , $cy + $by - $ax ; // This code is contributed by anuj_67.?>
<script> // JavaScript program to all possible// points of a parallelogram // Driver Codelet ax = 5, ay = 0; // Coordinates of Alet bx = 1, by = 1; // Coordinates of Blet cx = 2, cy = 5; // Coordinates of C document.write(ax + bx - cx + ", " + (ay + by - cy) + "<br/>");document.write(ax + cx - bx + ", " + (ay + cy - by) + "<br/>");document.write(cx + bx - ax + ", " + (cy + by - ax) + "<br/>"); // This code is contributed by susmitakundugoaldanga </script>
Output:
4, -4
6, 4
-2, 1
Time Complexity: O(1)Auxiliary Space: O(1)
Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
vt_m
susmitakundugoaldanga
_shinchancode
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for distance between two points on earth
Find if two rectangles overlap
Check whether triangle is valid or not if sides are given
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Program for Point of Intersection of Two Lines
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 259,
"s": 52,
"text": "Find the all the possible coordinate from the given three coordinates to make a parallelogram of a non-zero area.Let’s call A,B,C are the three given points. We can have only the three possible situations: "
},
{
"code": null,
"e": 390,
"s": 259,
"text": "(1) AB and AC are sides, and BC a diagonal\n(2) AB and BC are sides, and AC a diagonal \n(3) BC and AC are sides, and AB a diagonal "
},
{
"code": null,
"e": 682,
"s": 390,
"text": "Hence, we can say that only 3 coordinates are possible from which we can generate a parallelogram if three coordinates are given.To prove that all the three points are different let’s suppose it’s wrong. Without losing of generality suppose that the points got in cases AD and BC are equal. "
},
{
"code": null,
"e": 755,
"s": 682,
"text": "Consider the system of two equations for the equality of these points: "
},
{
"code": null,
"e": 854,
"s": 755,
"text": "Bx + Cx - Ax = Ax + Cx - Bx\nBy + Cy - Ay = Ay + Cy - By\n\nIt can be simplified as-\n\nAx = Bx\nAy = By"
},
{
"code": null,
"e": 922,
"s": 854,
"text": "And we got a contradiction, as all the points A, B, C are distinct."
},
{
"code": null,
"e": 933,
"s": 922,
"text": "Examples: "
},
{
"code": null,
"e": 1137,
"s": 933,
"text": "Input : A = (0 0)\n B = (1 0)\n C = (0 1)\nOutput : 1 -1\n -1 1\n 1 1\n\nInput : A = (-1 -1)\n B = (0 1)\n C = (1 1)\nOutput : -2 -1\n 0 -1\n 2 3"
},
{
"code": null,
"e": 1260,
"s": 1139,
"text": "Since the opposite sides are equal, AD = BC and AB = CD, we can calculate the co-ordinates of the missing point (D) as: "
},
{
"code": null,
"e": 1345,
"s": 1260,
"text": "AD = BC\n(Dx - Ax, Dy - Ay) = (Cx - Bx, Cy - By)\nDx = Ax + Cx - Bx \nDy = Ay + Cy - By"
},
{
"code": null,
"e": 1571,
"s": 1345,
"text": "The cases where the diagonals are AD and BC, CD and AB are processed in the same way.Reference: https://math.stackexchange.com/questions/1322535/how-many-different-parallelograms-can-be-drawn-if-given-three-co-ordinates-in-3d"
},
{
"code": null,
"e": 1620,
"s": 1571,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 1624,
"s": 1620,
"text": "C++"
},
{
"code": null,
"e": 1629,
"s": 1624,
"text": "Java"
},
{
"code": null,
"e": 1637,
"s": 1629,
"text": "Python3"
},
{
"code": null,
"e": 1640,
"s": 1637,
"text": "C#"
},
{
"code": null,
"e": 1644,
"s": 1640,
"text": "PHP"
},
{
"code": null,
"e": 1655,
"s": 1644,
"text": "Javascript"
},
{
"code": "// C++ program to all possible points// of a parallelogram#include <bits/stdc++.h>using namespace std; // main methodint main(){ int ax = 5, ay = 0; //coordinates of A int bx = 1, by = 1; //coordinates of B int cx = 2, cy = 5; //coordinates of C cout << ax + bx - cx << \", \" << ay + by - cy <<endl; cout << ax + cx - bx << \", \" << ay + cy - by <<endl; cout << cx + bx - ax << \", \" << cy + by - ax <<endl; return 0;}",
"e": 2114,
"s": 1655,
"text": null
},
{
"code": "// Java program to all possible// points of a parallelogrampublic class ParallelogramPoints{ // Driver code public static void main(String[] s) { int ax = 5, ay = 0; //coordinates of A int bx = 1, by = 1; //coordinates of B int cx = 2, cy = 5; //coordinates of C System.out.println(ax + bx - cx + \", \" + (ay + by - cy)); System.out.println(ax + cx - bx + \", \" + (ay + cy - by)); System.out.println(cx + bx - ax + \", \" + (cy + by - ax)); }} // This code is contributed by Prerna Saini",
"e": 2735,
"s": 2114,
"text": null
},
{
"code": "# Python3 program to find all possible points# of a parallelogram ax = 5ay = 0 #coordinates of Abx = 1by = 1 #coordinates of Bcx = 2cy = 5 #coordinates of Cprint(ax + bx - cx, \", \", ay + by - cy)print(ax + cx - bx, \", \", ay + cy - by)print(cx + bx - ax, \", \", cy + by - ax)",
"e": 3009,
"s": 2735,
"text": null
},
{
"code": "// C# program to all possible// points of a parallelogramusing System; public class ParallelogramPoints{ // Driver code public static void Main() { //coordinates of A int ax = 5, ay = 0; //coordinates of B int bx = 1, by = 1; //coordinates of C int cx = 2, cy = 5; Console.WriteLine(ax + bx - cx + \", \" + (ay + by - cy)); Console.WriteLine(ax + cx - bx + \", \" + (ay + cy - by)); Console.WriteLine(cx + bx - ax + \", \" + (cy + by - ax)); }} // This code is contributed by vt_m.",
"e": 3670,
"s": 3009,
"text": null
},
{
"code": "<?php// PHP program to all// possible points// of a parallelogram // Driver Code //coordinates of A$ax = 5; $ay = 0; //coordinates of B$bx = 1; $by = 1; //coordinates of C$cx = 2; $cy = 5; echo $ax + $bx - $cx , \", \" , $ay + $by - $cy ,\"\\n\"; echo $ax + $cx - $bx , \", \" , $ay + $cy - $by,\"\\n\" ; echo $cx + $bx - $ax , \", \" , $cy + $by - $ax ; // This code is contributed by anuj_67.?>",
"e": 4086,
"s": 3670,
"text": null
},
{
"code": "<script> // JavaScript program to all possible// points of a parallelogram // Driver Codelet ax = 5, ay = 0; // Coordinates of Alet bx = 1, by = 1; // Coordinates of Blet cx = 2, cy = 5; // Coordinates of C document.write(ax + bx - cx + \", \" + (ay + by - cy) + \"<br/>\");document.write(ax + cx - bx + \", \" + (ay + cy - by) + \"<br/>\");document.write(cx + bx - ax + \", \" + (cy + by - ax) + \"<br/>\"); // This code is contributed by susmitakundugoaldanga </script>",
"e": 4612,
"s": 4086,
"text": null
},
{
"code": null,
"e": 4621,
"s": 4612,
"text": "Output: "
},
{
"code": null,
"e": 4638,
"s": 4621,
"text": "4, -4\n6, 4\n-2, 1"
},
{
"code": null,
"e": 4681,
"s": 4638,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4948,
"s": 4681,
"text": "Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 4953,
"s": 4948,
"text": "vt_m"
},
{
"code": null,
"e": 4975,
"s": 4953,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 4989,
"s": 4975,
"text": "_shinchancode"
},
{
"code": null,
"e": 4999,
"s": 4989,
"text": "Geometric"
},
{
"code": null,
"e": 5012,
"s": 4999,
"text": "Mathematical"
},
{
"code": null,
"e": 5025,
"s": 5012,
"text": "Mathematical"
},
{
"code": null,
"e": 5035,
"s": 5025,
"text": "Geometric"
},
{
"code": null,
"e": 5133,
"s": 5035,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5182,
"s": 5133,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 5213,
"s": 5182,
"text": "Find if two rectangles overlap"
},
{
"code": null,
"e": 5271,
"s": 5213,
"text": "Check whether triangle is valid or not if sides are given"
},
{
"code": null,
"e": 5322,
"s": 5271,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 5369,
"s": 5322,
"text": "Program for Point of Intersection of Two Lines"
},
{
"code": null,
"e": 5399,
"s": 5369,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 5442,
"s": 5399,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5502,
"s": 5442,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 5517,
"s": 5502,
"text": "C++ Data Types"
}
] |
TimeSpan.FromHours() Method in C#
|
30 Sep, 2019
This method is used to get a TimeSpan that represents a specified number of hours, accurate to the nearest millisecond.
Syntax: public static TimeSpan FromHours (double value);
Parameter:value: This parameter specifies the number of hours, accurate to the nearest millisecond.
Return Value: It returns a new TimeSpan object that represents the value.
Exceptions:
OverflowException: It occurs when the given double value is smaller than the smallest possible value or greater than the largest possible value or the value is PositiveInfinity or is NegativeInfinity.
ArgumentException: If the value is equal to NaN.
Below programs illustrate the use of TimeSpan.FromHours(Double) Method:
Program 1:
// C# program to demonstrate the// TimeSpan.FromDays(Double) Methodusing System; class GFG { // Main Method public static void Main() { try { TimeSpan interval = TimeSpan.FromHours(12.3459); Console.WriteLine("The Timespan is : {0}", interval); } catch (OverflowException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
The Timespan is : 12:20:45.2400000
Program 2: For Overflow Exception
// C# program to demonstrate the// TimeSpan.FromDays(Double) Methodusing System; class GFG { // Main Method public static void Main() { try { TimeSpan interval = TimeSpan.FromHours(Double.NegativeInfinity); Console.WriteLine("The Timespan is : {0}", interval); } catch (OverflowException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Exception Thrown: System.OverflowException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.timespan.fromhours?view=netframework-4.7.2
shubham_singh
CSharp-method
CSharp-TimeSpan-Struct
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Sep, 2019"
},
{
"code": null,
"e": 148,
"s": 28,
"text": "This method is used to get a TimeSpan that represents a specified number of hours, accurate to the nearest millisecond."
},
{
"code": null,
"e": 205,
"s": 148,
"text": "Syntax: public static TimeSpan FromHours (double value);"
},
{
"code": null,
"e": 305,
"s": 205,
"text": "Parameter:value: This parameter specifies the number of hours, accurate to the nearest millisecond."
},
{
"code": null,
"e": 379,
"s": 305,
"text": "Return Value: It returns a new TimeSpan object that represents the value."
},
{
"code": null,
"e": 391,
"s": 379,
"text": "Exceptions:"
},
{
"code": null,
"e": 592,
"s": 391,
"text": "OverflowException: It occurs when the given double value is smaller than the smallest possible value or greater than the largest possible value or the value is PositiveInfinity or is NegativeInfinity."
},
{
"code": null,
"e": 641,
"s": 592,
"text": "ArgumentException: If the value is equal to NaN."
},
{
"code": null,
"e": 713,
"s": 641,
"text": "Below programs illustrate the use of TimeSpan.FromHours(Double) Method:"
},
{
"code": null,
"e": 724,
"s": 713,
"text": "Program 1:"
},
{
"code": "// C# program to demonstrate the// TimeSpan.FromDays(Double) Methodusing System; class GFG { // Main Method public static void Main() { try { TimeSpan interval = TimeSpan.FromHours(12.3459); Console.WriteLine(\"The Timespan is : {0}\", interval); } catch (OverflowException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 1223,
"s": 724,
"text": null
},
{
"code": null,
"e": 1259,
"s": 1223,
"text": "The Timespan is : 12:20:45.2400000\n"
},
{
"code": null,
"e": 1293,
"s": 1259,
"text": "Program 2: For Overflow Exception"
},
{
"code": "// C# program to demonstrate the// TimeSpan.FromDays(Double) Methodusing System; class GFG { // Main Method public static void Main() { try { TimeSpan interval = TimeSpan.FromHours(Double.NegativeInfinity); Console.WriteLine(\"The Timespan is : {0}\", interval); } catch (OverflowException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 1831,
"s": 1293,
"text": null
},
{
"code": null,
"e": 1875,
"s": 1831,
"text": "Exception Thrown: System.OverflowException\n"
},
{
"code": null,
"e": 1886,
"s": 1875,
"text": "Reference:"
},
{
"code": null,
"e": 1980,
"s": 1886,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.timespan.fromhours?view=netframework-4.7.2"
},
{
"code": null,
"e": 1994,
"s": 1980,
"text": "shubham_singh"
},
{
"code": null,
"e": 2008,
"s": 1994,
"text": "CSharp-method"
},
{
"code": null,
"e": 2031,
"s": 2008,
"text": "CSharp-TimeSpan-Struct"
},
{
"code": null,
"e": 2034,
"s": 2031,
"text": "C#"
}
] |
JavaFX | ComboBox with examples
|
20 Aug, 2021
ComboBox is a part of the JavaFX library. JavaFX ComboBox is an implementation of simple ComboBox which shows a list of items out of which user can select at most one item, it inherits the class ComboBoxBase.
Constructors of ComboBox:
ComboBox(): creates a default empty combo boxComboBox(ObservableList i): creates a combo box with the given items
ComboBox(): creates a default empty combo box
ComboBox(ObservableList i): creates a combo box with the given items
Commonly used Methods:
Below programs illustrate the ComboBox class of JavaFX:
Program to create a Combo Box and add items to it: This program creates a ComboBox named combo_box and add a list of string to it using ChoiceBox(FXCollections.observableArrayList(week_days)). We would add the combo box and a label(description) to the tilepane(getChildren().add() function). We will create a stage (container) and add the tilepane to the scene and add the scene to the stage. We would display the stage using show() function.
Java
// Java Program to create a combo Box and add items to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class combo_box_1 extends Application { // Launch the application public void start(Stage stage) { // Set title for the stage stage.setTitle("creating combo box "); // Create a tile pane TilePane r = new TilePane(); // Create a label Label description_label = new Label("This is a combo box example "); // Weekdays String week_days[] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" }; // Create a combo box ComboBox combo_box = new ComboBox(FXCollections .observableArrayList(week_days)); // Create a tile pane TilePane tile_pane = new TilePane(combo_box); // Create a scene Scene scene = new Scene(tile_pane, 200, 200); // Set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // Launch the application launch(args); }}
Output:
Program to create a combo box and add an event handler to it: This program creates a ComboBox named combo_box and add a list of string to it using(ChoiceBox(FXCollections.observableArrayList(week_days))). We would add the combo box and a label(description) to the tilepane(getChildren().add() function). We will create a stage (container) and add the tilepane to the scene and add the scene to the stage. We would display the stage using show() function. We would add an event handler event to handle the events of combo_box which will change the text of the label selected to the item selected. We will also add the label selected to the tile pane.
Java
// Java program to create a combo box and add event handler to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class combo_box_2 extends Application { // Launch the application public void start(Stage stage) { // Set title for the stage stage.setTitle("creating combo box "); // Create a tile pane TilePane r = new TilePane(); // Create a label Label description_label = new Label("This is a combo box example "); // Weekdays String week_days[] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" }; // Create a combo box ComboBox combo_box = new ComboBox(FXCollections .observableArrayList(week_days)); // Label to display the selected menuitem Label selected = new Label("default item selected"); // Create action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { selected.setText(combo_box.getValue() + " selected"); } }; // Set on action combo_box.setOnAction(event); // Create a tile pane TilePane tile_pane = new TilePane(combo_box, selected); // Create a scene Scene scene = new Scene(tile_pane, 200, 200); // Set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // Launch the application launch(args); }}
Output:
Note: The above programs might not run in an online IDE please use an offline converter.
Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ComboBox.html
nidhi_biet
ManasChhabra2
peterlamantia5
sagartomar9927
JavaFX
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Aug, 2021"
},
{
"code": null,
"e": 237,
"s": 28,
"text": "ComboBox is a part of the JavaFX library. JavaFX ComboBox is an implementation of simple ComboBox which shows a list of items out of which user can select at most one item, it inherits the class ComboBoxBase."
},
{
"code": null,
"e": 264,
"s": 237,
"text": "Constructors of ComboBox: "
},
{
"code": null,
"e": 378,
"s": 264,
"text": "ComboBox(): creates a default empty combo boxComboBox(ObservableList i): creates a combo box with the given items"
},
{
"code": null,
"e": 424,
"s": 378,
"text": "ComboBox(): creates a default empty combo box"
},
{
"code": null,
"e": 493,
"s": 424,
"text": "ComboBox(ObservableList i): creates a combo box with the given items"
},
{
"code": null,
"e": 518,
"s": 493,
"text": "Commonly used Methods: "
},
{
"code": null,
"e": 574,
"s": 518,
"text": "Below programs illustrate the ComboBox class of JavaFX:"
},
{
"code": null,
"e": 1017,
"s": 574,
"text": "Program to create a Combo Box and add items to it: This program creates a ComboBox named combo_box and add a list of string to it using ChoiceBox(FXCollections.observableArrayList(week_days)). We would add the combo box and a label(description) to the tilepane(getChildren().add() function). We will create a stage (container) and add the tilepane to the scene and add the scene to the stage. We would display the stage using show() function."
},
{
"code": null,
"e": 1022,
"s": 1017,
"text": "Java"
},
{
"code": "// Java Program to create a combo Box and add items to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class combo_box_1 extends Application { // Launch the application public void start(Stage stage) { // Set title for the stage stage.setTitle(\"creating combo box \"); // Create a tile pane TilePane r = new TilePane(); // Create a label Label description_label = new Label(\"This is a combo box example \"); // Weekdays String week_days[] = { \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\" }; // Create a combo box ComboBox combo_box = new ComboBox(FXCollections .observableArrayList(week_days)); // Create a tile pane TilePane tile_pane = new TilePane(combo_box); // Create a scene Scene scene = new Scene(tile_pane, 200, 200); // Set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // Launch the application launch(args); }}",
"e": 2476,
"s": 1022,
"text": null
},
{
"code": null,
"e": 2485,
"s": 2476,
"text": "Output: "
},
{
"code": null,
"e": 3135,
"s": 2485,
"text": "Program to create a combo box and add an event handler to it: This program creates a ComboBox named combo_box and add a list of string to it using(ChoiceBox(FXCollections.observableArrayList(week_days))). We would add the combo box and a label(description) to the tilepane(getChildren().add() function). We will create a stage (container) and add the tilepane to the scene and add the scene to the stage. We would display the stage using show() function. We would add an event handler event to handle the events of combo_box which will change the text of the label selected to the item selected. We will also add the label selected to the tile pane."
},
{
"code": null,
"e": 3140,
"s": 3135,
"text": "Java"
},
{
"code": "// Java program to create a combo box and add event handler to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class combo_box_2 extends Application { // Launch the application public void start(Stage stage) { // Set title for the stage stage.setTitle(\"creating combo box \"); // Create a tile pane TilePane r = new TilePane(); // Create a label Label description_label = new Label(\"This is a combo box example \"); // Weekdays String week_days[] = { \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\" }; // Create a combo box ComboBox combo_box = new ComboBox(FXCollections .observableArrayList(week_days)); // Label to display the selected menuitem Label selected = new Label(\"default item selected\"); // Create action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { selected.setText(combo_box.getValue() + \" selected\"); } }; // Set on action combo_box.setOnAction(event); // Create a tile pane TilePane tile_pane = new TilePane(combo_box, selected); // Create a scene Scene scene = new Scene(tile_pane, 200, 200); // Set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // Launch the application launch(args); }}",
"e": 5056,
"s": 3140,
"text": null
},
{
"code": null,
"e": 5065,
"s": 5056,
"text": "Output: "
},
{
"code": null,
"e": 5154,
"s": 5065,
"text": "Note: The above programs might not run in an online IDE please use an offline converter."
},
{
"code": null,
"e": 5245,
"s": 5154,
"text": "Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ComboBox.html "
},
{
"code": null,
"e": 5256,
"s": 5245,
"text": "nidhi_biet"
},
{
"code": null,
"e": 5270,
"s": 5256,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 5285,
"s": 5270,
"text": "peterlamantia5"
},
{
"code": null,
"e": 5300,
"s": 5285,
"text": "sagartomar9927"
},
{
"code": null,
"e": 5307,
"s": 5300,
"text": "JavaFX"
},
{
"code": null,
"e": 5312,
"s": 5307,
"text": "Java"
},
{
"code": null,
"e": 5317,
"s": 5312,
"text": "Java"
}
] |
HTML - <td> Tag
|
The HTML <td> tag is used for specifying a cell or table data within a table.
<!DOCTYPE html>
<html>
<head>
<title>HTML td Tag</title>
</head>
<body>
<table border = "1">
<tr>
<th>Subject</th>
<th>Topic</th>
</tr>
<tr>
<td>Java</td>
<td>Threading</td>
</tr>
<tr>
<td>C++</td>
<td>Virtual Functions</td>
</tr>
<tr>
<td>Linux</td>
<td>File Systems</td>
</tr>
</table>
</body>
</html>
This will produce the following result −
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <td> tag also supports the following additional attributes −
This tag supports all the event attributes described in − HTML Events Reference
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2452,
"s": 2374,
"text": "The HTML <td> tag is used for specifying a cell or table data within a table."
},
{
"code": null,
"e": 2987,
"s": 2452,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML td Tag</title>\n </head>\n\n <body>\n <table border = \"1\">\n <tr>\n <th>Subject</th>\n <th>Topic</th>\n </tr>\n \n <tr>\n <td>Java</td>\n <td>Threading</td>\n </tr>\n \n <tr>\n <td>C++</td>\n <td>Virtual Functions</td>\n </tr>\n \n <tr>\n <td>Linux</td>\n <td>File Systems</td>\n </tr>\n </table>\n </body>\n\n</html>"
},
{
"code": null,
"e": 3028,
"s": 2987,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3112,
"s": 3028,
"text": "This tag supports all the global attributes described in − HTML Attribute Reference"
},
{
"code": null,
"e": 3183,
"s": 3112,
"text": "The HTML <td> tag also supports the following additional attributes −"
},
{
"code": null,
"e": 3263,
"s": 3183,
"text": "This tag supports all the event attributes described in − HTML Events Reference"
},
{
"code": null,
"e": 3296,
"s": 3263,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3310,
"s": 3296,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3345,
"s": 3310,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3359,
"s": 3345,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3394,
"s": 3359,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3411,
"s": 3394,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3446,
"s": 3411,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3477,
"s": 3446,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3510,
"s": 3477,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3541,
"s": 3510,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3576,
"s": 3541,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3607,
"s": 3576,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3614,
"s": 3607,
"text": " Print"
},
{
"code": null,
"e": 3625,
"s": 3614,
"text": " Add Notes"
}
] |
Linear Regression with example | by Sandeep Khurana | Towards Data Science
|
Machine Learning — Fictional story. Once there was a doctor. He would look at person and predict if s/he has lack of Haemoglobin (red blood cells) or not. And almost all the time his prediction will come true upon testing the blood of the patient.
How would he predict? Lets assume pale color of face, tiredness in body are symptoms of low Hb (heamoglobin). If the weight of the person is less then more chances such symptoms are because of low Hb. The doctor “based upon his past experience” will “predict” after looking at the person.
What if we can make computer also learn things like this and make such prediction. Assuming we have numeric quantified variables like paleness and tiredness.
Linear Regression
We have seen equation like below in maths classes. y is the output we want. x is the input variable. c = constant and a is the slope of the line.
y = c + axc = constanta = slope
The output varies linearly based upon the input.
y is the output which is determined by input x. How much value of x has impact on y is determined by “a”. In the two dimensional graph having axis ‘x’ and ‘y’ , ‘a’ is the slope of the line.
‘c’ is the constant (value of y when x is zero).
Historical Data
Lets say we have good amount of historical data wherein values of input ‘x’ and output/result ‘y’ are provided.
We also know that change in x impacts y somewhat linearly. It means if we take the values of these ‘x’s and ‘y’s and plot of graph then we get a graph like this. Not exactly same but somewhat like this wherein there seems to be clutter of points going in one linear direction. Image courtsey — https://en.wikipedia.org/wiki/Linear_regression
What do we want to do
We want to look at the historical data and find the values of ‘c’ and ‘a’. Lets call ‘c’ as the constant and ‘a’ as the weight. If we are able to figure out the values of c and a then we can predict the value of y for any new x.
How to do
As you can see from the graph, although the dots form a linear pattern but they are not in same line. So we cant know the 100% perfect value of c and a. But what we can do it to find the best fit line, shown in red above.
This means our output will be approximate. There might be slight deviation from actual value. But it works fine for most business applications.
How in details
Look at the dots in the graph. What if we figure out a line whose distances from each dot in the graph is optimal/minimal. This would mean ‘best fit line’ as shown in red in the pic above. Our objective is to draw the red line in the graph above.
So, we draw a random line on the graph for some random value of c and a. Lets say we keep c and a both 1 (c=1, a=1) and draw the line on the graph for each (well at least 2 ) x. Based upon values of x this line might end up in one of the following positions
On leftish side of the dots towards y axis. More vertical.
On rightish side of dots towards x axis. More horizontal.
Somewhere between dots but still not best fit line.
Since this was a random line, we need a mechamism to move this line iteratively and slowly towards the place where it best fits the sample data (dots in the graph).
So, effectively we need
To find if its best fit line or not
If its not best fit line then move it towards the best fit line. It means we will have to change the value of c and a.
How much values of c and a we need to change and in which direction? We will use combination of gradient descent with least square method to achive these objectives. These are explained below.
Mathematics
For each item in the sample data (called training set too), get the value of y from our estimated line (c=1, a=1). Lets call it h(y).
Also, we have y which is real value for each sample data.
We get the difference between approximated h(y) and y as h(y) — y. Square this difference up. So for one sample we have (h(y) — y) ^ 2
Do it for all samples. Lets say we have sample size as ‘m’, we get the squares of differences for each sample size, sum it up (summmation from 1 to m), get the average of it (i.e. divide by m), make it half (as half of squared difference provides better results). We now have our cost function. We need to minimize this cost function. It means we need to minimize the distance of our line with sample data (dots) to get best fit line.
More explanation of cost function is at — https://www.coursera.org/learn/machine-learning/lecture/rkTp3/cost-function
But we have 2 variables c and a which we need to keep changing to get at best fit line.
For initial combination of c and a, we need to find how much to move and then move it. Once we have new line for new values of c and a then do the distance calculation with each point again and keep doing it till we find that we are not moving much e.g. moving quite less.
It bascially means our line is stil far from the dots in the graph.
Since we need to change both c and a independently, we will use partial differentiation. So we will get the derivative of above cost function wrt c and then wrt a. Remember, we have h(y) for one sample = c + ax
So result of partial derivates of cost function wrt ‘c’ will be
And result of partial derivates of cost function wrt ‘a’ will be
Now we decide the step size i.e. how much big or small of step we want to take in each iteration. Lets call it alpha and we set this value to 0.01. It can be any suitable value based upon the data.
So the distance to be moved by c will be
And the distance to be moved by a will be
Above farmulae will not only give the distance we moved but also the direction e.g. if the random like we initially drew was more verticlish and had to move down to be the best fit then new values will decrease e.g. a will change from 1 to 0.99. But if our initial random line was horizontalish and had to move up to be best fit like then new values will be more e.g. a will change from 1 to 1.01 .
And as mentioned earlier we stop when we realize we are almost not moving or after certain number of iterations. It means we have reached our best fit line i.e. the red line.
What is learning without an example exercise.
Lets take the data of passenger vehicle sales in India. To keep things simple, lets say only one variable which is GDP of the country has impact on the sales. In reality there are more factors like auto interest loan rates etc but thats for next article. For this lets focus on linear equation of number of vehicle sold in India wrt GDP.
Sample Data
I looked at passenger vehicles sales in India year wise for last few years. Also checked GDP for each year. While looking at both the data it dawned upon me that impact of GDP in ‘current year’ will have effect on vehicle sales ‘next year’ . So whichever year GDP was less, the coming year sales was lower and when GDP increased the next year vehicle sales also increased. Hence they say preparing the data for ML analytics is more important and thats where most time needs to be spent.
Lets have equation as y = c + ax .
y = number of vehicles sold in the year
x = GDP of prior year.
We need to find c and a.
Below is table of data. I saved this data in a file called ‘vehicle_sale_data’. Please note that number of vehicles sold figure is in lakhs (1 lakh = 0.1 million).
year,GDP,4wheeler_passengar_vehicle_sale(in lakhs)2011,6.2,26.32012,6.5,26.652013,5.48,25.032014,6.54,26.012015,7.18,27.92016,7.93,30.47
First column = year, which is of not much use in the code below
Second column — GDP for the ‘previous’ year. This is x in the equation.
Third column — Number of vehicles sold. This is what we want to predict maybe for nexy year if we know the GDP of current year.
We will use python to create the model. Below are the steps.
Read the file. ‘gdp_sale’ dictionary will have key as GDP and value is sales.
def read_data() : data = open("vehicle_sale_data" , "r") gdp_sale = collections.OrderedDict() for line in data.readlines()[1:] : record = line.split(",") gdp_sale[float(record[1])] = float(record[2].replace('\n', "")) return gdp_sale
Calulate the step and get to new ‘c’ and ‘a’. For first time, we will pass the initial value ‘c’ and ‘a’. This function will calculate the values of new c and new a after moving one step. This function need to be called iteratively till it stablizes.
def step_cost_function_for(gdp_sale, constant, slope) : global stepSize diff_sum_constant = 0 # diff of sum for constant 'c' in "c + ax" equation diff_sum_slope = 0 # diff of sum for 'a' in "c + ax" equation gdp_for_years = list(gdp_sale.keys()) for year_gdp in gdp_for_years: # for each year's gdp in the sample data # get the sale for given 'c' and 'a'by giving the GDP for this sample record trg_data_sale = sale_for_data(constant, slope, year_gdp) # calculated sale for current 'c' and 'a' a_year_sale = gdp_sale.get(year_gdp) # real sale for this record diff_sum_slope = diff_sum_slope + ((trg_data_sale - a_year_sale) * year_gdp) # slope's (h(y) - y) * x diff_sum_constant = diff_sum_constant + (trg_data_sale - a_year_sale) # consant's (h(y) - y) step_for_constant = (stepSize / len(gdp_sale)) * diff_sum_constant # distance to be moved by c step_for_slope = (stepSize / len(gdp_sale)) * diff_sum_slope # distance to be moved by a new_constant = constant - step_for_constant # new c new_slope = slope - step_for_slope # new a return new_constant, new_slope
Function to get the sales of vehicles provided the values of c, a and x. Used by above function for each sample data (gdp).
def sale_for_data(constant, slope, data): return constant + slope * data # y = c + ax format
Iteration to get optimum weights ie optimum values of c and a. It will stop if c and a both are not moving more than 0.01 in next iteration.
def get_weights(gdp_sale) : constant = 1 slope = 1 accepted_diff = 0.01 while 1 == 1: # continue till we reach local minimum new_constant, new_slope = step_cost_function_for(gdp_sale, constant, slope) # if the diff is too less then lets break if (abs(constant - new_constant) <= accepted_diff) and (abs(slope - new_slope) <= accepted_diff): print "done. Diff is less than " + str(accepted_diff) return new_constant, new_slope else: constant = new_constant slope = new_slope print "new values for constant and slope are " + str(new_constant) + ", " + \ str(new_slope)
And of course the main function
def main() : contant, slope = get_weights(read_data()) print "constant :" + contant + ", slope:" + slopeif __name__ == '__main__': main()
I got the equation as
y (vehicles sales) = 1.43 + 3.84 * x
x is value of GDP
So if we have GDP as 7.5 this year then we will have passenger vehicles sales next year as — 1.43 7.5*3.84 = 30.23
The complete program is below. Its also on github at https://github.com/skhurana333/ml/blob/master/linearRegSingleVariant.py
# sales of vehicle as a function of GDP (for India)import collectionsstepSize = 0.01def read_data() : data = open("vehicle_sale_data" , "r") gdp_sale = collections.OrderedDict() for line in data.readlines()[1:] : record = line.split(",") gdp_sale[float(record[1])] = float(record[2].replace('\n', "")) return gdp_saledef sale_for_data(constant, slope, data): return constant + slope * data # y = c + ax formatdef step_cost_function_for(gdp_sale, constant, slope) : global stepSize diff_sum_constant = 0 # diff of sum for constant 'c' in "c + ax" equation diff_sum_slope = 0 # diff of sum for 'a' in "c + ax" equation gdp_for_years = list(gdp_sale.keys()) for year_gdp in gdp_for_years: # for each year's gdp in the sample data # get the sale for given 'c' and 'a'by giving the GDP for this sample record trg_data_sale = sale_for_data(constant, slope, year_gdp) # calculated sale for current 'c' and 'a' a_year_sale = gdp_sale.get(year_gdp) # real sale for this record diff_sum_slope = diff_sum_slope + ((trg_data_sale - a_year_sale) * year_gdp) # slope's (h(y) - y) * x diff_sum_constant = diff_sum_constant + (trg_data_sale - a_year_sale) # consant's (h(y) - y) step_for_constant = (stepSize / len(gdp_sale)) * diff_sum_constant # distance to be moved by c step_for_slope = (stepSize / len(gdp_sale)) * diff_sum_slope # distance to be moved by a new_constant = constant - step_for_constant # new c new_slope = slope - step_for_slope # new a return new_constant, new_slopedef get_weights(gdp_sale) : constant = 1 slope = 1 accepted_diff = 0.01 while 1 == 1: # continue till we reach local minimum new_constant, new_slope = step_cost_function_for(gdp_sale, constant, slope) # if the diff is too less then lets break if (abs(constant - new_constant) <= accepted_diff) and (abs(slope - new_slope) <= accepted_diff): print "done. Diff is less than " + str(accepted_diff) return new_constant, new_slope else: constant = new_constant slope = new_slope print "new values for constant and slope are " + str(new_constant) + ", " + \ str(new_slope)def main() : contant, slope = get_weights(read_data()) print "constant :" + contant + ", slope:" + slopeif __name__ == '__main__': main()
|
[
{
"code": null,
"e": 420,
"s": 172,
"text": "Machine Learning — Fictional story. Once there was a doctor. He would look at person and predict if s/he has lack of Haemoglobin (red blood cells) or not. And almost all the time his prediction will come true upon testing the blood of the patient."
},
{
"code": null,
"e": 709,
"s": 420,
"text": "How would he predict? Lets assume pale color of face, tiredness in body are symptoms of low Hb (heamoglobin). If the weight of the person is less then more chances such symptoms are because of low Hb. The doctor “based upon his past experience” will “predict” after looking at the person."
},
{
"code": null,
"e": 867,
"s": 709,
"text": "What if we can make computer also learn things like this and make such prediction. Assuming we have numeric quantified variables like paleness and tiredness."
},
{
"code": null,
"e": 885,
"s": 867,
"text": "Linear Regression"
},
{
"code": null,
"e": 1031,
"s": 885,
"text": "We have seen equation like below in maths classes. y is the output we want. x is the input variable. c = constant and a is the slope of the line."
},
{
"code": null,
"e": 1063,
"s": 1031,
"text": "y = c + axc = constanta = slope"
},
{
"code": null,
"e": 1112,
"s": 1063,
"text": "The output varies linearly based upon the input."
},
{
"code": null,
"e": 1303,
"s": 1112,
"text": "y is the output which is determined by input x. How much value of x has impact on y is determined by “a”. In the two dimensional graph having axis ‘x’ and ‘y’ , ‘a’ is the slope of the line."
},
{
"code": null,
"e": 1352,
"s": 1303,
"text": "‘c’ is the constant (value of y when x is zero)."
},
{
"code": null,
"e": 1368,
"s": 1352,
"text": "Historical Data"
},
{
"code": null,
"e": 1480,
"s": 1368,
"text": "Lets say we have good amount of historical data wherein values of input ‘x’ and output/result ‘y’ are provided."
},
{
"code": null,
"e": 1822,
"s": 1480,
"text": "We also know that change in x impacts y somewhat linearly. It means if we take the values of these ‘x’s and ‘y’s and plot of graph then we get a graph like this. Not exactly same but somewhat like this wherein there seems to be clutter of points going in one linear direction. Image courtsey — https://en.wikipedia.org/wiki/Linear_regression"
},
{
"code": null,
"e": 1844,
"s": 1822,
"text": "What do we want to do"
},
{
"code": null,
"e": 2073,
"s": 1844,
"text": "We want to look at the historical data and find the values of ‘c’ and ‘a’. Lets call ‘c’ as the constant and ‘a’ as the weight. If we are able to figure out the values of c and a then we can predict the value of y for any new x."
},
{
"code": null,
"e": 2083,
"s": 2073,
"text": "How to do"
},
{
"code": null,
"e": 2305,
"s": 2083,
"text": "As you can see from the graph, although the dots form a linear pattern but they are not in same line. So we cant know the 100% perfect value of c and a. But what we can do it to find the best fit line, shown in red above."
},
{
"code": null,
"e": 2449,
"s": 2305,
"text": "This means our output will be approximate. There might be slight deviation from actual value. But it works fine for most business applications."
},
{
"code": null,
"e": 2464,
"s": 2449,
"text": "How in details"
},
{
"code": null,
"e": 2711,
"s": 2464,
"text": "Look at the dots in the graph. What if we figure out a line whose distances from each dot in the graph is optimal/minimal. This would mean ‘best fit line’ as shown in red in the pic above. Our objective is to draw the red line in the graph above."
},
{
"code": null,
"e": 2969,
"s": 2711,
"text": "So, we draw a random line on the graph for some random value of c and a. Lets say we keep c and a both 1 (c=1, a=1) and draw the line on the graph for each (well at least 2 ) x. Based upon values of x this line might end up in one of the following positions"
},
{
"code": null,
"e": 3028,
"s": 2969,
"text": "On leftish side of the dots towards y axis. More vertical."
},
{
"code": null,
"e": 3086,
"s": 3028,
"text": "On rightish side of dots towards x axis. More horizontal."
},
{
"code": null,
"e": 3138,
"s": 3086,
"text": "Somewhere between dots but still not best fit line."
},
{
"code": null,
"e": 3303,
"s": 3138,
"text": "Since this was a random line, we need a mechamism to move this line iteratively and slowly towards the place where it best fits the sample data (dots in the graph)."
},
{
"code": null,
"e": 3327,
"s": 3303,
"text": "So, effectively we need"
},
{
"code": null,
"e": 3363,
"s": 3327,
"text": "To find if its best fit line or not"
},
{
"code": null,
"e": 3482,
"s": 3363,
"text": "If its not best fit line then move it towards the best fit line. It means we will have to change the value of c and a."
},
{
"code": null,
"e": 3675,
"s": 3482,
"text": "How much values of c and a we need to change and in which direction? We will use combination of gradient descent with least square method to achive these objectives. These are explained below."
},
{
"code": null,
"e": 3687,
"s": 3675,
"text": "Mathematics"
},
{
"code": null,
"e": 3821,
"s": 3687,
"text": "For each item in the sample data (called training set too), get the value of y from our estimated line (c=1, a=1). Lets call it h(y)."
},
{
"code": null,
"e": 3879,
"s": 3821,
"text": "Also, we have y which is real value for each sample data."
},
{
"code": null,
"e": 4014,
"s": 3879,
"text": "We get the difference between approximated h(y) and y as h(y) — y. Square this difference up. So for one sample we have (h(y) — y) ^ 2"
},
{
"code": null,
"e": 4449,
"s": 4014,
"text": "Do it for all samples. Lets say we have sample size as ‘m’, we get the squares of differences for each sample size, sum it up (summmation from 1 to m), get the average of it (i.e. divide by m), make it half (as half of squared difference provides better results). We now have our cost function. We need to minimize this cost function. It means we need to minimize the distance of our line with sample data (dots) to get best fit line."
},
{
"code": null,
"e": 4567,
"s": 4449,
"text": "More explanation of cost function is at — https://www.coursera.org/learn/machine-learning/lecture/rkTp3/cost-function"
},
{
"code": null,
"e": 4655,
"s": 4567,
"text": "But we have 2 variables c and a which we need to keep changing to get at best fit line."
},
{
"code": null,
"e": 4928,
"s": 4655,
"text": "For initial combination of c and a, we need to find how much to move and then move it. Once we have new line for new values of c and a then do the distance calculation with each point again and keep doing it till we find that we are not moving much e.g. moving quite less."
},
{
"code": null,
"e": 4996,
"s": 4928,
"text": "It bascially means our line is stil far from the dots in the graph."
},
{
"code": null,
"e": 5207,
"s": 4996,
"text": "Since we need to change both c and a independently, we will use partial differentiation. So we will get the derivative of above cost function wrt c and then wrt a. Remember, we have h(y) for one sample = c + ax"
},
{
"code": null,
"e": 5271,
"s": 5207,
"text": "So result of partial derivates of cost function wrt ‘c’ will be"
},
{
"code": null,
"e": 5336,
"s": 5271,
"text": "And result of partial derivates of cost function wrt ‘a’ will be"
},
{
"code": null,
"e": 5534,
"s": 5336,
"text": "Now we decide the step size i.e. how much big or small of step we want to take in each iteration. Lets call it alpha and we set this value to 0.01. It can be any suitable value based upon the data."
},
{
"code": null,
"e": 5575,
"s": 5534,
"text": "So the distance to be moved by c will be"
},
{
"code": null,
"e": 5617,
"s": 5575,
"text": "And the distance to be moved by a will be"
},
{
"code": null,
"e": 6016,
"s": 5617,
"text": "Above farmulae will not only give the distance we moved but also the direction e.g. if the random like we initially drew was more verticlish and had to move down to be the best fit then new values will decrease e.g. a will change from 1 to 0.99. But if our initial random line was horizontalish and had to move up to be best fit like then new values will be more e.g. a will change from 1 to 1.01 ."
},
{
"code": null,
"e": 6191,
"s": 6016,
"text": "And as mentioned earlier we stop when we realize we are almost not moving or after certain number of iterations. It means we have reached our best fit line i.e. the red line."
},
{
"code": null,
"e": 6237,
"s": 6191,
"text": "What is learning without an example exercise."
},
{
"code": null,
"e": 6575,
"s": 6237,
"text": "Lets take the data of passenger vehicle sales in India. To keep things simple, lets say only one variable which is GDP of the country has impact on the sales. In reality there are more factors like auto interest loan rates etc but thats for next article. For this lets focus on linear equation of number of vehicle sold in India wrt GDP."
},
{
"code": null,
"e": 6587,
"s": 6575,
"text": "Sample Data"
},
{
"code": null,
"e": 7074,
"s": 6587,
"text": "I looked at passenger vehicles sales in India year wise for last few years. Also checked GDP for each year. While looking at both the data it dawned upon me that impact of GDP in ‘current year’ will have effect on vehicle sales ‘next year’ . So whichever year GDP was less, the coming year sales was lower and when GDP increased the next year vehicle sales also increased. Hence they say preparing the data for ML analytics is more important and thats where most time needs to be spent."
},
{
"code": null,
"e": 7109,
"s": 7074,
"text": "Lets have equation as y = c + ax ."
},
{
"code": null,
"e": 7149,
"s": 7109,
"text": "y = number of vehicles sold in the year"
},
{
"code": null,
"e": 7172,
"s": 7149,
"text": "x = GDP of prior year."
},
{
"code": null,
"e": 7197,
"s": 7172,
"text": "We need to find c and a."
},
{
"code": null,
"e": 7361,
"s": 7197,
"text": "Below is table of data. I saved this data in a file called ‘vehicle_sale_data’. Please note that number of vehicles sold figure is in lakhs (1 lakh = 0.1 million)."
},
{
"code": null,
"e": 7498,
"s": 7361,
"text": "year,GDP,4wheeler_passengar_vehicle_sale(in lakhs)2011,6.2,26.32012,6.5,26.652013,5.48,25.032014,6.54,26.012015,7.18,27.92016,7.93,30.47"
},
{
"code": null,
"e": 7562,
"s": 7498,
"text": "First column = year, which is of not much use in the code below"
},
{
"code": null,
"e": 7634,
"s": 7562,
"text": "Second column — GDP for the ‘previous’ year. This is x in the equation."
},
{
"code": null,
"e": 7762,
"s": 7634,
"text": "Third column — Number of vehicles sold. This is what we want to predict maybe for nexy year if we know the GDP of current year."
},
{
"code": null,
"e": 7823,
"s": 7762,
"text": "We will use python to create the model. Below are the steps."
},
{
"code": null,
"e": 7901,
"s": 7823,
"text": "Read the file. ‘gdp_sale’ dictionary will have key as GDP and value is sales."
},
{
"code": null,
"e": 8161,
"s": 7901,
"text": "def read_data() : data = open(\"vehicle_sale_data\" , \"r\") gdp_sale = collections.OrderedDict() for line in data.readlines()[1:] : record = line.split(\",\") gdp_sale[float(record[1])] = float(record[2].replace('\\n', \"\")) return gdp_sale"
},
{
"code": null,
"e": 8412,
"s": 8161,
"text": "Calulate the step and get to new ‘c’ and ‘a’. For first time, we will pass the initial value ‘c’ and ‘a’. This function will calculate the values of new c and new a after moving one step. This function need to be called iteratively till it stablizes."
},
{
"code": null,
"e": 9542,
"s": 8412,
"text": "def step_cost_function_for(gdp_sale, constant, slope) : global stepSize diff_sum_constant = 0 # diff of sum for constant 'c' in \"c + ax\" equation diff_sum_slope = 0 # diff of sum for 'a' in \"c + ax\" equation gdp_for_years = list(gdp_sale.keys()) for year_gdp in gdp_for_years: # for each year's gdp in the sample data # get the sale for given 'c' and 'a'by giving the GDP for this sample record trg_data_sale = sale_for_data(constant, slope, year_gdp) # calculated sale for current 'c' and 'a' a_year_sale = gdp_sale.get(year_gdp) # real sale for this record diff_sum_slope = diff_sum_slope + ((trg_data_sale - a_year_sale) * year_gdp) # slope's (h(y) - y) * x diff_sum_constant = diff_sum_constant + (trg_data_sale - a_year_sale) # consant's (h(y) - y) step_for_constant = (stepSize / len(gdp_sale)) * diff_sum_constant # distance to be moved by c step_for_slope = (stepSize / len(gdp_sale)) * diff_sum_slope # distance to be moved by a new_constant = constant - step_for_constant # new c new_slope = slope - step_for_slope # new a return new_constant, new_slope"
},
{
"code": null,
"e": 9666,
"s": 9542,
"text": "Function to get the sales of vehicles provided the values of c, a and x. Used by above function for each sample data (gdp)."
},
{
"code": null,
"e": 9764,
"s": 9666,
"text": "def sale_for_data(constant, slope, data): return constant + slope * data # y = c + ax format"
},
{
"code": null,
"e": 9905,
"s": 9764,
"text": "Iteration to get optimum weights ie optimum values of c and a. It will stop if c and a both are not moving more than 0.01 in next iteration."
},
{
"code": null,
"e": 10585,
"s": 9905,
"text": "def get_weights(gdp_sale) : constant = 1 slope = 1 accepted_diff = 0.01 while 1 == 1: # continue till we reach local minimum new_constant, new_slope = step_cost_function_for(gdp_sale, constant, slope) # if the diff is too less then lets break if (abs(constant - new_constant) <= accepted_diff) and (abs(slope - new_slope) <= accepted_diff): print \"done. Diff is less than \" + str(accepted_diff) return new_constant, new_slope else: constant = new_constant slope = new_slope print \"new values for constant and slope are \" + str(new_constant) + \", \" + \\ str(new_slope)"
},
{
"code": null,
"e": 10617,
"s": 10585,
"text": "And of course the main function"
},
{
"code": null,
"e": 10764,
"s": 10617,
"text": "def main() : contant, slope = get_weights(read_data()) print \"constant :\" + contant + \", slope:\" + slopeif __name__ == '__main__': main()"
},
{
"code": null,
"e": 10786,
"s": 10764,
"text": "I got the equation as"
},
{
"code": null,
"e": 10823,
"s": 10786,
"text": "y (vehicles sales) = 1.43 + 3.84 * x"
},
{
"code": null,
"e": 10841,
"s": 10823,
"text": "x is value of GDP"
},
{
"code": null,
"e": 10956,
"s": 10841,
"text": "So if we have GDP as 7.5 this year then we will have passenger vehicles sales next year as — 1.43 7.5*3.84 = 30.23"
},
{
"code": null,
"e": 11081,
"s": 10956,
"text": "The complete program is below. Its also on github at https://github.com/skhurana333/ml/blob/master/linearRegSingleVariant.py"
}
] |
Dictionary.Keys Property in C#
|
The Dictionary.Keys property in C# is used to fetch all the keys in the Dictionary.
Following is the syntax −
public System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection Keys { get; }
Let us now see an example to implement the Dictionary.Keys property −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict =
new Dictionary<string, string>();
dict.Add("One", "Kagido");
dict.Add("Two", "Ngidi");
dict.Add("Three", "Devillers");
dict.Add("Four", "Smith");
dict.Add("Five", "Warner");
Console.WriteLine("Count of elements = "+dict.Count);
Console.WriteLine("\nKey/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.Write("\nAll the keys..\n");
Dictionary<string, string>.KeyCollection allKeys =
dict.Keys;
foreach(string str in allKeys){
Console.WriteLine("Key = {0}", str);
}
}
}
This will produce the following output −
Count of elements = 5
Key/value pairs...
Key = One, Value = Kagido
Key = Two, Value = Ngidi
Key = Three, Value = Devillers
Key = Four, Value = Smith
Key = Five, Value = Warner
All the keys..
Key = One
Key = Two
Key = Three
Key = Four
Key = Five
Let us now see another example to implement the Dictionary.Keys property −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict =
new Dictionary<string, string>();
dict.Add("One", "Chris");
dict.Add("Two", "Steve");
dict.Add("Three", "Messi");
dict.Add("Four", "Ryan");
dict.Add("Five", "Nathan");
Console.WriteLine("Count of elements = "+dict.Count);
Console.WriteLine("\nKey/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.WriteLine("Value for key three = "+dict["Three"]);
dict["Three"] = "Katie";
Console.WriteLine("Updated value associated with key Three...");
Console.WriteLine(dict["Three"]);
Console.Write("\nAll the keys..\n");
Dictionary<string, string>.KeyCollection allKeys = dict.Keys;
foreach(string str in allKeys){
Console.WriteLine("Key = {0}", str);
}
}
}
This will produce the following output −
Count of elements = 5
Key/value pairs...
Key = One, Value = Chris
Key = Two, Value = Steve
Key = Three, Value = Messi
Key = Four, Value = Ryan
Key = Five, Value = Nathan
Value for key three = Messi
Updated value associated with key Three...
Katie
All the keys..
Key = One
Key = Two
Key = Three
Key = Four
Key = Five
|
[
{
"code": null,
"e": 1146,
"s": 1062,
"text": "The Dictionary.Keys property in C# is used to fetch all the keys in the Dictionary."
},
{
"code": null,
"e": 1172,
"s": 1146,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1259,
"s": 1172,
"text": "public System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection Keys { get; }"
},
{
"code": null,
"e": 1329,
"s": 1259,
"text": "Let us now see an example to implement the Dictionary.Keys property −"
},
{
"code": null,
"e": 2141,
"s": 1329,
"text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main(){\n Dictionary<string, string> dict =\n new Dictionary<string, string>();\n dict.Add(\"One\", \"Kagido\");\n dict.Add(\"Two\", \"Ngidi\");\n dict.Add(\"Three\", \"Devillers\");\n dict.Add(\"Four\", \"Smith\");\n dict.Add(\"Five\", \"Warner\");\n Console.WriteLine(\"Count of elements = \"+dict.Count);\n Console.WriteLine(\"\\nKey/value pairs...\");\n foreach(KeyValuePair<string, string> res in dict){\n Console.WriteLine(\"Key = {0}, Value = {1}\", res.Key, res.Value);\n }\n Console.Write(\"\\nAll the keys..\\n\");\n Dictionary<string, string>.KeyCollection allKeys =\n dict.Keys;\n foreach(string str in allKeys){\n Console.WriteLine(\"Key = {0}\", str);\n }\n }\n}"
},
{
"code": null,
"e": 2182,
"s": 2141,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2427,
"s": 2182,
"text": "Count of elements = 5\nKey/value pairs...\nKey = One, Value = Kagido\nKey = Two, Value = Ngidi\nKey = Three, Value = Devillers\nKey = Four, Value = Smith\nKey = Five, Value = Warner\nAll the keys..\nKey = One\nKey = Two\nKey = Three\nKey = Four\nKey = Five"
},
{
"code": null,
"e": 2502,
"s": 2427,
"text": "Let us now see another example to implement the Dictionary.Keys property −"
},
{
"code": null,
"e": 3509,
"s": 2502,
"text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main(){\n Dictionary<string, string> dict =\n new Dictionary<string, string>();\n dict.Add(\"One\", \"Chris\");\n dict.Add(\"Two\", \"Steve\");\n dict.Add(\"Three\", \"Messi\");\n dict.Add(\"Four\", \"Ryan\");\n dict.Add(\"Five\", \"Nathan\");\n Console.WriteLine(\"Count of elements = \"+dict.Count);\n Console.WriteLine(\"\\nKey/value pairs...\");\n foreach(KeyValuePair<string, string> res in dict){\n Console.WriteLine(\"Key = {0}, Value = {1}\", res.Key, res.Value);\n }\n Console.WriteLine(\"Value for key three = \"+dict[\"Three\"]);\n dict[\"Three\"] = \"Katie\";\n Console.WriteLine(\"Updated value associated with key Three...\");\n Console.WriteLine(dict[\"Three\"]);\n Console.Write(\"\\nAll the keys..\\n\");\n Dictionary<string, string>.KeyCollection allKeys = dict.Keys;\n foreach(string str in allKeys){\n Console.WriteLine(\"Key = {0}\", str);\n }\n }\n}"
},
{
"code": null,
"e": 3550,
"s": 3509,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3866,
"s": 3550,
"text": "Count of elements = 5\nKey/value pairs...\nKey = One, Value = Chris\nKey = Two, Value = Steve\nKey = Three, Value = Messi\nKey = Four, Value = Ryan\nKey = Five, Value = Nathan\nValue for key three = Messi\nUpdated value associated with key Three...\nKatie\nAll the keys..\nKey = One\nKey = Two\nKey = Three\nKey = Four\nKey = Five"
}
] |
Build an Algorithmic Trading System | by Posey | Towards Data Science
|
After dozens of emails and DMs, it seemed appropriate to write a proper introduction to getting started with Algorithmic Trading. This guide should serve as a walkthrough for building your first Proof of Concept algorithmic trading system.
Disclaimer: Luke is a Co-Founder of Spawner, a company whose tech is directly mentioned and used in this article.
Note: Nothing herein is investment advice. This is purely for educational purposes. Good returns with algorithmic trading requires many hours of programming, testing, failing, retrying, and testing again before you have a system robust enough to automatically trade securities. Please try everything in a Paper Trading account before ever testing with real money. Use common sense.
Let’s compartmentalize some of the pieces of an algorithmic trading system or automated trading system. We’ll go through them step-by-step and then showcase a finished example at the end of the article.
Some key ingredients for your trading system:
Signals and Indicators
Trade Execution System
Backtesting
Indicators are the generators of a signal. Indicators are some signal generator that will alert your trading system of when it’s a good time to buy, sell, or hold a security (stock, bond, option, etc.). This could mean opening a position, adding to a position, decreasing a position, shorting, employing some strategy with derivatives, etc...
Technical Indicators have long been used in algorithmic trading systems to generate a signal. Algorithmic traders often build and backtest dozens of combinations of indicators, timeframes, and entries to build a signal that actually generates alpha.
At Spawner, we’re building all sorts of indicators to help users tap into signals and build more robust systems. We’ll use some of the technical indicators provided by Spawner in this article. The perk of using these indicators is we don’t need to gather our own pricing data, as all you need to do is pass the ticker to the API, and the API will return your desired indicator.
You can get your API Token to start interacting with the API.
Using standard REST we’ll pass a ticker and our token and get back JSON:
token = 'sp_znci3#zcnz49Kjznkkze'url = "https://spawnerapi.com/bollinger/aapl/token"response = requests.get(url)print(response.json())
returns:
[{‘upper’: [302.74, 307.65, (...)],
‘lower’: [302.74, 288.01, (...)]}]
These are the upper and lower bands of Bollinger Bands. We’ve got other indicators in the API like RSI, Kelton Bands, and more. The perk to using such an API is we don’t have to gather our own data. We can skip setting up massive data pipelines and directly access our indicators.
We can visualize what our upper and lower Bollinger Bands would look like:
bands = response.json()upper = bands[0]['upper']lower = bands[0]['lower']# Using Plotlyfig.add_trace(go.Scatter(x=date, y=upper, line_color='rgba(107, 191, 22,1)', name='Upper Band'))fig.add_trace(go.Scatter(x=date, y=lower, line_color='rgba(214, 14, 14,1)', name='Lower Band'))
The upper and lower Bollinger Bands above are plotted at one standard deviation above and below the simple moving average (SMA) of the stock price. The bands are sensitive to volatility. Some traders like to buy when the price touches the lower band, go short from upper band, and exit either position when price touches the moving average.
How can we implement that logic in an algorithm? Let’s do some napkin logic and write some pseudo-code:
if price divided by lower band less than 5% different and price > lower band: long $1500if price divided by upper band less than 5% different and price < upper band: short $1500
We can then write the logic for exiting a position. The exit logic can get complex super quick. For example, you might want to gradually take profits, take profits under certain conditions, have stop orders in case your position gets wrecked, etc...:
if position_value > 1550: exit position if position_value < 1450: exit position
Let’s write this out in Python and see how we would do order execution.
So we’ve got a signal we might like. How do we set up order execution? We’ll use the Alpaca API for this. Alpaca has a free trading API through which we can programmatically set up our trades. I’m not associated with Alpaca in any way, other than as a user. But I can say from setting up these systems in various brokerages, Alpaca is far easier to use than the majority of APIs offered by mainstream brokerages.
We could build an API and expose endpoints for our trading system, maybe as a Flask App. For the purposes of this article, we’ll keep it all in one file. We’ll use timers to constantly check market conditions of the tickers we’re following. If any of them trigger our indicators to provide a signal we’ll execute a trade!
Here is an example of an indicator. We return a signal if the price enters the range < .5% above lower Bollinger Band.
def indicator(ticker): # Get lower Bollinger Band url = "https://spawnerapi.com/bollinger/" + ticker + "/" + token response = requests.get(url) bands = response.json() lower = bands[0]['lower'] moving_avg = bands[0]['average'] # get last value in list (latest band values) lower = lower[-1] moving_avg = moving_avg[-1] # Get real-time price quote url = "https://spawnerapi.com/price/" + ticker + "/" + token response = requests.get(url) price = response.json()['price'] # Return signal or no signal if price > lower and ((price / lower)-1) < .005: return 'buy lower', moving_avg[-1], price else: return 'no signal', 'no avg', price
Now we can build our order execution function...
# We'll pass a ticker, quantity to buy, and profit and stop limits.def submit(ticker, quantity, profit_limit, stop_limit): api.submit_order( symbol=ticker, side='buy', type='market', qty=str(quantity), time_in_force='day', order_class='bracket', take_profit=dict( limit_price=str(profit_limit), ), stop_loss=dict( stop_price=str(stop_limit), limit_price=str(stop_limit), ) )
Finally, we’ll write an oversimplified function (not robust!) to check our signal every few seconds and execute a trade if our signal hits.
Note: it’s important we don’t trigger the buy order an infinite number of times. Signals can stay high for a long time, so make sure you’re getting out of the loop! One way to do this is have a list of tickers you’re watching, and whenever you trigger a buy you can remove that ticker from the list. Up to you! Here’s an oversimplified function that will only check the signal once, execute, and quit.
def timer(): x = True while x==True: print('Checking Signal...') signal, moving_avg, price = indicator('AAPL') if signal == 'buy lower': submit('AAPL', 5, moving_avg, (price-(price*.02))) print("Executing Trade.") # exit loop x = False else: print("No Signal.") time.sleep(2)
Let’s test!
If we check our Alpaca portal we’ll see the trade was submitted and our limits for profit and stop loss are set.
Keeping your trades within set risk parameters is important. This means appropriately sizing positions, limiting exposure to conditions like volatility, minimizing drawdowns, managing Value at Risk, etc... We’ll do another article discussing risk in the future. Many of these metrics are already active in the Spawner API.
Backtesting is the one (crucial!) piece we’ll save for another more in-depth article. Backtesting is a monster and we’re spending time making examples for backtesting that should make implementation much easier. Standby for that!
To support my writing and get full access to all articles on Medium, visit https://posey.medium.com/membership
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": 411,
"s": 171,
"text": "After dozens of emails and DMs, it seemed appropriate to write a proper introduction to getting started with Algorithmic Trading. This guide should serve as a walkthrough for building your first Proof of Concept algorithmic trading system."
},
{
"code": null,
"e": 525,
"s": 411,
"text": "Disclaimer: Luke is a Co-Founder of Spawner, a company whose tech is directly mentioned and used in this article."
},
{
"code": null,
"e": 907,
"s": 525,
"text": "Note: Nothing herein is investment advice. This is purely for educational purposes. Good returns with algorithmic trading requires many hours of programming, testing, failing, retrying, and testing again before you have a system robust enough to automatically trade securities. Please try everything in a Paper Trading account before ever testing with real money. Use common sense."
},
{
"code": null,
"e": 1110,
"s": 907,
"text": "Let’s compartmentalize some of the pieces of an algorithmic trading system or automated trading system. We’ll go through them step-by-step and then showcase a finished example at the end of the article."
},
{
"code": null,
"e": 1156,
"s": 1110,
"text": "Some key ingredients for your trading system:"
},
{
"code": null,
"e": 1179,
"s": 1156,
"text": "Signals and Indicators"
},
{
"code": null,
"e": 1202,
"s": 1179,
"text": "Trade Execution System"
},
{
"code": null,
"e": 1214,
"s": 1202,
"text": "Backtesting"
},
{
"code": null,
"e": 1557,
"s": 1214,
"text": "Indicators are the generators of a signal. Indicators are some signal generator that will alert your trading system of when it’s a good time to buy, sell, or hold a security (stock, bond, option, etc.). This could mean opening a position, adding to a position, decreasing a position, shorting, employing some strategy with derivatives, etc..."
},
{
"code": null,
"e": 1807,
"s": 1557,
"text": "Technical Indicators have long been used in algorithmic trading systems to generate a signal. Algorithmic traders often build and backtest dozens of combinations of indicators, timeframes, and entries to build a signal that actually generates alpha."
},
{
"code": null,
"e": 2185,
"s": 1807,
"text": "At Spawner, we’re building all sorts of indicators to help users tap into signals and build more robust systems. We’ll use some of the technical indicators provided by Spawner in this article. The perk of using these indicators is we don’t need to gather our own pricing data, as all you need to do is pass the ticker to the API, and the API will return your desired indicator."
},
{
"code": null,
"e": 2247,
"s": 2185,
"text": "You can get your API Token to start interacting with the API."
},
{
"code": null,
"e": 2320,
"s": 2247,
"text": "Using standard REST we’ll pass a ticker and our token and get back JSON:"
},
{
"code": null,
"e": 2455,
"s": 2320,
"text": "token = 'sp_znci3#zcnz49Kjznkkze'url = \"https://spawnerapi.com/bollinger/aapl/token\"response = requests.get(url)print(response.json())"
},
{
"code": null,
"e": 2464,
"s": 2455,
"text": "returns:"
},
{
"code": null,
"e": 2500,
"s": 2464,
"text": "[{‘upper’: [302.74, 307.65, (...)],"
},
{
"code": null,
"e": 2535,
"s": 2500,
"text": "‘lower’: [302.74, 288.01, (...)]}]"
},
{
"code": null,
"e": 2816,
"s": 2535,
"text": "These are the upper and lower bands of Bollinger Bands. We’ve got other indicators in the API like RSI, Kelton Bands, and more. The perk to using such an API is we don’t have to gather our own data. We can skip setting up massive data pipelines and directly access our indicators."
},
{
"code": null,
"e": 2891,
"s": 2816,
"text": "We can visualize what our upper and lower Bollinger Bands would look like:"
},
{
"code": null,
"e": 3170,
"s": 2891,
"text": "bands = response.json()upper = bands[0]['upper']lower = bands[0]['lower']# Using Plotlyfig.add_trace(go.Scatter(x=date, y=upper, line_color='rgba(107, 191, 22,1)', name='Upper Band'))fig.add_trace(go.Scatter(x=date, y=lower, line_color='rgba(214, 14, 14,1)', name='Lower Band'))"
},
{
"code": null,
"e": 3511,
"s": 3170,
"text": "The upper and lower Bollinger Bands above are plotted at one standard deviation above and below the simple moving average (SMA) of the stock price. The bands are sensitive to volatility. Some traders like to buy when the price touches the lower band, go short from upper band, and exit either position when price touches the moving average."
},
{
"code": null,
"e": 3615,
"s": 3511,
"text": "How can we implement that logic in an algorithm? Let’s do some napkin logic and write some pseudo-code:"
},
{
"code": null,
"e": 3803,
"s": 3615,
"text": "if price divided by lower band less than 5% different and price > lower band: long $1500if price divided by upper band less than 5% different and price < upper band: short $1500"
},
{
"code": null,
"e": 4054,
"s": 3803,
"text": "We can then write the logic for exiting a position. The exit logic can get complex super quick. For example, you might want to gradually take profits, take profits under certain conditions, have stop orders in case your position gets wrecked, etc...:"
},
{
"code": null,
"e": 4146,
"s": 4054,
"text": "if position_value > 1550: exit position if position_value < 1450: exit position"
},
{
"code": null,
"e": 4218,
"s": 4146,
"text": "Let’s write this out in Python and see how we would do order execution."
},
{
"code": null,
"e": 4631,
"s": 4218,
"text": "So we’ve got a signal we might like. How do we set up order execution? We’ll use the Alpaca API for this. Alpaca has a free trading API through which we can programmatically set up our trades. I’m not associated with Alpaca in any way, other than as a user. But I can say from setting up these systems in various brokerages, Alpaca is far easier to use than the majority of APIs offered by mainstream brokerages."
},
{
"code": null,
"e": 4953,
"s": 4631,
"text": "We could build an API and expose endpoints for our trading system, maybe as a Flask App. For the purposes of this article, we’ll keep it all in one file. We’ll use timers to constantly check market conditions of the tickers we’re following. If any of them trigger our indicators to provide a signal we’ll execute a trade!"
},
{
"code": null,
"e": 5072,
"s": 4953,
"text": "Here is an example of an indicator. We return a signal if the price enters the range < .5% above lower Bollinger Band."
},
{
"code": null,
"e": 5767,
"s": 5072,
"text": "def indicator(ticker): # Get lower Bollinger Band url = \"https://spawnerapi.com/bollinger/\" + ticker + \"/\" + token response = requests.get(url) bands = response.json() lower = bands[0]['lower'] moving_avg = bands[0]['average'] # get last value in list (latest band values) lower = lower[-1] moving_avg = moving_avg[-1] # Get real-time price quote url = \"https://spawnerapi.com/price/\" + ticker + \"/\" + token response = requests.get(url) price = response.json()['price'] # Return signal or no signal if price > lower and ((price / lower)-1) < .005: return 'buy lower', moving_avg[-1], price else: return 'no signal', 'no avg', price"
},
{
"code": null,
"e": 5816,
"s": 5767,
"text": "Now we can build our order execution function..."
},
{
"code": null,
"e": 6287,
"s": 5816,
"text": "# We'll pass a ticker, quantity to buy, and profit and stop limits.def submit(ticker, quantity, profit_limit, stop_limit): api.submit_order( symbol=ticker, side='buy', type='market', qty=str(quantity), time_in_force='day', order_class='bracket', take_profit=dict( limit_price=str(profit_limit), ), stop_loss=dict( stop_price=str(stop_limit), limit_price=str(stop_limit), ) )"
},
{
"code": null,
"e": 6427,
"s": 6287,
"text": "Finally, we’ll write an oversimplified function (not robust!) to check our signal every few seconds and execute a trade if our signal hits."
},
{
"code": null,
"e": 6829,
"s": 6427,
"text": "Note: it’s important we don’t trigger the buy order an infinite number of times. Signals can stay high for a long time, so make sure you’re getting out of the loop! One way to do this is have a list of tickers you’re watching, and whenever you trigger a buy you can remove that ticker from the list. Up to you! Here’s an oversimplified function that will only check the signal once, execute, and quit."
},
{
"code": null,
"e": 7184,
"s": 6829,
"text": "def timer(): x = True while x==True: print('Checking Signal...') signal, moving_avg, price = indicator('AAPL') if signal == 'buy lower': submit('AAPL', 5, moving_avg, (price-(price*.02))) print(\"Executing Trade.\") # exit loop x = False else: print(\"No Signal.\") time.sleep(2)"
},
{
"code": null,
"e": 7196,
"s": 7184,
"text": "Let’s test!"
},
{
"code": null,
"e": 7309,
"s": 7196,
"text": "If we check our Alpaca portal we’ll see the trade was submitted and our limits for profit and stop loss are set."
},
{
"code": null,
"e": 7632,
"s": 7309,
"text": "Keeping your trades within set risk parameters is important. This means appropriately sizing positions, limiting exposure to conditions like volatility, minimizing drawdowns, managing Value at Risk, etc... We’ll do another article discussing risk in the future. Many of these metrics are already active in the Spawner API."
},
{
"code": null,
"e": 7862,
"s": 7632,
"text": "Backtesting is the one (crucial!) piece we’ll save for another more in-depth article. Backtesting is a monster and we’re spending time making examples for backtesting that should make implementation much easier. Standby for that!"
},
{
"code": null,
"e": 7973,
"s": 7862,
"text": "To support my writing and get full access to all articles on Medium, visit https://posey.medium.com/membership"
}
] |
Printing TreeMap Having Custom Class Objects as Keys or Values in Java
|
04 Jan, 2021
TreeMap is a map implementation that keeps its entry sorted according to the natural ordering of its keys. So, for an integer, this would mean ascending order, and for string, it would be alphabetical order. TreeMap can also be sorted according to the user by using a comparator at construction time.
Here we are going to see how to print TreeMap having custom class objects as keys or values. But before that, let’s see exactly what happens when trying to print it normally. While trying to print object directly printed value might not be in proper format and in multiple cases garbage values like @agc1243 print at the output.
Normal Printing implementation:
Java
// Printing TreeMap Having Custom Class Objects directlyimport java.io.*;import java.util.Map;import java.util.Set;import java.util.TreeMap; // make a class Studentclass Student { private Integer regId; private String name; public Student(Integer regId, String name) { this.regId = regId; this.name = name; } public Integer getId() { return regId; } public String getName() { return name; }}class GFG { public static void main(String[] args) { // creating a TreeMap TreeMap<Integer, Student> tmap = new TreeMap<Integer, Student>(); // Mapping student objects to int keys tmap.put(1, new Student(101, "Abhay")); tmap.put(2, new Student(102, "Sarika")); tmap.put(3, new Student(103, "Vanshika")); // get all entries Set<Map.Entry<Integer, Student> > entries = tmap.entrySet(); // printing keys and values using for loop for (Map.Entry<Integer, Student> entry : entries) { System.out.println(entry.getKey() + "=>" + entry.getValue()); } }}
1=>Student@3941a79c
2=>Student@506e1b77
3=>Student@4fca772d
The reason why the output is not in the proper format?
The reason is our Student class has not overridden the toString method from the Object class. So that is why the toString method of the Object class is used here which prints “class_name@object_hashcode” when an object is printed.
So, the next question is How to fix this?
To fix this, override the toString method in our Student class.
Implementation:
Java
// Printing TreeMap Having Custom Class// Objects as Keys or Values in Javaimport java.util.Map;import java.util.Set;import java.util.TreeMap; // make a class Studentclass Student { private Integer regId; private String name; public Student(Integer regId, String name) { this.regId = regId; this.name = name; } public Integer getId() { return regId; } public String getName() { return name; } /* * Override this method in your custom class * used as key or value in the TreeMap */ public String toString() { return "[" + this.getId() + "=>" + this.getName() + "]"; }}class GFG { public static void main(String[] args) { // creating a TreeMap TreeMap<Integer, Student> tmap = new TreeMap<Integer, Student>(); // Mapping student objects to int keys tmap.put(1, new Student(101, "Abhay")); tmap.put(2, new Student(102, "Sarika")); tmap.put(3, new Student(103, "Vanshika")); // get all entries Set<Map.Entry<Integer, Student> > entries = tmap.entrySet(); // printing keys and values using for loop for (Map.Entry<Integer, Student> entry : entries) { System.out.println(entry.getKey() + "=>" + entry.getValue()); } }}
1=>[101=>Abhay]
2=>[102=>Sarika]
3=>[103=>Vanshika]
Note: So the main tip here to remember is to always override the toString() method in your custom classes.
java-TreeMap
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jan, 2021"
},
{
"code": null,
"e": 329,
"s": 28,
"text": "TreeMap is a map implementation that keeps its entry sorted according to the natural ordering of its keys. So, for an integer, this would mean ascending order, and for string, it would be alphabetical order. TreeMap can also be sorted according to the user by using a comparator at construction time."
},
{
"code": null,
"e": 659,
"s": 329,
"text": "Here we are going to see how to print TreeMap having custom class objects as keys or values. But before that, let’s see exactly what happens when trying to print it normally. While trying to print object directly printed value might not be in proper format and in multiple cases garbage values like @agc1243 print at the output."
},
{
"code": null,
"e": 691,
"s": 659,
"text": "Normal Printing implementation:"
},
{
"code": null,
"e": 696,
"s": 691,
"text": "Java"
},
{
"code": "// Printing TreeMap Having Custom Class Objects directlyimport java.io.*;import java.util.Map;import java.util.Set;import java.util.TreeMap; // make a class Studentclass Student { private Integer regId; private String name; public Student(Integer regId, String name) { this.regId = regId; this.name = name; } public Integer getId() { return regId; } public String getName() { return name; }}class GFG { public static void main(String[] args) { // creating a TreeMap TreeMap<Integer, Student> tmap = new TreeMap<Integer, Student>(); // Mapping student objects to int keys tmap.put(1, new Student(101, \"Abhay\")); tmap.put(2, new Student(102, \"Sarika\")); tmap.put(3, new Student(103, \"Vanshika\")); // get all entries Set<Map.Entry<Integer, Student> > entries = tmap.entrySet(); // printing keys and values using for loop for (Map.Entry<Integer, Student> entry : entries) { System.out.println(entry.getKey() + \"=>\" + entry.getValue()); } }}",
"e": 1834,
"s": 696,
"text": null
},
{
"code": null,
"e": 1894,
"s": 1834,
"text": "1=>Student@3941a79c\n2=>Student@506e1b77\n3=>Student@4fca772d"
},
{
"code": null,
"e": 1951,
"s": 1896,
"text": "The reason why the output is not in the proper format?"
},
{
"code": null,
"e": 2182,
"s": 1951,
"text": "The reason is our Student class has not overridden the toString method from the Object class. So that is why the toString method of the Object class is used here which prints “class_name@object_hashcode” when an object is printed."
},
{
"code": null,
"e": 2224,
"s": 2182,
"text": "So, the next question is How to fix this?"
},
{
"code": null,
"e": 2288,
"s": 2224,
"text": "To fix this, override the toString method in our Student class."
},
{
"code": null,
"e": 2304,
"s": 2288,
"text": "Implementation:"
},
{
"code": null,
"e": 2309,
"s": 2304,
"text": "Java"
},
{
"code": "// Printing TreeMap Having Custom Class// Objects as Keys or Values in Javaimport java.util.Map;import java.util.Set;import java.util.TreeMap; // make a class Studentclass Student { private Integer regId; private String name; public Student(Integer regId, String name) { this.regId = regId; this.name = name; } public Integer getId() { return regId; } public String getName() { return name; } /* * Override this method in your custom class * used as key or value in the TreeMap */ public String toString() { return \"[\" + this.getId() + \"=>\" + this.getName() + \"]\"; }}class GFG { public static void main(String[] args) { // creating a TreeMap TreeMap<Integer, Student> tmap = new TreeMap<Integer, Student>(); // Mapping student objects to int keys tmap.put(1, new Student(101, \"Abhay\")); tmap.put(2, new Student(102, \"Sarika\")); tmap.put(3, new Student(103, \"Vanshika\")); // get all entries Set<Map.Entry<Integer, Student> > entries = tmap.entrySet(); // printing keys and values using for loop for (Map.Entry<Integer, Student> entry : entries) { System.out.println(entry.getKey() + \"=>\" + entry.getValue()); } }}",
"e": 3665,
"s": 2309,
"text": null
},
{
"code": null,
"e": 3717,
"s": 3665,
"text": "1=>[101=>Abhay]\n2=>[102=>Sarika]\n3=>[103=>Vanshika]"
},
{
"code": null,
"e": 3824,
"s": 3717,
"text": "Note: So the main tip here to remember is to always override the toString() method in your custom classes."
},
{
"code": null,
"e": 3837,
"s": 3824,
"text": "java-TreeMap"
},
{
"code": null,
"e": 3844,
"s": 3837,
"text": "Picked"
},
{
"code": null,
"e": 3849,
"s": 3844,
"text": "Java"
},
{
"code": null,
"e": 3863,
"s": 3849,
"text": "Java Programs"
},
{
"code": null,
"e": 3868,
"s": 3863,
"text": "Java"
},
{
"code": null,
"e": 3966,
"s": 3868,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3981,
"s": 3966,
"text": "Stream In Java"
},
{
"code": null,
"e": 4002,
"s": 3981,
"text": "Introduction to Java"
},
{
"code": null,
"e": 4023,
"s": 4002,
"text": "Constructors in Java"
},
{
"code": null,
"e": 4042,
"s": 4023,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 4059,
"s": 4042,
"text": "Generics in Java"
},
{
"code": null,
"e": 4085,
"s": 4059,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4119,
"s": 4085,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 4166,
"s": 4119,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 4204,
"s": 4166,
"text": "Factory method design pattern in Java"
}
] |
Number and its Types in Julia
|
01 Aug, 2020
Julia is a high-level, dynamic, general-purpose programming language that can be used to write software applications, and is well-suited for data analysis and computational science. Numbers are important in any programming language. Numbers in Julia is classified into two types: Integer and Floating-Point Numbers. Julia provides a wide range of primitive numeric types. These inbuilt numeric datatypes help Julia to take full advantage of computational resources. Julia also provides software support for Arbitrary Precision Arithmetic, which can handle numeric operations which is difficult to represent in native hardware representations. However, support for Arbitrary Precision Arithmetic comes at the cost of slower performance. Complex and Rational Numbers are defined on top of primitive numeric types.
The following are Julia’s primitive numeric types:
IntegerTypeSignedNumber of bitsRangeInt8Yes8-2^7 to 2^7 – 1UInt8No80 to 2^8-1Int16Yes16-2^15 to 2^15-1UInt16No160 to 2^16 – 1Int32Yes32-2^31 to 2^31-1UInt32No320 to 2^32-1Int64Yes64-2^63 to 2^63-1UInt64No640 to 2^64 – 1Int128Yes128-2^127 to 2^127 – 1UInt128No1280 to 2^128 – 1BoolN/A8false(0) and true(1)Floating point numbersTypePrecisionNumber of bitsFloat16half16Float32single32Float64double64
IntegerTypeSignedNumber of bitsRangeInt8Yes8-2^7 to 2^7 – 1UInt8No80 to 2^8-1Int16Yes16-2^15 to 2^15-1UInt16No160 to 2^16 – 1Int32Yes32-2^31 to 2^31-1UInt32No320 to 2^32-1Int64Yes64-2^63 to 2^63-1UInt64No640 to 2^64 – 1Int128Yes128-2^127 to 2^127 – 1UInt128No1280 to 2^128 – 1BoolN/A8false(0) and true(1)
Floating point numbersTypePrecisionNumber of bitsFloat16half16Float32single32Float64double64
The default type for an integer literal depends on whether the system is 32-bit or 64-bit. The variable Sys.WORD_SIZE indicates whether the system is 32-bit or 64-bit:
println(Sys.WORD_SIZE)println(typeof(123))
Output:
However, larger integer literals that cannot be represented using 32 bits are represented using 64 bits, regardless of the system type.Unsigned integers are represented using the 0x prefix and hexadecimal digits 0-9a-f or 0-9A-F. Size of the unsigned integer is determined by the number of hex digits used.
println(typeof(0x12))println(typeof(0x123))println(typeof(0x1234567))println(typeof(0x123456789abcd))println(typeof(0x1112223333444555566677788))
Output:
Binary and octal literals are also supported in Julia.
println(typeof(0b10))println(typeof(0o10))println(0b10)println(0o10)
Output:
println(typemin(Int8), ' ', typemax(Int8))println(typemin(Int16), ' ', typemax(Int16))println(typemin(Int32), ' ', typemax(Int32))println(typemin(Int64), ' ', typemax(Int64))println(typemin(Int128), ' ', typemax(Int128))
Output:
Floating Point Numbers are represented in a standard format. There is no literal format for Float32, but we can convert values to Float32 by writing an ‘f’ or explicit typecasting.
println(typeof(1.0))println(typeof(.5))println(typeof(-1.23))println(typeof(0.5f0))println(2.5f-4)println(typeof(2.5f-4))println(typeof(Float32(-1.5)))
Output:
Floating point numbers have a positive zero and a negative zero which are equal to each other but have different binary representations.
julia> 0.0 == -0.0
true
julia> bitstring(0.0)
"0000000000000000000000000000000000000000000000000000000000000000"
julia> bitstring(-0.0)
"1000000000000000000000000000000000000000000000000000000000000000"
Global constant ‘im’ is used to represent complex number i where i is square root of -1.
println(typeof(1+2im)) # performing mathematical operations println()println((1 + 2im) + (2 + 3im))println((5 + 5im) - (3 + 2im))println((5 + 2im) * (3 + 2im))println((1 + 2im) / (1 - 2im))println(3(2 - 5im)^2)
Output:
Julia has rational numbers to represent exact ratios of integers. Rational numbers are constructed using the // operator.
println(typeof(6//9))println(6//9)println(-6//9)println(-6//-9)println(5//8 + 3//12)println(6//5 - 10//13)println(5//8 * 3//12)println(6//5 / 10//3)
Output:
Julia-Basics
Picked
Julia
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": 840,
"s": 28,
"text": "Julia is a high-level, dynamic, general-purpose programming language that can be used to write software applications, and is well-suited for data analysis and computational science. Numbers are important in any programming language. Numbers in Julia is classified into two types: Integer and Floating-Point Numbers. Julia provides a wide range of primitive numeric types. These inbuilt numeric datatypes help Julia to take full advantage of computational resources. Julia also provides software support for Arbitrary Precision Arithmetic, which can handle numeric operations which is difficult to represent in native hardware representations. However, support for Arbitrary Precision Arithmetic comes at the cost of slower performance. Complex and Rational Numbers are defined on top of primitive numeric types."
},
{
"code": null,
"e": 891,
"s": 840,
"text": "The following are Julia’s primitive numeric types:"
},
{
"code": null,
"e": 1288,
"s": 891,
"text": "IntegerTypeSignedNumber of bitsRangeInt8Yes8-2^7 to 2^7 – 1UInt8No80 to 2^8-1Int16Yes16-2^15 to 2^15-1UInt16No160 to 2^16 – 1Int32Yes32-2^31 to 2^31-1UInt32No320 to 2^32-1Int64Yes64-2^63 to 2^63-1UInt64No640 to 2^64 – 1Int128Yes128-2^127 to 2^127 – 1UInt128No1280 to 2^128 – 1BoolN/A8false(0) and true(1)Floating point numbersTypePrecisionNumber of bitsFloat16half16Float32single32Float64double64"
},
{
"code": null,
"e": 1593,
"s": 1288,
"text": "IntegerTypeSignedNumber of bitsRangeInt8Yes8-2^7 to 2^7 – 1UInt8No80 to 2^8-1Int16Yes16-2^15 to 2^15-1UInt16No160 to 2^16 – 1Int32Yes32-2^31 to 2^31-1UInt32No320 to 2^32-1Int64Yes64-2^63 to 2^63-1UInt64No640 to 2^64 – 1Int128Yes128-2^127 to 2^127 – 1UInt128No1280 to 2^128 – 1BoolN/A8false(0) and true(1)"
},
{
"code": null,
"e": 1686,
"s": 1593,
"text": "Floating point numbersTypePrecisionNumber of bitsFloat16half16Float32single32Float64double64"
},
{
"code": null,
"e": 1854,
"s": 1686,
"text": "The default type for an integer literal depends on whether the system is 32-bit or 64-bit. The variable Sys.WORD_SIZE indicates whether the system is 32-bit or 64-bit:"
},
{
"code": "println(Sys.WORD_SIZE)println(typeof(123))",
"e": 1897,
"s": 1854,
"text": null
},
{
"code": null,
"e": 1905,
"s": 1897,
"text": "Output:"
},
{
"code": null,
"e": 2212,
"s": 1905,
"text": "However, larger integer literals that cannot be represented using 32 bits are represented using 64 bits, regardless of the system type.Unsigned integers are represented using the 0x prefix and hexadecimal digits 0-9a-f or 0-9A-F. Size of the unsigned integer is determined by the number of hex digits used."
},
{
"code": "println(typeof(0x12))println(typeof(0x123))println(typeof(0x1234567))println(typeof(0x123456789abcd))println(typeof(0x1112223333444555566677788))",
"e": 2358,
"s": 2212,
"text": null
},
{
"code": null,
"e": 2366,
"s": 2358,
"text": "Output:"
},
{
"code": null,
"e": 2421,
"s": 2366,
"text": "Binary and octal literals are also supported in Julia."
},
{
"code": "println(typeof(0b10))println(typeof(0o10))println(0b10)println(0o10)",
"e": 2490,
"s": 2421,
"text": null
},
{
"code": null,
"e": 2498,
"s": 2490,
"text": "Output:"
},
{
"code": "println(typemin(Int8), ' ', typemax(Int8))println(typemin(Int16), ' ', typemax(Int16))println(typemin(Int32), ' ', typemax(Int32))println(typemin(Int64), ' ', typemax(Int64))println(typemin(Int128), ' ', typemax(Int128))",
"e": 2719,
"s": 2498,
"text": null
},
{
"code": null,
"e": 2727,
"s": 2719,
"text": "Output:"
},
{
"code": null,
"e": 2908,
"s": 2727,
"text": "Floating Point Numbers are represented in a standard format. There is no literal format for Float32, but we can convert values to Float32 by writing an ‘f’ or explicit typecasting."
},
{
"code": "println(typeof(1.0))println(typeof(.5))println(typeof(-1.23))println(typeof(0.5f0))println(2.5f-4)println(typeof(2.5f-4))println(typeof(Float32(-1.5)))",
"e": 3060,
"s": 2908,
"text": null
},
{
"code": null,
"e": 3068,
"s": 3060,
"text": "Output:"
},
{
"code": null,
"e": 3205,
"s": 3068,
"text": "Floating point numbers have a positive zero and a negative zero which are equal to each other but have different binary representations."
},
{
"code": null,
"e": 3411,
"s": 3205,
"text": "julia> 0.0 == -0.0\ntrue\n\njulia> bitstring(0.0)\n\"0000000000000000000000000000000000000000000000000000000000000000\"\n\njulia> bitstring(-0.0)\n\"1000000000000000000000000000000000000000000000000000000000000000\"\n"
},
{
"code": null,
"e": 3500,
"s": 3411,
"text": "Global constant ‘im’ is used to represent complex number i where i is square root of -1."
},
{
"code": "println(typeof(1+2im)) # performing mathematical operations println()println((1 + 2im) + (2 + 3im))println((5 + 5im) - (3 + 2im))println((5 + 2im) * (3 + 2im))println((1 + 2im) / (1 - 2im))println(3(2 - 5im)^2)",
"e": 3713,
"s": 3500,
"text": null
},
{
"code": null,
"e": 3721,
"s": 3713,
"text": "Output:"
},
{
"code": null,
"e": 3843,
"s": 3721,
"text": "Julia has rational numbers to represent exact ratios of integers. Rational numbers are constructed using the // operator."
},
{
"code": "println(typeof(6//9))println(6//9)println(-6//9)println(-6//-9)println(5//8 + 3//12)println(6//5 - 10//13)println(5//8 * 3//12)println(6//5 / 10//3)",
"e": 3992,
"s": 3843,
"text": null
},
{
"code": null,
"e": 4000,
"s": 3992,
"text": "Output:"
},
{
"code": null,
"e": 4013,
"s": 4000,
"text": "Julia-Basics"
},
{
"code": null,
"e": 4020,
"s": 4013,
"text": "Picked"
},
{
"code": null,
"e": 4026,
"s": 4020,
"text": "Julia"
}
] |
Java Program for Breadth First Search or BFS for a Graph
|
20 Dec, 2021
Breadth First Traversal (or Search) for a graph is similar to Breadth First Traversal of a tree (See method 2 of this post). The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array. For simplicity, it is assumed that all vertices are reachable from the starting vertex.For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. A Breadth First Traversal of the following graph is 2, 0, 3, 1.
Following are the implementations of simple Breadth First Traversal from a given source.
The implementation uses adjacency list representation of graphs. STL\’s list container is used to store lists of adjacent nodes and queue of nodes needed for BFS traversal.
Java
// Java program to print BFS traversal from a given source vertex.// BFS(int s) traverses vertices reachable from s.import java.io.*;import java.util.*; // This class represents a directed graph using adjacency list// representationclass Graph{ private int V; // No. of vertices private LinkedList<Integer> adj[]; //Adjacency Lists // Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } // Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); } // prints BFS traversal from a given source s void BFS(int s) { // Mark all the vertices as not visited(By default // set as false) boolean visited[] = new boolean[V]; // Create a queue for BFS LinkedList<Integer> queue = new LinkedList<Integer>(); // Mark the current node as visited and enqueue it visited[s]=true; queue.add(s); while (queue.size() != 0) { // Dequeue a vertex from queue and print it s = queue.poll(); System.out.print(s+" "); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it // visited and enqueue it Iterator<Integer> i = adj[s].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) { visited[n] = true; queue.add(n); } } } } // Driver method to public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println("Following is Breadth First Traversal "+ "(starting from vertex 2)"); g.BFS(2); }}// This code is contributed by Aakash Hasija
Please refer complete article on Breadth First Search or BFS for a Graph for more details!
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Convert Char to String in Java?
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
How to Write Data into Excel Sheet using Java?
Comparing two ArrayList In Java
Java Program to Read a File to String
SHA-1 Hash
Java Program to Append a String in an Existing File
Java Program to Find Sum of Array Elements
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Dec, 2021"
},
{
"code": null,
"e": 768,
"s": 28,
"text": "Breadth First Traversal (or Search) for a graph is similar to Breadth First Traversal of a tree (See method 2 of this post). The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array. For simplicity, it is assumed that all vertices are reachable from the starting vertex.For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. A Breadth First Traversal of the following graph is 2, 0, 3, 1."
},
{
"code": null,
"e": 857,
"s": 768,
"text": "Following are the implementations of simple Breadth First Traversal from a given source."
},
{
"code": null,
"e": 1030,
"s": 857,
"text": "The implementation uses adjacency list representation of graphs. STL\\’s list container is used to store lists of adjacent nodes and queue of nodes needed for BFS traversal."
},
{
"code": null,
"e": 1035,
"s": 1030,
"text": "Java"
},
{
"code": "// Java program to print BFS traversal from a given source vertex.// BFS(int s) traverses vertices reachable from s.import java.io.*;import java.util.*; // This class represents a directed graph using adjacency list// representationclass Graph{ private int V; // No. of vertices private LinkedList<Integer> adj[]; //Adjacency Lists // Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } // Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); } // prints BFS traversal from a given source s void BFS(int s) { // Mark all the vertices as not visited(By default // set as false) boolean visited[] = new boolean[V]; // Create a queue for BFS LinkedList<Integer> queue = new LinkedList<Integer>(); // Mark the current node as visited and enqueue it visited[s]=true; queue.add(s); while (queue.size() != 0) { // Dequeue a vertex from queue and print it s = queue.poll(); System.out.print(s+\" \"); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it // visited and enqueue it Iterator<Integer> i = adj[s].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) { visited[n] = true; queue.add(n); } } } } // Driver method to public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println(\"Following is Breadth First Traversal \"+ \"(starting from vertex 2)\"); g.BFS(2); }}// This code is contributed by Aakash Hasija",
"e": 3117,
"s": 1035,
"text": null
},
{
"code": null,
"e": 3208,
"s": 3117,
"text": "Please refer complete article on Breadth First Search or BFS for a Graph for more details!"
},
{
"code": null,
"e": 3222,
"s": 3208,
"text": "Java Programs"
},
{
"code": null,
"e": 3320,
"s": 3222,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3368,
"s": 3320,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 3407,
"s": 3368,
"text": "How to Convert Char to String in Java?"
},
{
"code": null,
"e": 3458,
"s": 3407,
"text": "How to Get Elements By Index from HashSet in Java?"
},
{
"code": null,
"e": 3492,
"s": 3458,
"text": "Java Program to Write into a File"
},
{
"code": null,
"e": 3539,
"s": 3492,
"text": "How to Write Data into Excel Sheet using Java?"
},
{
"code": null,
"e": 3571,
"s": 3539,
"text": "Comparing two ArrayList In Java"
},
{
"code": null,
"e": 3609,
"s": 3571,
"text": "Java Program to Read a File to String"
},
{
"code": null,
"e": 3620,
"s": 3609,
"text": "SHA-1 Hash"
},
{
"code": null,
"e": 3672,
"s": 3620,
"text": "Java Program to Append a String in an Existing File"
}
] |
Program to Parse a comma separated string in C++
|
24 Oct, 2020
Given a comma-separated string, the task is to parse this string and separate the words in C++.Examples:
Input: "1,2,3,4,5"
Output:
1
2
3
4
5
Input: "Geeks,for,Geeks"
Output:
Geeks
for
Geeks
Approach:
Get the string in stream – stringstream
Create a string vector to store the parsed words
Now till there is a string in stringstream, checked by good() method,Get the substring if the string from starting point to the first appearance of ‘, ‘ using getline() methodThis will give the word in the substringNow store this word in the vectorThis word is now removed from the stream and stored in the vector
Get the substring if the string from starting point to the first appearance of ‘, ‘ using getline() method
This will give the word in the substring
Now store this word in the vector
This word is now removed from the stream and stored in the vector
Below is the implementation of the above approach:
CPP
// C++ program to parse a comma-separated string #include <bits/stdc++.h>using namespace std; int main(){ string str = "1,2,3,4,5,6"; vector<string> v; stringstream ss(str); while (ss.good()) { string substr; getline(ss, substr, ','); v.push_back(substr); } for (size_t i = 0; i < v.size(); i++) cout << v[i] << endl;}
1
2
3
4
5
6
danielcrawley1998
C++
C++ Programs
Strings
Strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Oct, 2020"
},
{
"code": null,
"e": 135,
"s": 28,
"text": "Given a comma-separated string, the task is to parse this string and separate the words in C++.Examples: "
},
{
"code": null,
"e": 229,
"s": 135,
"text": "Input: \"1,2,3,4,5\"\nOutput: \n1\n2\n3\n4\n5\n\nInput: \"Geeks,for,Geeks\"\nOutput: \nGeeks\nfor\nGeeks\n\n\n\n\n"
},
{
"code": null,
"e": 242,
"s": 231,
"text": "Approach: "
},
{
"code": null,
"e": 282,
"s": 242,
"text": "Get the string in stream – stringstream"
},
{
"code": null,
"e": 331,
"s": 282,
"text": "Create a string vector to store the parsed words"
},
{
"code": null,
"e": 645,
"s": 331,
"text": "Now till there is a string in stringstream, checked by good() method,Get the substring if the string from starting point to the first appearance of ‘, ‘ using getline() methodThis will give the word in the substringNow store this word in the vectorThis word is now removed from the stream and stored in the vector"
},
{
"code": null,
"e": 752,
"s": 645,
"text": "Get the substring if the string from starting point to the first appearance of ‘, ‘ using getline() method"
},
{
"code": null,
"e": 793,
"s": 752,
"text": "This will give the word in the substring"
},
{
"code": null,
"e": 827,
"s": 793,
"text": "Now store this word in the vector"
},
{
"code": null,
"e": 893,
"s": 827,
"text": "This word is now removed from the stream and stored in the vector"
},
{
"code": null,
"e": 945,
"s": 893,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 949,
"s": 945,
"text": "CPP"
},
{
"code": "// C++ program to parse a comma-separated string #include <bits/stdc++.h>using namespace std; int main(){ string str = \"1,2,3,4,5,6\"; vector<string> v; stringstream ss(str); while (ss.good()) { string substr; getline(ss, substr, ','); v.push_back(substr); } for (size_t i = 0; i < v.size(); i++) cout << v[i] << endl;}",
"e": 1317,
"s": 949,
"text": null
},
{
"code": null,
"e": 1334,
"s": 1317,
"text": "1\n2\n3\n4\n5\n6\n\n\n\n\n"
},
{
"code": null,
"e": 1354,
"s": 1336,
"text": "danielcrawley1998"
},
{
"code": null,
"e": 1358,
"s": 1354,
"text": "C++"
},
{
"code": null,
"e": 1371,
"s": 1358,
"text": "C++ Programs"
},
{
"code": null,
"e": 1379,
"s": 1371,
"text": "Strings"
},
{
"code": null,
"e": 1387,
"s": 1379,
"text": "Strings"
},
{
"code": null,
"e": 1391,
"s": 1387,
"text": "CPP"
}
] |
Matplotlib.axes.Axes.quiver() in Python
|
19 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.barbs() function in axes module of matplotlib library is also used to plot a 2D field of arrows.
Syntax: Axes.quiver(self, *args, data=None, **kw
Parameters: This method accept the following parameters that are described below:
X, Y : These parameter are the x and y coordinates of the arrow locations.
U, V: These parameter are the x and y components of the arrow vector.
C : This parameter contains the numeric data that defines the arrow colors by colormapping via norm and cmap.
pivot : This parameter is the part of the arrow that is anchored to the X, Y grid.
units : This parameter is the arrow dimensions (except for length) are measured in multiples of this unit.
angles : This parameter is the method for determining the angle of the arrows.
scale : This parameter is the number of data units per arrow length unit.
scale_units : This parameter is an optional parameter nad it contains these values ‘width’, ‘height’, ‘dots’, ‘inches’, ‘x’, ‘y’, ‘xy’ .
width : This parameter is the shaft width in arrow units.
headwidth : This parameter is the head width as multiple of shaft width.
headlength : This parameter is the length width as multiple of shaft width.
headwidth : This parameter is the head width as multiple of shaft width.
headaxislength : This parameter is the head length at shaft intersection.
minshaft : This parameter is the length below which arrow scales, in units of head length.
minlength : This parameter is the minimum length as a multiple of shaft width.
color : This parameter is the explicit color(s) for the arrows.
Below examples illustrate the matplotlib.axes.Axes.quiver() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np X = np.arange(-20, 20, 0.5)Y = np.arange(-20, 20, 0.5)U, V = np.meshgrid(X, Y) fig, ax = plt.subplots()q = ax.quiver(X, Y, U, V) ax.set_title('matplotlib.axes.Axes.quiver()\ Example', fontsize = 14, fontweight ='bold')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np X, Y = np.meshgrid(np.arange(0, 2 * np.pi, .2), np.arange(0, 2 * np.pi, .2))U = np.cos(X**2)V = np.sin(Y**2)C = U**2 + V**2 fig, ax = plt.subplots()ax.quiver(X, Y, U, V, C, units ='width')ax.set_title('matplotlib.axes.Axes.quiver() \Example', fontsize = 14, fontweight ='bold')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 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": 434,
"s": 328,
"text": "The Axes.barbs() function in axes module of matplotlib library is also used to plot a 2D field of arrows."
},
{
"code": null,
"e": 483,
"s": 434,
"text": "Syntax: Axes.quiver(self, *args, data=None, **kw"
},
{
"code": null,
"e": 565,
"s": 483,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 640,
"s": 565,
"text": "X, Y : These parameter are the x and y coordinates of the arrow locations."
},
{
"code": null,
"e": 710,
"s": 640,
"text": "U, V: These parameter are the x and y components of the arrow vector."
},
{
"code": null,
"e": 820,
"s": 710,
"text": "C : This parameter contains the numeric data that defines the arrow colors by colormapping via norm and cmap."
},
{
"code": null,
"e": 903,
"s": 820,
"text": "pivot : This parameter is the part of the arrow that is anchored to the X, Y grid."
},
{
"code": null,
"e": 1010,
"s": 903,
"text": "units : This parameter is the arrow dimensions (except for length) are measured in multiples of this unit."
},
{
"code": null,
"e": 1089,
"s": 1010,
"text": "angles : This parameter is the method for determining the angle of the arrows."
},
{
"code": null,
"e": 1163,
"s": 1089,
"text": "scale : This parameter is the number of data units per arrow length unit."
},
{
"code": null,
"e": 1300,
"s": 1163,
"text": "scale_units : This parameter is an optional parameter nad it contains these values ‘width’, ‘height’, ‘dots’, ‘inches’, ‘x’, ‘y’, ‘xy’ ."
},
{
"code": null,
"e": 1358,
"s": 1300,
"text": "width : This parameter is the shaft width in arrow units."
},
{
"code": null,
"e": 1431,
"s": 1358,
"text": "headwidth : This parameter is the head width as multiple of shaft width."
},
{
"code": null,
"e": 1507,
"s": 1431,
"text": "headlength : This parameter is the length width as multiple of shaft width."
},
{
"code": null,
"e": 1580,
"s": 1507,
"text": "headwidth : This parameter is the head width as multiple of shaft width."
},
{
"code": null,
"e": 1654,
"s": 1580,
"text": "headaxislength : This parameter is the head length at shaft intersection."
},
{
"code": null,
"e": 1745,
"s": 1654,
"text": "minshaft : This parameter is the length below which arrow scales, in units of head length."
},
{
"code": null,
"e": 1824,
"s": 1745,
"text": "minlength : This parameter is the minimum length as a multiple of shaft width."
},
{
"code": null,
"e": 1888,
"s": 1824,
"text": "color : This parameter is the explicit color(s) for the arrows."
},
{
"code": null,
"e": 1977,
"s": 1888,
"text": "Below examples illustrate the matplotlib.axes.Axes.quiver() function in matplotlib.axes:"
},
{
"code": null,
"e": 1988,
"s": 1977,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np X = np.arange(-20, 20, 0.5)Y = np.arange(-20, 20, 0.5)U, V = np.meshgrid(X, Y) fig, ax = plt.subplots()q = ax.quiver(X, Y, U, V) ax.set_title('matplotlib.axes.Axes.quiver()\\ Example', fontsize = 14, fontweight ='bold')plt.show()",
"e": 2313,
"s": 1988,
"text": null
},
{
"code": null,
"e": 2321,
"s": 2313,
"text": "Output:"
},
{
"code": null,
"e": 2332,
"s": 2321,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np X, Y = np.meshgrid(np.arange(0, 2 * np.pi, .2), np.arange(0, 2 * np.pi, .2))U = np.cos(X**2)V = np.sin(Y**2)C = U**2 + V**2 fig, ax = plt.subplots()ax.quiver(X, Y, U, V, C, units ='width')ax.set_title('matplotlib.axes.Axes.quiver() \\Example', fontsize = 14, fontweight ='bold')plt.show()",
"e": 2734,
"s": 2332,
"text": null
},
{
"code": null,
"e": 2742,
"s": 2734,
"text": "Output:"
},
{
"code": null,
"e": 2760,
"s": 2742,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2767,
"s": 2760,
"text": "Python"
}
] |
How to create a Currency converter app in ReactJS ?
|
20 Aug, 2021
In this article, we will be building a very simple currency converter app with the help of an API.
Our app contains three sections, one for taking the user input and store it inside a state variable, a menu where users can change the units of conversion, and finally a display section where we display the final results. At first, we call the API and store the required conversion rates inside a state variable and later we perform some operations that convert the currencies. Our app contains a flip switch where users can switch currencies at any time.
Prerequisites: The pre-requisites for this project are:
React
Functional Components
React Hooks
React Axios & API
Javascript ES6
Creating a React application and installing some npm packages:
Step 1: Create a react application by typing the following command in the terminal:npx create-react-app currency-converter
Step 1: Create a react application by typing the following command in the terminal:
npx create-react-app currency-converter
Step 2: Now, go to the project folder i.e currency-converter by running the following command:cd currency-converter
Step 2: Now, go to the project folder i.e currency-converter by running the following command:
cd currency-converter
Step 3: Let’s install some npm packages required for this project:npm install axiosnpm install react-dropdownnpm install react-icons
Step 3: Let’s install some npm packages required for this project:
npm install axios
npm install react-dropdown
npm install react-icons
Project Structure: It will look like this.
Example: Here App.js is the only default component of our app that contains all the logic. We will be using a free opensource (no auth requires) API called ‘currency-api’ to fetch a list of all the available currencies in the world and also their conversion rates. We are using the react-dropdown npm package to list all the available currencies and also we react-icons npm package for the switch button.
Now write down the following code in the App.js file.
App.js
import { useEffect, useState } from 'react';import Axios from 'axios';import Dropdown from 'react-dropdown';import { HiSwitchHorizontal } from 'react-icons/hi';import 'react-dropdown/style.css';import './App.css'; function App() { // Initializing all the state variables const [info, setInfo] = useState([]); const [input, setInput] = useState(0); const [from, setFrom] = useState("usd"); const [to, setTo] = useState("inr"); const [options, setOptions] = useState([]); const [output, setOutput] = useState(0); // Calling the api whenever the dependency changes useEffect(() => { Axios.get(`https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/${from}.json`) .then((res) => { setInfo(res.data[from]); }) }, [from]); // Calling the convert function whenever // a user switches the currency useEffect(() => { setOptions(Object.keys(info)); convert(); }, [info]) // Function to convert the currency function convert() { var rate = info[to]; setOutput(input * rate); } // Function to switch between two currency function flip() { var temp = from; setFrom(to); setTo(temp); } return ( <div className="App"> <div className="heading"> <h1>Currency converter</h1> </div> <div className="container"> <div className="left"> <h3>Amount</h3> <input type="text" placeholder="Enter the amount" onChange={(e) => setInput(e.target.value)} /> </div> <div className="middle"> <h3>From</h3> <Dropdown options={options} onChange={(e) => { setFrom(e.value) }} value={from} placeholder="From" /> </div> <div className="switch"> <HiSwitchHorizontal size="30px" onClick={() => { flip()}}/> </div> <div className="right"> <h3>To</h3> <Dropdown options={options} onChange={(e) => {setTo(e.value)}} value={to} placeholder="To" /> </div> </div> <div className="result"> <button onClick={()=>{convert()}}>Convert</button> <h2>Converted Amount:</h2> <p>{input+" "+from+" = "+output.toFixed(2) + " " + to}</p> </div> </div> );} export default App;
Now let’s edit the file named App.css
App.css
@import url('https://fonts.googleapis.com/css2?family=Pacifico&display=swap'); .App { height: 100vh; width: 100%; display: flex; align-items: center; flex-direction: column; padding-top: 120px; background-image: linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%);}.heading{ font-family: 'Pacifico', cursive; font-size: 35px;}.container{ height: 300px; width: 800px; display: flex; justify-content: space-around; align-items: center;}input{ padding-left: 5px; font-size: 20px; height: 36px;}.middle,.right{ width: 120px;}.switch{ padding: 5px; margin-top: 25px; background-color: rgb(226, 252, 184); border-radius: 50%; cursor: pointer;}.result{ box-sizing: border-box; width: 800px; padding-left: 30px;}button{ width: 100px; height: 30px; font-weight: bold; font-size: 20px; border: 2px solid forestgreen; background-color: rgb(226, 252, 184); cursor: pointer;}p,h3, button, .switch{ color: forestgreen;}p{ font-size: 30px;}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
React-Questions
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Aug, 2021"
},
{
"code": null,
"e": 153,
"s": 54,
"text": "In this article, we will be building a very simple currency converter app with the help of an API."
},
{
"code": null,
"e": 609,
"s": 153,
"text": "Our app contains three sections, one for taking the user input and store it inside a state variable, a menu where users can change the units of conversion, and finally a display section where we display the final results. At first, we call the API and store the required conversion rates inside a state variable and later we perform some operations that convert the currencies. Our app contains a flip switch where users can switch currencies at any time."
},
{
"code": null,
"e": 665,
"s": 609,
"text": "Prerequisites: The pre-requisites for this project are:"
},
{
"code": null,
"e": 671,
"s": 665,
"text": "React"
},
{
"code": null,
"e": 693,
"s": 671,
"text": "Functional Components"
},
{
"code": null,
"e": 705,
"s": 693,
"text": "React Hooks"
},
{
"code": null,
"e": 723,
"s": 705,
"text": "React Axios & API"
},
{
"code": null,
"e": 738,
"s": 723,
"text": "Javascript ES6"
},
{
"code": null,
"e": 801,
"s": 738,
"text": "Creating a React application and installing some npm packages:"
},
{
"code": null,
"e": 924,
"s": 801,
"text": "Step 1: Create a react application by typing the following command in the terminal:npx create-react-app currency-converter"
},
{
"code": null,
"e": 1008,
"s": 924,
"text": "Step 1: Create a react application by typing the following command in the terminal:"
},
{
"code": null,
"e": 1048,
"s": 1008,
"text": "npx create-react-app currency-converter"
},
{
"code": null,
"e": 1164,
"s": 1048,
"text": "Step 2: Now, go to the project folder i.e currency-converter by running the following command:cd currency-converter"
},
{
"code": null,
"e": 1259,
"s": 1164,
"text": "Step 2: Now, go to the project folder i.e currency-converter by running the following command:"
},
{
"code": null,
"e": 1281,
"s": 1259,
"text": "cd currency-converter"
},
{
"code": null,
"e": 1414,
"s": 1281,
"text": "Step 3: Let’s install some npm packages required for this project:npm install axiosnpm install react-dropdownnpm install react-icons"
},
{
"code": null,
"e": 1481,
"s": 1414,
"text": "Step 3: Let’s install some npm packages required for this project:"
},
{
"code": null,
"e": 1499,
"s": 1481,
"text": "npm install axios"
},
{
"code": null,
"e": 1526,
"s": 1499,
"text": "npm install react-dropdown"
},
{
"code": null,
"e": 1550,
"s": 1526,
"text": "npm install react-icons"
},
{
"code": null,
"e": 1593,
"s": 1550,
"text": "Project Structure: It will look like this."
},
{
"code": null,
"e": 1999,
"s": 1593,
"text": "Example: Here App.js is the only default component of our app that contains all the logic. We will be using a free opensource (no auth requires) API called ‘currency-api’ to fetch a list of all the available currencies in the world and also their conversion rates. We are using the react-dropdown npm package to list all the available currencies and also we react-icons npm package for the switch button. "
},
{
"code": null,
"e": 2054,
"s": 1999,
"text": "Now write down the following code in the App.js file. "
},
{
"code": null,
"e": 2061,
"s": 2054,
"text": "App.js"
},
{
"code": "import { useEffect, useState } from 'react';import Axios from 'axios';import Dropdown from 'react-dropdown';import { HiSwitchHorizontal } from 'react-icons/hi';import 'react-dropdown/style.css';import './App.css'; function App() { // Initializing all the state variables const [info, setInfo] = useState([]); const [input, setInput] = useState(0); const [from, setFrom] = useState(\"usd\"); const [to, setTo] = useState(\"inr\"); const [options, setOptions] = useState([]); const [output, setOutput] = useState(0); // Calling the api whenever the dependency changes useEffect(() => { Axios.get(`https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/${from}.json`) .then((res) => { setInfo(res.data[from]); }) }, [from]); // Calling the convert function whenever // a user switches the currency useEffect(() => { setOptions(Object.keys(info)); convert(); }, [info]) // Function to convert the currency function convert() { var rate = info[to]; setOutput(input * rate); } // Function to switch between two currency function flip() { var temp = from; setFrom(to); setTo(temp); } return ( <div className=\"App\"> <div className=\"heading\"> <h1>Currency converter</h1> </div> <div className=\"container\"> <div className=\"left\"> <h3>Amount</h3> <input type=\"text\" placeholder=\"Enter the amount\" onChange={(e) => setInput(e.target.value)} /> </div> <div className=\"middle\"> <h3>From</h3> <Dropdown options={options} onChange={(e) => { setFrom(e.value) }} value={from} placeholder=\"From\" /> </div> <div className=\"switch\"> <HiSwitchHorizontal size=\"30px\" onClick={() => { flip()}}/> </div> <div className=\"right\"> <h3>To</h3> <Dropdown options={options} onChange={(e) => {setTo(e.value)}} value={to} placeholder=\"To\" /> </div> </div> <div className=\"result\"> <button onClick={()=>{convert()}}>Convert</button> <h2>Converted Amount:</h2> <p>{input+\" \"+from+\" = \"+output.toFixed(2) + \" \" + to}</p> </div> </div> );} export default App;",
"e": 4365,
"s": 2061,
"text": null
},
{
"code": null,
"e": 4403,
"s": 4365,
"text": "Now let’s edit the file named App.css"
},
{
"code": null,
"e": 4411,
"s": 4403,
"text": "App.css"
},
{
"code": "@import url('https://fonts.googleapis.com/css2?family=Pacifico&display=swap'); .App { height: 100vh; width: 100%; display: flex; align-items: center; flex-direction: column; padding-top: 120px; background-image: linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%);}.heading{ font-family: 'Pacifico', cursive; font-size: 35px;}.container{ height: 300px; width: 800px; display: flex; justify-content: space-around; align-items: center;}input{ padding-left: 5px; font-size: 20px; height: 36px;}.middle,.right{ width: 120px;}.switch{ padding: 5px; margin-top: 25px; background-color: rgb(226, 252, 184); border-radius: 50%; cursor: pointer;}.result{ box-sizing: border-box; width: 800px; padding-left: 30px;}button{ width: 100px; height: 30px; font-weight: bold; font-size: 20px; border: 2px solid forestgreen; background-color: rgb(226, 252, 184); cursor: pointer;}p,h3, button, .switch{ color: forestgreen;}p{ font-size: 30px;}",
"e": 5371,
"s": 4411,
"text": null
},
{
"code": null,
"e": 5484,
"s": 5371,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 5494,
"s": 5484,
"text": "npm start"
},
{
"code": null,
"e": 5593,
"s": 5494,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 5609,
"s": 5593,
"text": "React-Questions"
},
{
"code": null,
"e": 5620,
"s": 5609,
"text": "JavaScript"
},
{
"code": null,
"e": 5628,
"s": 5620,
"text": "ReactJS"
},
{
"code": null,
"e": 5645,
"s": 5628,
"text": "Web Technologies"
}
] |
Basics of File Handling in C#
|
09 Sep, 2019
Generally, the file is used to store the data. The term File Handling refers to the various operations like creating the file, reading from the file, writing to the file, appending the file, etc. There are two basic operation which is mostly used in file handling is reading and writing of the file. The file becomes stream when we open the file for writing and reading. A stream is a sequence of bytes which is used for communication. Two stream can be formed from file one is input stream which is used to read the file and another is output stream is used to write in the file. In C#, System.IO namespace contains classes which handle input and output streams and provide information about file and directory structure.
File-Handling-Class-Hierarchy
Here we are going to discuss about two classes which are useful for writing in and reading from the text file.
The StreamWriter class implements TextWriter for writing character to stream in a particular format. The class contains the following method which are mostly used.
Example:
// C# program to write user input // to a file using StreamWriter Classusing System;using System.IO; namespace GeeksforGeeks { class GFG { class WriteToFile { public void Data() { // This will create a file named sample.txt // at the specified location StreamWriter sw = new StreamWriter("H://geeksforgeeks.txt"); // To write on the console screen Console.WriteLine("Enter the Text that you want to write on File"); // To read the input from the user string str = Console.ReadLine(); // To write a line in buffer sw.WriteLine(str); // To write in output stream sw.Flush(); // To close the stream sw.Close(); } } // Main Method static void Main(string[] args) { WriteToFile wr = new WriteToFile(); wr.Data(); Console.ReadKey(); }}}
Input:
Output: You will find the file at the specified location having the content:
The StreamReader class implements TextReader for reading character from the stream in a particular format. The class contains the following method which are mostly used.
Example:
// C# program to read from a file// using StreamReader Classusing System;using System.IO; namespace GeeksforGeeks { class GFG { class ReadFile { public void DataReading() { // Takinga a new input stream i.e. // geeksforgeeks.txt and opens it StreamReader sr = new StreamReader("H://geeksforgeeks.txt"); Console.WriteLine("Content of the File"); // This is use to specify from where // to start reading input stream sr.BaseStream.Seek(0, SeekOrigin.Begin); // To read line from input stream string str = sr.ReadLine(); // To read the whole file line by line while (str != null) { Console.WriteLine(str); str = sr.ReadLine(); } Console.ReadLine(); // to close the stream sr.Close(); } } // Main Method static void Main(string[] args) { ReadFile wr = new ReadFile(); wr.DataReading(); }}}
Output:
File Handling
C#
File Handling
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
C# | Delegates
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Class and Object
C# | Constructors
C# | Arrays
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Sep, 2019"
},
{
"code": null,
"e": 777,
"s": 54,
"text": "Generally, the file is used to store the data. The term File Handling refers to the various operations like creating the file, reading from the file, writing to the file, appending the file, etc. There are two basic operation which is mostly used in file handling is reading and writing of the file. The file becomes stream when we open the file for writing and reading. A stream is a sequence of bytes which is used for communication. Two stream can be formed from file one is input stream which is used to read the file and another is output stream is used to write in the file. In C#, System.IO namespace contains classes which handle input and output streams and provide information about file and directory structure."
},
{
"code": null,
"e": 807,
"s": 777,
"text": "File-Handling-Class-Hierarchy"
},
{
"code": null,
"e": 918,
"s": 807,
"text": "Here we are going to discuss about two classes which are useful for writing in and reading from the text file."
},
{
"code": null,
"e": 1082,
"s": 918,
"text": "The StreamWriter class implements TextWriter for writing character to stream in a particular format. The class contains the following method which are mostly used."
},
{
"code": null,
"e": 1091,
"s": 1082,
"text": "Example:"
},
{
"code": "// C# program to write user input // to a file using StreamWriter Classusing System;using System.IO; namespace GeeksforGeeks { class GFG { class WriteToFile { public void Data() { // This will create a file named sample.txt // at the specified location StreamWriter sw = new StreamWriter(\"H://geeksforgeeks.txt\"); // To write on the console screen Console.WriteLine(\"Enter the Text that you want to write on File\"); // To read the input from the user string str = Console.ReadLine(); // To write a line in buffer sw.WriteLine(str); // To write in output stream sw.Flush(); // To close the stream sw.Close(); } } // Main Method static void Main(string[] args) { WriteToFile wr = new WriteToFile(); wr.Data(); Console.ReadKey(); }}}",
"e": 2129,
"s": 1091,
"text": null
},
{
"code": null,
"e": 2136,
"s": 2129,
"text": "Input:"
},
{
"code": null,
"e": 2213,
"s": 2136,
"text": "Output: You will find the file at the specified location having the content:"
},
{
"code": null,
"e": 2383,
"s": 2213,
"text": "The StreamReader class implements TextReader for reading character from the stream in a particular format. The class contains the following method which are mostly used."
},
{
"code": null,
"e": 2392,
"s": 2383,
"text": "Example:"
},
{
"code": "// C# program to read from a file// using StreamReader Classusing System;using System.IO; namespace GeeksforGeeks { class GFG { class ReadFile { public void DataReading() { // Takinga a new input stream i.e. // geeksforgeeks.txt and opens it StreamReader sr = new StreamReader(\"H://geeksforgeeks.txt\"); Console.WriteLine(\"Content of the File\"); // This is use to specify from where // to start reading input stream sr.BaseStream.Seek(0, SeekOrigin.Begin); // To read line from input stream string str = sr.ReadLine(); // To read the whole file line by line while (str != null) { Console.WriteLine(str); str = sr.ReadLine(); } Console.ReadLine(); // to close the stream sr.Close(); } } // Main Method static void Main(string[] args) { ReadFile wr = new ReadFile(); wr.DataReading(); }}}",
"e": 3542,
"s": 2392,
"text": null
},
{
"code": null,
"e": 3550,
"s": 3542,
"text": "Output:"
},
{
"code": null,
"e": 3564,
"s": 3550,
"text": "File Handling"
},
{
"code": null,
"e": 3567,
"s": 3564,
"text": "C#"
},
{
"code": null,
"e": 3581,
"s": 3567,
"text": "File Handling"
},
{
"code": null,
"e": 3679,
"s": 3581,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3722,
"s": 3679,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 3753,
"s": 3722,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 3768,
"s": 3753,
"text": "C# | Delegates"
},
{
"code": null,
"e": 3817,
"s": 3768,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 3833,
"s": 3817,
"text": "C# | Data Types"
},
{
"code": null,
"e": 3856,
"s": 3833,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 3896,
"s": 3856,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 3918,
"s": 3896,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 3936,
"s": 3918,
"text": "C# | Constructors"
}
] |
File listFiles() method in Java with Examples
|
30 Jan, 2019
The listFiles() method is a part of File class.The function returns an array of Files denoting the files in a given abstract pathname if the path name is a directory else returns null. The function is an overloaded function. One of the function does not have any parameter, the second function takes FilenameFilter object as parameter, the third function takes FileFilter object as parameter
Function Signature:
public File[] listFiles()
public File[] listFiles(FilenameFilter f)
public File[] listFiles(FileFilter f)
Function Syntax:
file.listFiles()
file.listFiles(filter)
Parameters: The function is a overloaded function
One of the function does not have any parameter,
The second function takes FilenameFilter object as a parameter,
The third function takes FileFilter object as a parameter
Return value: The function returns a File array, or null value if the file object is a file.
Exception: This method throws Security Exception if the function is not allowed read access to the file
Below programs will illustrate the use of the listFiles() function
Example 1: We will try to find all the files and directories in a given directory
// Java program to demonstrate the// use of listFiles() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File("f:\\program"); // Get all the names of the files present // in the given directory File[] files = f.listFiles(); System.out.println("Files are:"); // Display the names of the files for (int i = 0; i < files.length; i++) { System.out.println(files[i].getName()); } } catch (Exception e) { System.err.println(e.getMessage()); } }}
Output:
Files are:
1232.txt
1245.txt
5671.txt
program1
Example 2: We will try to find all the files and directories in a given directory whose names start with “12”
// Java program to demonstrate the// use of listFiles() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File("f:\\program"); // Create a FilenameFilter FilenameFilter filter = new FilenameFilter() { public boolean accept(File f, String name) { return name.startsWith("12"); } }; // Get all the names of the files present // in the given directory // and whose names start with "12" File[] files = f.listFiles(filter); System.out.println("Files are:"); // Display the names of the files for (int i = 0; i < files.length; i++) { System.out.println(files[i].getName()); } } catch (Exception e) { System.err.println(e.getMessage()); } }}
Output:
Files are:
1232.txt
1245.txt
Example 3: We will try to find all the files and directories in a given directory which are text files
// Java program to demonstrate the// use of listFiles() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File("f:\\program"); // Create a FileFilter FileFilter filter = new FileFilter() { public boolean accept(File f) { return f.getName().endsWith("txt"); } }; // Get all the names of the files present // in the given directory // which are text files File[] files = f.listFiles(filter); System.out.println("Files are:"); // Display the names of the files for (int i = 0; i < files.length; i++) { System.out.println(files[i].getName()); } } catch (Exception e) { System.err.println(e.getMessage()); } }}
Output:
Files are:
1232.txt
1245.txt
5671.txt
The programs might not run in an online IDE. please use an offline IDE and set the Parent file of the file
Java-File Class
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jan, 2019"
},
{
"code": null,
"e": 420,
"s": 28,
"text": "The listFiles() method is a part of File class.The function returns an array of Files denoting the files in a given abstract pathname if the path name is a directory else returns null. The function is an overloaded function. One of the function does not have any parameter, the second function takes FilenameFilter object as parameter, the third function takes FileFilter object as parameter"
},
{
"code": null,
"e": 440,
"s": 420,
"text": "Function Signature:"
},
{
"code": null,
"e": 546,
"s": 440,
"text": "public File[] listFiles()\npublic File[] listFiles(FilenameFilter f)\npublic File[] listFiles(FileFilter f)"
},
{
"code": null,
"e": 563,
"s": 546,
"text": "Function Syntax:"
},
{
"code": null,
"e": 603,
"s": 563,
"text": "file.listFiles()\nfile.listFiles(filter)"
},
{
"code": null,
"e": 653,
"s": 603,
"text": "Parameters: The function is a overloaded function"
},
{
"code": null,
"e": 702,
"s": 653,
"text": "One of the function does not have any parameter,"
},
{
"code": null,
"e": 766,
"s": 702,
"text": "The second function takes FilenameFilter object as a parameter,"
},
{
"code": null,
"e": 824,
"s": 766,
"text": "The third function takes FileFilter object as a parameter"
},
{
"code": null,
"e": 917,
"s": 824,
"text": "Return value: The function returns a File array, or null value if the file object is a file."
},
{
"code": null,
"e": 1021,
"s": 917,
"text": "Exception: This method throws Security Exception if the function is not allowed read access to the file"
},
{
"code": null,
"e": 1088,
"s": 1021,
"text": "Below programs will illustrate the use of the listFiles() function"
},
{
"code": null,
"e": 1170,
"s": 1088,
"text": "Example 1: We will try to find all the files and directories in a given directory"
},
{
"code": "// Java program to demonstrate the// use of listFiles() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File(\"f:\\\\program\"); // Get all the names of the files present // in the given directory File[] files = f.listFiles(); System.out.println(\"Files are:\"); // Display the names of the files for (int i = 0; i < files.length; i++) { System.out.println(files[i].getName()); } } catch (Exception e) { System.err.println(e.getMessage()); } }}",
"e": 1917,
"s": 1170,
"text": null
},
{
"code": null,
"e": 1925,
"s": 1917,
"text": "Output:"
},
{
"code": null,
"e": 1973,
"s": 1925,
"text": "Files are:\n1232.txt\n1245.txt\n5671.txt\nprogram1\n"
},
{
"code": null,
"e": 2083,
"s": 1973,
"text": "Example 2: We will try to find all the files and directories in a given directory whose names start with “12”"
},
{
"code": "// Java program to demonstrate the// use of listFiles() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File(\"f:\\\\program\"); // Create a FilenameFilter FilenameFilter filter = new FilenameFilter() { public boolean accept(File f, String name) { return name.startsWith(\"12\"); } }; // Get all the names of the files present // in the given directory // and whose names start with \"12\" File[] files = f.listFiles(filter); System.out.println(\"Files are:\"); // Display the names of the files for (int i = 0; i < files.length; i++) { System.out.println(files[i].getName()); } } catch (Exception e) { System.err.println(e.getMessage()); } }}",
"e": 3137,
"s": 2083,
"text": null
},
{
"code": null,
"e": 3145,
"s": 3137,
"text": "Output:"
},
{
"code": null,
"e": 3175,
"s": 3145,
"text": "Files are:\n1232.txt\n1245.txt\n"
},
{
"code": null,
"e": 3278,
"s": 3175,
"text": "Example 3: We will try to find all the files and directories in a given directory which are text files"
},
{
"code": "// Java program to demonstrate the// use of listFiles() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File(\"f:\\\\program\"); // Create a FileFilter FileFilter filter = new FileFilter() { public boolean accept(File f) { return f.getName().endsWith(\"txt\"); } }; // Get all the names of the files present // in the given directory // which are text files File[] files = f.listFiles(filter); System.out.println(\"Files are:\"); // Display the names of the files for (int i = 0; i < files.length; i++) { System.out.println(files[i].getName()); } } catch (Exception e) { System.err.println(e.getMessage()); } }}",
"e": 4302,
"s": 3278,
"text": null
},
{
"code": null,
"e": 4310,
"s": 4302,
"text": "Output:"
},
{
"code": null,
"e": 4349,
"s": 4310,
"text": "Files are:\n1232.txt\n1245.txt\n5671.txt\n"
},
{
"code": null,
"e": 4456,
"s": 4349,
"text": "The programs might not run in an online IDE. please use an offline IDE and set the Parent file of the file"
},
{
"code": null,
"e": 4472,
"s": 4456,
"text": "Java-File Class"
},
{
"code": null,
"e": 4487,
"s": 4472,
"text": "Java-Functions"
},
{
"code": null,
"e": 4503,
"s": 4487,
"text": "Java-IO package"
},
{
"code": null,
"e": 4508,
"s": 4503,
"text": "Java"
},
{
"code": null,
"e": 4513,
"s": 4508,
"text": "Java"
}
] |
How to Plot a Logistic Regression Curve in R?
|
27 Jan, 2022
In this article, we will learn how to plot a Logistic Regression Curve in the R programming Language.
Logistic regression is basically a supervised classification algorithm. That helps us in creating a differentiating curve that separates two classes of variables. To Plot the Logistic Regression curve in the R Language, we use the following methods.
Dataset used: Sample4
To plot the logistic regression curve in base R, we first fit the variables in a logistic regression model by using the glm() function. The glm() function is used to fit generalized linear models, specified by giving a symbolic description of the linear predictor. Then we use that model to create a data frame where the y-axis variable is changed to its predicted value derived by using the predict() function with the above-created model. Then we plot a scatter plot of original points by using the plot() function and predicted values by using the lines() function.
Syntax:
logistic_model <- glm( formula, family, dataframe )
plot( original_dataframe )
lines( predicted_dataframe )
Parameter:
formula: determines the symbolic description of the model to be fitted.
family: determines the description of the error distribution and link function to be used in the model.
dataframe: determines the data frame to be used for fitting purpose
Example: Plot logistic regression
R
# load dataframedf <- read.csv("Sample4.csv") # create logistic regression modellogistic_model <- glm(var1 ~ var2, data=df, family=binomial) #Data frame with hp in ascending orderPredicted_data <- data.frame(var2=seq( min(df$var2), max(df$var2),len=500)) # Fill predicted values using regression modelPredicted_data$var1 = predict( logistic_model, Predicted_data, type="response") # Plot Predicted data and original data pointsplot(var1 ~ var2, data=df)lines(var1 ~ var2, Predicted_data, lwd=2, col="green")
Output:
To plot the logistic curve using the ggplot2 package library, we use the stat_smooth() function. The argument method of function with the value “glm” plots the logistic regression curve on top of a ggplot2 plot. So, we first plot the desired scatter plot of original data points and then overlap it with a regression curve using the stat_smooth() function.
Syntax:
plot + stat_smooth( method=”glm”, se, method.args )
Parameter:
se: determines a boolean that tells whether to display confidence interval around smooth.
method.args: determines the method function for logistic curve.
Example: Plot logistic regression
R
# load library ggplot2library(ggplot2) # load data from CSVdf <- read.csv("Sample4.csv") # Plot Predicted data and original data pointsggplot(df, aes(x=var2, y=var1)) + geom_point() + stat_smooth(method="glm", color="green", se=FALSE, method.args = list(family=binomial))
Output:
sweetyty
sumitgumber28
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 130,
"s": 28,
"text": "In this article, we will learn how to plot a Logistic Regression Curve in the R programming Language."
},
{
"code": null,
"e": 380,
"s": 130,
"text": "Logistic regression is basically a supervised classification algorithm. That helps us in creating a differentiating curve that separates two classes of variables. To Plot the Logistic Regression curve in the R Language, we use the following methods."
},
{
"code": null,
"e": 402,
"s": 380,
"text": "Dataset used: Sample4"
},
{
"code": null,
"e": 971,
"s": 402,
"text": "To plot the logistic regression curve in base R, we first fit the variables in a logistic regression model by using the glm() function. The glm() function is used to fit generalized linear models, specified by giving a symbolic description of the linear predictor. Then we use that model to create a data frame where the y-axis variable is changed to its predicted value derived by using the predict() function with the above-created model. Then we plot a scatter plot of original points by using the plot() function and predicted values by using the lines() function."
},
{
"code": null,
"e": 979,
"s": 971,
"text": "Syntax:"
},
{
"code": null,
"e": 1031,
"s": 979,
"text": "logistic_model <- glm( formula, family, dataframe )"
},
{
"code": null,
"e": 1058,
"s": 1031,
"text": "plot( original_dataframe )"
},
{
"code": null,
"e": 1087,
"s": 1058,
"text": "lines( predicted_dataframe )"
},
{
"code": null,
"e": 1098,
"s": 1087,
"text": "Parameter:"
},
{
"code": null,
"e": 1170,
"s": 1098,
"text": "formula: determines the symbolic description of the model to be fitted."
},
{
"code": null,
"e": 1274,
"s": 1170,
"text": "family: determines the description of the error distribution and link function to be used in the model."
},
{
"code": null,
"e": 1342,
"s": 1274,
"text": "dataframe: determines the data frame to be used for fitting purpose"
},
{
"code": null,
"e": 1376,
"s": 1342,
"text": "Example: Plot logistic regression"
},
{
"code": null,
"e": 1378,
"s": 1376,
"text": "R"
},
{
"code": "# load dataframedf <- read.csv(\"Sample4.csv\") # create logistic regression modellogistic_model <- glm(var1 ~ var2, data=df, family=binomial) #Data frame with hp in ascending orderPredicted_data <- data.frame(var2=seq( min(df$var2), max(df$var2),len=500)) # Fill predicted values using regression modelPredicted_data$var1 = predict( logistic_model, Predicted_data, type=\"response\") # Plot Predicted data and original data pointsplot(var1 ~ var2, data=df)lines(var1 ~ var2, Predicted_data, lwd=2, col=\"green\")",
"e": 1888,
"s": 1378,
"text": null
},
{
"code": null,
"e": 1896,
"s": 1888,
"text": "Output:"
},
{
"code": null,
"e": 2253,
"s": 1896,
"text": "To plot the logistic curve using the ggplot2 package library, we use the stat_smooth() function. The argument method of function with the value “glm” plots the logistic regression curve on top of a ggplot2 plot. So, we first plot the desired scatter plot of original data points and then overlap it with a regression curve using the stat_smooth() function."
},
{
"code": null,
"e": 2261,
"s": 2253,
"text": "Syntax:"
},
{
"code": null,
"e": 2313,
"s": 2261,
"text": "plot + stat_smooth( method=”glm”, se, method.args )"
},
{
"code": null,
"e": 2324,
"s": 2313,
"text": "Parameter:"
},
{
"code": null,
"e": 2414,
"s": 2324,
"text": "se: determines a boolean that tells whether to display confidence interval around smooth."
},
{
"code": null,
"e": 2478,
"s": 2414,
"text": "method.args: determines the method function for logistic curve."
},
{
"code": null,
"e": 2512,
"s": 2478,
"text": "Example: Plot logistic regression"
},
{
"code": null,
"e": 2514,
"s": 2512,
"text": "R"
},
{
"code": "# load library ggplot2library(ggplot2) # load data from CSVdf <- read.csv(\"Sample4.csv\") # Plot Predicted data and original data pointsggplot(df, aes(x=var2, y=var1)) + geom_point() + stat_smooth(method=\"glm\", color=\"green\", se=FALSE, method.args = list(family=binomial))",
"e": 2806,
"s": 2514,
"text": null
},
{
"code": null,
"e": 2814,
"s": 2806,
"text": "Output:"
},
{
"code": null,
"e": 2823,
"s": 2814,
"text": "sweetyty"
},
{
"code": null,
"e": 2837,
"s": 2823,
"text": "sumitgumber28"
},
{
"code": null,
"e": 2844,
"s": 2837,
"text": "Picked"
},
{
"code": null,
"e": 2853,
"s": 2844,
"text": "R-Charts"
},
{
"code": null,
"e": 2862,
"s": 2853,
"text": "R-Graphs"
},
{
"code": null,
"e": 2870,
"s": 2862,
"text": "R-plots"
},
{
"code": null,
"e": 2881,
"s": 2870,
"text": "R Language"
}
] |
numpy.allclose() in Python
|
28 Dec, 2018
numpy.allclose() function is used to find if two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers. The relative difference (rtol * abs(arr2)) and the absolute difference atol are added together to compare against the absolute difference between arr1 and arr2. If either array contains one or more NaNs, False is returned. Infs are treated as equal if they are in the same place and of the same sign in both arrays.
If the following equation is element-wise True, then allclose returns True.absolute(arr1 - arr2) <= (atol + rtol * absolute(arr2))As, The above equation is not symmetric in arr1 and arr2, So, allclose(arr1, arr2) might be different from allclose(arr2, arr1) in some rare cases.
Syntax : numpy.allclose(arr1, arr2, rtol, atol, equal_nan=False)
Parameters :arr1 : [array_like] Input 1st array.arr2 : [array_like] Input 2nd array.rtol : [float] The relative tolerance parameter.atol : [float] The absolute tolerance parameter.equal_nan : [bool] Whether to compare NaN’s as equal. If True, NaN’s in arr1 will be considered equal to NaN’s in arr2 in the output array.
Return : [ bool] Returns True if the two arrays are equal within the given tolerance, otherwise it returns False.
Code #1 :
# Python program explaining# allclose() function import numpy as geek # input arraysin_arr1 = geek.array([5e5, 1e-7, 4.000004e6])print ("1st Input array : ", in_arr1) in_arr2 = geek.array([5.00001e5, 1e-7, 4e6])print ("2nd Input array : ", in_arr2) # setting the absolute and relative tolerancertol = 1e-05atol = 1e-08 res = geek.allclose(in_arr1, in_arr2, rtol, atol)print ("Are the two arrays are equal within the tolerance: \t", res)
1st Input array : [ 5.00000000e+05 1.00000000e-07 4.00000400e+06]
2nd Input array : [ 5.00001000e+05 1.00000000e-07 4.00000000e+06]
Are the two arrays are equal within the tolerance: True
Code #2 :
# Python program explaining# allclose() function import numpy as geek # input arraysin_arr1 = geek.array([5e5, 1e-7, 4.000004e6])print ("1st Input array : ", in_arr1) in_arr2 = geek.array([5.00001e5, 1e-7, 4e6])print ("2nd Input array : ", in_arr2) # setting the absolute and relative tolerancertol = 1e-06atol = 1e-09 res = geek.allclose(in_arr1, in_arr2, rtol, atol)print ("Are the two arrays are equal within the tolerance: \t", res)
1st Input array : [5000000.0, 1e-07, 40000004.0]
2nd Input array : [5000001.0, 1e-07, 40000000.0]
Are the two arrays are equal within the tolerance: True
Code #3 :
# Python program explaining# allclose() function import numpy as geek # input arraysin_arr1 = geek.array([5e5, 1e-7, geek.nan])print ("1st Input array : ", in_arr1) in_arr2 = geek.array([5e5, 1e-7, geek.nan])print ("2nd Input array : ", in_arr2) # setting the absolute and relative tolerancertol = 1e-06atol = 1e-09 res = geek.allclose(in_arr1, in_arr2, rtol, atol)print ("Are the two arrays are equal within the tolerance: \t", res)
1st Input array : [500000.0, 1e-07, nan]
2nd Input array : [500000.0, 1e-07, nan]
Are the two arrays are equal within the tolerance: False
Code #4 :
# Python program explaining# allclose() function import numpy as geek # input arraysin_arr1 = geek.array([5e5, 1e-7, geek.nan])print ("1st Input array : ", in_arr1) in_arr2 = geek.array([5e5, 1e-7, geek.nan])print ("2nd Input array : ", in_arr2) # setting the absolute and relative tolerancertol = 1e-06atol = 1e-09 res = geek.allclose(in_arr1, in_arr2, rtol, atol, equal_nan = True) print ("Are the two arrays are equal within the tolerance: \t", res)
1st Input array : [500000.0, 1e-07, nan]
2nd Input array : [500000.0, 1e-07, nan]
Are the two arrays are equal within the tolerance: True
Python numpy-Logic Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Dec, 2018"
},
{
"code": null,
"e": 508,
"s": 28,
"text": "numpy.allclose() function is used to find if two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers. The relative difference (rtol * abs(arr2)) and the absolute difference atol are added together to compare against the absolute difference between arr1 and arr2. If either array contains one or more NaNs, False is returned. Infs are treated as equal if they are in the same place and of the same sign in both arrays."
},
{
"code": null,
"e": 786,
"s": 508,
"text": "If the following equation is element-wise True, then allclose returns True.absolute(arr1 - arr2) <= (atol + rtol * absolute(arr2))As, The above equation is not symmetric in arr1 and arr2, So, allclose(arr1, arr2) might be different from allclose(arr2, arr1) in some rare cases."
},
{
"code": null,
"e": 851,
"s": 786,
"text": "Syntax : numpy.allclose(arr1, arr2, rtol, atol, equal_nan=False)"
},
{
"code": null,
"e": 1171,
"s": 851,
"text": "Parameters :arr1 : [array_like] Input 1st array.arr2 : [array_like] Input 2nd array.rtol : [float] The relative tolerance parameter.atol : [float] The absolute tolerance parameter.equal_nan : [bool] Whether to compare NaN’s as equal. If True, NaN’s in arr1 will be considered equal to NaN’s in arr2 in the output array."
},
{
"code": null,
"e": 1285,
"s": 1171,
"text": "Return : [ bool] Returns True if the two arrays are equal within the given tolerance, otherwise it returns False."
},
{
"code": null,
"e": 1295,
"s": 1285,
"text": "Code #1 :"
},
{
"code": "# Python program explaining# allclose() function import numpy as geek # input arraysin_arr1 = geek.array([5e5, 1e-7, 4.000004e6])print (\"1st Input array : \", in_arr1) in_arr2 = geek.array([5.00001e5, 1e-7, 4e6])print (\"2nd Input array : \", in_arr2) # setting the absolute and relative tolerancertol = 1e-05atol = 1e-08 res = geek.allclose(in_arr1, in_arr2, rtol, atol)print (\"Are the two arrays are equal within the tolerance: \\t\", res)",
"e": 1739,
"s": 1295,
"text": null
},
{
"code": null,
"e": 1945,
"s": 1739,
"text": "1st Input array : [ 5.00000000e+05 1.00000000e-07 4.00000400e+06]\n2nd Input array : [ 5.00001000e+05 1.00000000e-07 4.00000000e+06]\nAre the two arrays are equal within the tolerance: True\n"
},
{
"code": null,
"e": 1956,
"s": 1945,
"text": " Code #2 :"
},
{
"code": "# Python program explaining# allclose() function import numpy as geek # input arraysin_arr1 = geek.array([5e5, 1e-7, 4.000004e6])print (\"1st Input array : \", in_arr1) in_arr2 = geek.array([5.00001e5, 1e-7, 4e6])print (\"2nd Input array : \", in_arr2) # setting the absolute and relative tolerancertol = 1e-06atol = 1e-09 res = geek.allclose(in_arr1, in_arr2, rtol, atol)print (\"Are the two arrays are equal within the tolerance: \\t\", res)",
"e": 2401,
"s": 1956,
"text": null
},
{
"code": null,
"e": 2563,
"s": 2401,
"text": "1st Input array : [5000000.0, 1e-07, 40000004.0]\n2nd Input array : [5000001.0, 1e-07, 40000000.0]\nAre the two arrays are equal within the tolerance: True\n"
},
{
"code": null,
"e": 2574,
"s": 2563,
"text": " Code #3 :"
},
{
"code": "# Python program explaining# allclose() function import numpy as geek # input arraysin_arr1 = geek.array([5e5, 1e-7, geek.nan])print (\"1st Input array : \", in_arr1) in_arr2 = geek.array([5e5, 1e-7, geek.nan])print (\"2nd Input array : \", in_arr2) # setting the absolute and relative tolerancertol = 1e-06atol = 1e-09 res = geek.allclose(in_arr1, in_arr2, rtol, atol)print (\"Are the two arrays are equal within the tolerance: \\t\", res)",
"e": 3016,
"s": 2574,
"text": null
},
{
"code": null,
"e": 3163,
"s": 3016,
"text": "1st Input array : [500000.0, 1e-07, nan]\n2nd Input array : [500000.0, 1e-07, nan]\nAre the two arrays are equal within the tolerance: False\n"
},
{
"code": null,
"e": 3174,
"s": 3163,
"text": " Code #4 :"
},
{
"code": "# Python program explaining# allclose() function import numpy as geek # input arraysin_arr1 = geek.array([5e5, 1e-7, geek.nan])print (\"1st Input array : \", in_arr1) in_arr2 = geek.array([5e5, 1e-7, geek.nan])print (\"2nd Input array : \", in_arr2) # setting the absolute and relative tolerancertol = 1e-06atol = 1e-09 res = geek.allclose(in_arr1, in_arr2, rtol, atol, equal_nan = True) print (\"Are the two arrays are equal within the tolerance: \\t\", res)",
"e": 3668,
"s": 3174,
"text": null
},
{
"code": null,
"e": 3814,
"s": 3668,
"text": "1st Input array : [500000.0, 1e-07, nan]\n2nd Input array : [500000.0, 1e-07, nan]\nAre the two arrays are equal within the tolerance: True\n"
},
{
"code": null,
"e": 3843,
"s": 3814,
"text": "Python numpy-Logic Functions"
},
{
"code": null,
"e": 3850,
"s": 3843,
"text": "Python"
}
] |
Python-Tkinter Scrollbar
|
26 Mar, 2020
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.
Note: For more information, refer to Python GUI – tkinter
The scrollbar widget is used to scroll down the content. We can also create the horizontal scrollbars to the Entry widget.
Syntax:The syntax to use the Scrollbar widget is given below.
w = Scrollbar(master, options)
Parameters:
master: This parameter is used to represents the parent window.
options: There are many options which are available and they can be used as key-value pairs separated by commas.
Options:Following are commonly used Option can be used with this widget :-
activebackground: This option is used to represent the background color of the widget when it has the focus.
bg: This option is used to represent the background color of the widget.
bd: This option is used to represent the border width of the widget.
command: This option can be set to the procedure associated with the list which can be called each time when the scrollbar is moved.
cursor: In this option, the mouse pointer is changed to the cursor type set to this option which can be an arrow, dot, etc.
elementborderwidth: This option is used to represent the border width around the arrow heads and slider. The default value is -1.
Highlightbackground: This option is used to focus highlighcolor when the widget doesn’t have the focus.
highlighcolor: This option is used to focus highlighcolor when the widget has the focus.
highlightthickness: This option is used to represent the thickness of the focus highlight.
jump: This option is used to control the behavior of the scroll jump. If it set to 1, then the callback is called when the user releases the mouse button.
orient: This option can be set to HORIZONTAL or VERTICAL depending upon the orientation of the scrollbar.
repeatdelay: This option tells the duration up to which the button is to be pressed before the slider starts moving in that direction repeatedly. The default is 300 ms.
repeatinterval: The default value of the repeat interval is 100.
takefocus: You can tab the focus through a scrollbar widget
troughcolor: This option is used to represent the color of the trough.
width: This option is used to represent the width of the scrollbar.
Methods:Methods used in this widgets are as follows:
get(): This method is used to returns the two numbers a and b which represents the current position of the scrollbar.
set(first, last): This method is used to connect the scrollbar to the other widget w. The yscrollcommand or xscrollcommand of the other widget to this method.
Example:
from tkinter import * root = Tk()root.geometry("150x200") w = Label(root, text ='GeeksForGeeks', font = "50") w.pack() scroll_bar = Scrollbar(root) scroll_bar.pack( side = RIGHT, fill = Y ) mylist = Listbox(root, yscrollcommand = scroll_bar.set ) for line in range(1, 26): mylist.insert(END, "Geeks " + str(line)) mylist.pack( side = LEFT, fill = BOTH ) scroll_bar.config( command = mylist.yview ) root.mainloop()
Output:
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 406,
"s": 54,
"text": "Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task."
},
{
"code": null,
"e": 464,
"s": 406,
"text": "Note: For more information, refer to Python GUI – tkinter"
},
{
"code": null,
"e": 587,
"s": 464,
"text": "The scrollbar widget is used to scroll down the content. We can also create the horizontal scrollbars to the Entry widget."
},
{
"code": null,
"e": 649,
"s": 587,
"text": "Syntax:The syntax to use the Scrollbar widget is given below."
},
{
"code": null,
"e": 681,
"s": 649,
"text": "w = Scrollbar(master, options) "
},
{
"code": null,
"e": 693,
"s": 681,
"text": "Parameters:"
},
{
"code": null,
"e": 757,
"s": 693,
"text": "master: This parameter is used to represents the parent window."
},
{
"code": null,
"e": 870,
"s": 757,
"text": "options: There are many options which are available and they can be used as key-value pairs separated by commas."
},
{
"code": null,
"e": 945,
"s": 870,
"text": "Options:Following are commonly used Option can be used with this widget :-"
},
{
"code": null,
"e": 1054,
"s": 945,
"text": "activebackground: This option is used to represent the background color of the widget when it has the focus."
},
{
"code": null,
"e": 1127,
"s": 1054,
"text": "bg: This option is used to represent the background color of the widget."
},
{
"code": null,
"e": 1196,
"s": 1127,
"text": "bd: This option is used to represent the border width of the widget."
},
{
"code": null,
"e": 1329,
"s": 1196,
"text": "command: This option can be set to the procedure associated with the list which can be called each time when the scrollbar is moved."
},
{
"code": null,
"e": 1453,
"s": 1329,
"text": "cursor: In this option, the mouse pointer is changed to the cursor type set to this option which can be an arrow, dot, etc."
},
{
"code": null,
"e": 1583,
"s": 1453,
"text": "elementborderwidth: This option is used to represent the border width around the arrow heads and slider. The default value is -1."
},
{
"code": null,
"e": 1687,
"s": 1583,
"text": "Highlightbackground: This option is used to focus highlighcolor when the widget doesn’t have the focus."
},
{
"code": null,
"e": 1776,
"s": 1687,
"text": "highlighcolor: This option is used to focus highlighcolor when the widget has the focus."
},
{
"code": null,
"e": 1867,
"s": 1776,
"text": "highlightthickness: This option is used to represent the thickness of the focus highlight."
},
{
"code": null,
"e": 2022,
"s": 1867,
"text": "jump: This option is used to control the behavior of the scroll jump. If it set to 1, then the callback is called when the user releases the mouse button."
},
{
"code": null,
"e": 2128,
"s": 2022,
"text": "orient: This option can be set to HORIZONTAL or VERTICAL depending upon the orientation of the scrollbar."
},
{
"code": null,
"e": 2297,
"s": 2128,
"text": "repeatdelay: This option tells the duration up to which the button is to be pressed before the slider starts moving in that direction repeatedly. The default is 300 ms."
},
{
"code": null,
"e": 2362,
"s": 2297,
"text": "repeatinterval: The default value of the repeat interval is 100."
},
{
"code": null,
"e": 2422,
"s": 2362,
"text": "takefocus: You can tab the focus through a scrollbar widget"
},
{
"code": null,
"e": 2493,
"s": 2422,
"text": "troughcolor: This option is used to represent the color of the trough."
},
{
"code": null,
"e": 2561,
"s": 2493,
"text": "width: This option is used to represent the width of the scrollbar."
},
{
"code": null,
"e": 2614,
"s": 2561,
"text": "Methods:Methods used in this widgets are as follows:"
},
{
"code": null,
"e": 2732,
"s": 2614,
"text": "get(): This method is used to returns the two numbers a and b which represents the current position of the scrollbar."
},
{
"code": null,
"e": 2891,
"s": 2732,
"text": "set(first, last): This method is used to connect the scrollbar to the other widget w. The yscrollcommand or xscrollcommand of the other widget to this method."
},
{
"code": null,
"e": 2900,
"s": 2891,
"text": "Example:"
},
{
"code": "from tkinter import * root = Tk()root.geometry(\"150x200\") w = Label(root, text ='GeeksForGeeks', font = \"50\") w.pack() scroll_bar = Scrollbar(root) scroll_bar.pack( side = RIGHT, fill = Y ) mylist = Listbox(root, yscrollcommand = scroll_bar.set ) for line in range(1, 26): mylist.insert(END, \"Geeks \" + str(line)) mylist.pack( side = LEFT, fill = BOTH ) scroll_bar.config( command = mylist.yview ) root.mainloop()",
"e": 3374,
"s": 2900,
"text": null
},
{
"code": null,
"e": 3382,
"s": 3374,
"text": "Output:"
},
{
"code": null,
"e": 3397,
"s": 3382,
"text": "Python-tkinter"
},
{
"code": null,
"e": 3404,
"s": 3397,
"text": "Python"
}
] |
Merge two Pandas dataframes by matched ID number
|
05 Apr, 2021
In this article, we will see how two data frames can be merged based on matched ID numbers.
Approach
Create a first data frame
Create a second data frame
Select Column to be matched
Merge using the merge function
Syntax : DataFrame.merge(parameters)
Display result
Given below are implementations to produce a required result with the use of the required parameter with an appropriate value.
Example:
Python3
# import pandas as pdimport pandas as pd # creating dataframes as df1 and df2df1 = pd.DataFrame({'ID': [1, 2, 3, 5, 7, 8], 'Name': ['Sam', 'John', 'Bridge', 'Edge', 'Joe', 'Hope']}) df2 = pd.DataFrame({'ID': [1, 2, 4, 5, 6, 8, 9], 'Marks': [67, 92, 75, 83, 69, 56, 81]}) # merging df1 and df2 by ID# i.e. the rows with common ID's get# merged i.e. {1,2,5,8}df = pd.merge(df1, df2, on="ID")print(df)
Output :
Merged Dataframe
Merging two Dataframes with the ID column, with all the ID’s of the left Dataframe i.e. first parameter of the merge function. The ID’s which are not present in df2 gets a NaN value for the columns of that row.
Example 2 :
Python3
# import pandas as pdimport pandas as pd # creating dataframes as df1 and df2df1 = pd.DataFrame({'ID': [1, 2, 3, 5, 7, 8], 'Name': ['Sam', 'John', 'Bridge', 'Edge', 'Joe', 'Hope']}) df2 = pd.DataFrame({'ID': [1, 2, 4, 5, 6, 8, 9], 'Marks': [67, 92, 75, 83, 69, 56, 81]}) # merging df1 and df2 by ID# i.e. the rows with common ID's get merged# with all the ID's of left dataframe i.e. df1# and NaN for columns of df2 where ID do not matchdf = pd.merge(df1, df2, on="ID", how="left")print(df)
Output :
Merged Dataframe
Merging two Dataframes with the ID column, with all the ID’s of the right Dataframe i.e. second parameter of the merge function. The ID’s which do not match from df1 gets a NaN value for that column.
Example 3 :
Python3
# import pandas as pdimport pandas as pd # creating dataframes as df1 and df2df1 = pd.DataFrame({'ID': [1, 2, 3, 5, 7, 8], 'Name': ['Sam', 'John', 'Bridge', 'Edge', 'Joe', 'Hope']}) df2 = pd.DataFrame({'ID': [1, 2, 4, 5, 6, 8, 9], 'Marks': [67, 92, 75, 83, 69, 56, 81]}) # merging df1 and df2 by ID# i.e. the rows with common ID's get merged# with all the ID's of right dataframe i.e. df2# and NaN values for df1 columns where ID do not matchdf = pd.merge(df1, df2, on="ID", how="right")print(df)
Output :
Merged Dataframe
Merging two Dataframes with the ID column, with all that match in both the dataframes.
Example 4 :
Python3
# import pandas as pdimport pandas as pd # creating dataframes as df1 and df2df1 = pd.DataFrame({'ID': [1, 2, 3, 5, 7, 8], 'Name': ['Sam', 'John', 'Bridge', 'Edge', 'Joe', 'Hope']}) df2 = pd.DataFrame({'ID': [1, 2, 4, 5, 6, 8, 9], 'Marks': [67, 92, 75, 83, 69, 56, 81]}) # merging df1 and df2 by ID# i.e. the rows with common ID's get merged# with all the ID's that match in both the Dataframedf = pd.merge(df1, df2, on="ID", how="inner")print(df)
Output :
Merged Dataframe
Merging two Dataframes with the ID column, with all the ID’s of both the dataframes and NaN value for the columns where the ID is not found in both the dataframes.
Example 5 :
Python3
# import pandas as pdimport pandas as pd # creating dataframes as df1 and df2df1 = pd.DataFrame({'ID': [1, 2, 3, 5, 7, 8], 'Name': ['Sam', 'John', 'Bridge', 'Edge', 'Joe', 'Hope']}) df2 = pd.DataFrame({'ID': [1, 2, 4, 5, 6, 8, 9], 'Marks': [67, 92, 75, 83, 69, 56, 81]}) # merging df1 and df2 by ID# i.e. the rows with common ID's get merged# with all the ID's of both the dataframes# and NaN values for the columns where the ID's # do not matchdf = pd.merge(df1, df2, on="ID", how="outer")print(df)
Output :
Merged DataFrame
Picked
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Apr, 2021"
},
{
"code": null,
"e": 120,
"s": 28,
"text": "In this article, we will see how two data frames can be merged based on matched ID numbers."
},
{
"code": null,
"e": 129,
"s": 120,
"text": "Approach"
},
{
"code": null,
"e": 155,
"s": 129,
"text": "Create a first data frame"
},
{
"code": null,
"e": 182,
"s": 155,
"text": "Create a second data frame"
},
{
"code": null,
"e": 210,
"s": 182,
"text": "Select Column to be matched"
},
{
"code": null,
"e": 241,
"s": 210,
"text": "Merge using the merge function"
},
{
"code": null,
"e": 278,
"s": 241,
"text": "Syntax : DataFrame.merge(parameters)"
},
{
"code": null,
"e": 293,
"s": 278,
"text": "Display result"
},
{
"code": null,
"e": 420,
"s": 293,
"text": "Given below are implementations to produce a required result with the use of the required parameter with an appropriate value."
},
{
"code": null,
"e": 429,
"s": 420,
"text": "Example:"
},
{
"code": null,
"e": 437,
"s": 429,
"text": "Python3"
},
{
"code": "# import pandas as pdimport pandas as pd # creating dataframes as df1 and df2df1 = pd.DataFrame({'ID': [1, 2, 3, 5, 7, 8], 'Name': ['Sam', 'John', 'Bridge', 'Edge', 'Joe', 'Hope']}) df2 = pd.DataFrame({'ID': [1, 2, 4, 5, 6, 8, 9], 'Marks': [67, 92, 75, 83, 69, 56, 81]}) # merging df1 and df2 by ID# i.e. the rows with common ID's get# merged i.e. {1,2,5,8}df = pd.merge(df1, df2, on=\"ID\")print(df)",
"e": 906,
"s": 437,
"text": null
},
{
"code": null,
"e": 916,
"s": 906,
"text": "Output : "
},
{
"code": null,
"e": 933,
"s": 916,
"text": "Merged Dataframe"
},
{
"code": null,
"e": 1144,
"s": 933,
"text": "Merging two Dataframes with the ID column, with all the ID’s of the left Dataframe i.e. first parameter of the merge function. The ID’s which are not present in df2 gets a NaN value for the columns of that row."
},
{
"code": null,
"e": 1156,
"s": 1144,
"text": "Example 2 :"
},
{
"code": null,
"e": 1164,
"s": 1156,
"text": "Python3"
},
{
"code": "# import pandas as pdimport pandas as pd # creating dataframes as df1 and df2df1 = pd.DataFrame({'ID': [1, 2, 3, 5, 7, 8], 'Name': ['Sam', 'John', 'Bridge', 'Edge', 'Joe', 'Hope']}) df2 = pd.DataFrame({'ID': [1, 2, 4, 5, 6, 8, 9], 'Marks': [67, 92, 75, 83, 69, 56, 81]}) # merging df1 and df2 by ID# i.e. the rows with common ID's get merged# with all the ID's of left dataframe i.e. df1# and NaN for columns of df2 where ID do not matchdf = pd.merge(df1, df2, on=\"ID\", how=\"left\")print(df)",
"e": 1725,
"s": 1164,
"text": null
},
{
"code": null,
"e": 1735,
"s": 1725,
"text": "Output : "
},
{
"code": null,
"e": 1752,
"s": 1735,
"text": "Merged Dataframe"
},
{
"code": null,
"e": 1952,
"s": 1752,
"text": "Merging two Dataframes with the ID column, with all the ID’s of the right Dataframe i.e. second parameter of the merge function. The ID’s which do not match from df1 gets a NaN value for that column."
},
{
"code": null,
"e": 1964,
"s": 1952,
"text": "Example 3 :"
},
{
"code": null,
"e": 1972,
"s": 1964,
"text": "Python3"
},
{
"code": "# import pandas as pdimport pandas as pd # creating dataframes as df1 and df2df1 = pd.DataFrame({'ID': [1, 2, 3, 5, 7, 8], 'Name': ['Sam', 'John', 'Bridge', 'Edge', 'Joe', 'Hope']}) df2 = pd.DataFrame({'ID': [1, 2, 4, 5, 6, 8, 9], 'Marks': [67, 92, 75, 83, 69, 56, 81]}) # merging df1 and df2 by ID# i.e. the rows with common ID's get merged# with all the ID's of right dataframe i.e. df2# and NaN values for df1 columns where ID do not matchdf = pd.merge(df1, df2, on=\"ID\", how=\"right\")print(df)",
"e": 2540,
"s": 1972,
"text": null
},
{
"code": null,
"e": 2549,
"s": 2540,
"text": "Output :"
},
{
"code": null,
"e": 2566,
"s": 2549,
"text": "Merged Dataframe"
},
{
"code": null,
"e": 2653,
"s": 2566,
"text": "Merging two Dataframes with the ID column, with all that match in both the dataframes."
},
{
"code": null,
"e": 2665,
"s": 2653,
"text": "Example 4 :"
},
{
"code": null,
"e": 2673,
"s": 2665,
"text": "Python3"
},
{
"code": "# import pandas as pdimport pandas as pd # creating dataframes as df1 and df2df1 = pd.DataFrame({'ID': [1, 2, 3, 5, 7, 8], 'Name': ['Sam', 'John', 'Bridge', 'Edge', 'Joe', 'Hope']}) df2 = pd.DataFrame({'ID': [1, 2, 4, 5, 6, 8, 9], 'Marks': [67, 92, 75, 83, 69, 56, 81]}) # merging df1 and df2 by ID# i.e. the rows with common ID's get merged# with all the ID's that match in both the Dataframedf = pd.merge(df1, df2, on=\"ID\", how=\"inner\")print(df)",
"e": 3190,
"s": 2673,
"text": null
},
{
"code": null,
"e": 3200,
"s": 3190,
"text": "Output : "
},
{
"code": null,
"e": 3217,
"s": 3200,
"text": "Merged Dataframe"
},
{
"code": null,
"e": 3381,
"s": 3217,
"text": "Merging two Dataframes with the ID column, with all the ID’s of both the dataframes and NaN value for the columns where the ID is not found in both the dataframes."
},
{
"code": null,
"e": 3393,
"s": 3381,
"text": "Example 5 :"
},
{
"code": null,
"e": 3401,
"s": 3393,
"text": "Python3"
},
{
"code": "# import pandas as pdimport pandas as pd # creating dataframes as df1 and df2df1 = pd.DataFrame({'ID': [1, 2, 3, 5, 7, 8], 'Name': ['Sam', 'John', 'Bridge', 'Edge', 'Joe', 'Hope']}) df2 = pd.DataFrame({'ID': [1, 2, 4, 5, 6, 8, 9], 'Marks': [67, 92, 75, 83, 69, 56, 81]}) # merging df1 and df2 by ID# i.e. the rows with common ID's get merged# with all the ID's of both the dataframes# and NaN values for the columns where the ID's # do not matchdf = pd.merge(df1, df2, on=\"ID\", how=\"outer\")print(df)",
"e": 3970,
"s": 3401,
"text": null
},
{
"code": null,
"e": 3980,
"s": 3970,
"text": "Output : "
},
{
"code": null,
"e": 3997,
"s": 3980,
"text": "Merged DataFrame"
},
{
"code": null,
"e": 4004,
"s": 3997,
"text": "Picked"
},
{
"code": null,
"e": 4028,
"s": 4004,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 4051,
"s": 4028,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 4065,
"s": 4051,
"text": "Python-pandas"
},
{
"code": null,
"e": 4072,
"s": 4065,
"text": "Python"
}
] |
ML | Common Loss Functions
|
21 Jun, 2022
The loss function estimates how well a particular algorithm models the provided data. Loss functions are classified into two classes based on the type of learning task
Regression Models: predict continuous values.
Classification Models: predict the output from a set of finite categorical values.
REGRESSION LOSSES
Mean Squared Error (MSE) / Quadratic Loss / L2 Loss
It is the Mean of Square of Residuals for all the datapoints in the dataset. Residuals is the difference between the actual and the predicted prediction by the model.
Squaring of residuals is done to convert negative values to positive values. The normal error can be both negative and positive. If some positive and negative numbers are summed up, the sum maybe 0. This will tell the model that the net error is 0 and the model is performing well but contrary to that, the model is still performing badly. Thus, to get the actual performance of the model, only positive values are taken to get positive, squaring is done.
Squaring also gives more weightage to larger errors. When the cost function is far away from its minimal value, squaring the error will penalize the model more and thus helping in reaching the minimal value faster.
Mean of the Square of Residuals is taking instead of just taking the sum of square of residuals to make the loss function independent of number of datapoints in the training set.
MSE is sensitive to outliers.
(1)
Python3
import numpy as np # Mean Squared Error def mse( y, y_pred ) : return np.sum( ( y - y_pred ) ** 2 ) / np.size( y )
where,
i - ith training sample in a dataset
n - number of training samples
y(i) - Actual output of ith training sample
y-hat(i) - Predicted value of ith training sample
Mean Absolute Error (MAE) / La Loss
It is the Mean of Absolute of Residuals for all the datapoints in the dataset. Residuals is the difference between the actual and the predicted prediction by the model.
The absolute of residuals is done to convert negative values to positive values.
Mean is taken to make the loss function independent of number of datapoints in the training set.
One advantage of MAE is that is is robust to outliers.
MAE is generally less preferred over MSE as it is harder to calculate the derivative of the absolute function because absolute function is not differentiable at the minima.
Source: Wikipedia
(2)
Python3
# Mean Absolute Error def mae( y, y_pred ) : return np.sum( np.abs( y - y_pred ) ) / np.size( y )
Mean Bias Error: It is the same as MSE. but less accurate and can could conclude if the model has a positive bias or negative bias.
(3)
Python3
# Mean Bias Error def mbe( y, y_pred ) : return np.sum( y - y_pred ) / np.size( y )
Huber Loss / Smooth Mean Absolute Error
It is the combination of MSE and MAE. It takes the good properties of both the loss functions by being less sensitive to outliers and differentiable at minima.
When the error is smaller, the MSE part of the Huber is utilized and when the error is large, the MAE part of Huber loss is used.
A new hyper-parameter ‘????‘ is introduced which tells the loss function where to switch from MSE to MAE.
Additional ‘????’ terms are introduced in the loss function to smoothen the transition from MSE to MAE.
Source: www.evergreeninnovations.co
(4)
Python3
def Huber(y, y_pred, delta): condition = np.abs(y - y_pred) < delta l = np.where(condition, 0.5 * (y - y_pred) ** 2, delta * (np.abs(y - y_pred) - 0.5 * delta)) return np.sum(l) / np.size(y)
Cross-Entropy Loss: Also known as Negative Log Likelihood. It is the commonly used loss function for classification. Cross-entropy loss progress as the predicted probability diverges from the actual label.
Python3
# Binary Loss def cross_entropy(y, y_pred): return - np.sum(y * np.log(y_pred) + (1 - y) * np.log(1 - y_pred)) / np.size(y)
(5)
Hinge Loss: Also known as Multi-class SVM Loss. Hinge loss is applied for maximum-margin classification, prominently for support vector machines. It is a convex function used in the convex optimizer.
(6)
Python3
# Hinge Loss def hinge(y, y_pred): l = 0 size = np.size(y) for i in range(size): l = l + max(0, 1 - y[i] * y_pred[i]) return l / size
mohit baliyan
simmytarika5
utkarshanand221
Machine Learning
Mathematical
Mathematical
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 196,
"s": 28,
"text": "The loss function estimates how well a particular algorithm models the provided data. Loss functions are classified into two classes based on the type of learning task"
},
{
"code": null,
"e": 242,
"s": 196,
"text": "Regression Models: predict continuous values."
},
{
"code": null,
"e": 325,
"s": 242,
"text": "Classification Models: predict the output from a set of finite categorical values."
},
{
"code": null,
"e": 344,
"s": 325,
"text": "REGRESSION LOSSES "
},
{
"code": null,
"e": 396,
"s": 344,
"text": "Mean Squared Error (MSE) / Quadratic Loss / L2 Loss"
},
{
"code": null,
"e": 563,
"s": 396,
"text": "It is the Mean of Square of Residuals for all the datapoints in the dataset. Residuals is the difference between the actual and the predicted prediction by the model."
},
{
"code": null,
"e": 1019,
"s": 563,
"text": "Squaring of residuals is done to convert negative values to positive values. The normal error can be both negative and positive. If some positive and negative numbers are summed up, the sum maybe 0. This will tell the model that the net error is 0 and the model is performing well but contrary to that, the model is still performing badly. Thus, to get the actual performance of the model, only positive values are taken to get positive, squaring is done."
},
{
"code": null,
"e": 1234,
"s": 1019,
"text": "Squaring also gives more weightage to larger errors. When the cost function is far away from its minimal value, squaring the error will penalize the model more and thus helping in reaching the minimal value faster."
},
{
"code": null,
"e": 1413,
"s": 1234,
"text": "Mean of the Square of Residuals is taking instead of just taking the sum of square of residuals to make the loss function independent of number of datapoints in the training set."
},
{
"code": null,
"e": 1444,
"s": 1413,
"text": "MSE is sensitive to outliers. "
},
{
"code": null,
"e": 1451,
"s": 1444,
"text": "(1) "
},
{
"code": null,
"e": 1459,
"s": 1451,
"text": "Python3"
},
{
"code": "import numpy as np # Mean Squared Error def mse( y, y_pred ) : return np.sum( ( y - y_pred ) ** 2 ) / np.size( y ) ",
"e": 1585,
"s": 1459,
"text": null
},
{
"code": null,
"e": 1772,
"s": 1585,
"text": "where,\ni - ith training sample in a dataset\nn - number of training samples\ny(i) - Actual output of ith training sample\ny-hat(i) - Predicted value of ith training sample"
},
{
"code": null,
"e": 1808,
"s": 1772,
"text": "Mean Absolute Error (MAE) / La Loss"
},
{
"code": null,
"e": 1977,
"s": 1808,
"text": "It is the Mean of Absolute of Residuals for all the datapoints in the dataset. Residuals is the difference between the actual and the predicted prediction by the model."
},
{
"code": null,
"e": 2058,
"s": 1977,
"text": "The absolute of residuals is done to convert negative values to positive values."
},
{
"code": null,
"e": 2155,
"s": 2058,
"text": "Mean is taken to make the loss function independent of number of datapoints in the training set."
},
{
"code": null,
"e": 2210,
"s": 2155,
"text": "One advantage of MAE is that is is robust to outliers."
},
{
"code": null,
"e": 2383,
"s": 2210,
"text": "MAE is generally less preferred over MSE as it is harder to calculate the derivative of the absolute function because absolute function is not differentiable at the minima."
},
{
"code": null,
"e": 2401,
"s": 2383,
"text": "Source: Wikipedia"
},
{
"code": null,
"e": 2408,
"s": 2401,
"text": "(2) "
},
{
"code": null,
"e": 2416,
"s": 2408,
"text": "Python3"
},
{
"code": "# Mean Absolute Error def mae( y, y_pred ) : return np.sum( np.abs( y - y_pred ) ) / np.size( y )",
"e": 2522,
"s": 2416,
"text": null
},
{
"code": null,
"e": 2657,
"s": 2524,
"text": "Mean Bias Error: It is the same as MSE. but less accurate and can could conclude if the model has a positive bias or negative bias. "
},
{
"code": null,
"e": 2664,
"s": 2657,
"text": "(3) "
},
{
"code": null,
"e": 2672,
"s": 2664,
"text": "Python3"
},
{
"code": "# Mean Bias Error def mbe( y, y_pred ) : return np.sum( y - y_pred ) / np.size( y )",
"e": 2764,
"s": 2672,
"text": null
},
{
"code": null,
"e": 2806,
"s": 2766,
"text": "Huber Loss / Smooth Mean Absolute Error"
},
{
"code": null,
"e": 2966,
"s": 2806,
"text": "It is the combination of MSE and MAE. It takes the good properties of both the loss functions by being less sensitive to outliers and differentiable at minima."
},
{
"code": null,
"e": 3096,
"s": 2966,
"text": "When the error is smaller, the MSE part of the Huber is utilized and when the error is large, the MAE part of Huber loss is used."
},
{
"code": null,
"e": 3202,
"s": 3096,
"text": "A new hyper-parameter ‘????‘ is introduced which tells the loss function where to switch from MSE to MAE."
},
{
"code": null,
"e": 3307,
"s": 3202,
"text": "Additional ‘????’ terms are introduced in the loss function to smoothen the transition from MSE to MAE. "
},
{
"code": null,
"e": 3343,
"s": 3307,
"text": "Source: www.evergreeninnovations.co"
},
{
"code": null,
"e": 3350,
"s": 3343,
"text": "(4) "
},
{
"code": null,
"e": 3358,
"s": 3350,
"text": "Python3"
},
{
"code": "def Huber(y, y_pred, delta): condition = np.abs(y - y_pred) < delta l = np.where(condition, 0.5 * (y - y_pred) ** 2, delta * (np.abs(y - y_pred) - 0.5 * delta)) return np.sum(l) / np.size(y)",
"e": 3577,
"s": 3358,
"text": null
},
{
"code": null,
"e": 3785,
"s": 3579,
"text": "Cross-Entropy Loss: Also known as Negative Log Likelihood. It is the commonly used loss function for classification. Cross-entropy loss progress as the predicted probability diverges from the actual label."
},
{
"code": null,
"e": 3793,
"s": 3785,
"text": "Python3"
},
{
"code": "# Binary Loss def cross_entropy(y, y_pred): return - np.sum(y * np.log(y_pred) + (1 - y) * np.log(1 - y_pred)) / np.size(y)",
"e": 3922,
"s": 3793,
"text": null
},
{
"code": null,
"e": 3931,
"s": 3924,
"text": "(5) "
},
{
"code": null,
"e": 4133,
"s": 3931,
"text": "Hinge Loss: Also known as Multi-class SVM Loss. Hinge loss is applied for maximum-margin classification, prominently for support vector machines. It is a convex function used in the convex optimizer. "
},
{
"code": null,
"e": 4140,
"s": 4133,
"text": "(6) "
},
{
"code": null,
"e": 4148,
"s": 4140,
"text": "Python3"
},
{
"code": "# Hinge Loss def hinge(y, y_pred): l = 0 size = np.size(y) for i in range(size): l = l + max(0, 1 - y[i] * y_pred[i]) return l / size",
"e": 4307,
"s": 4148,
"text": null
},
{
"code": null,
"e": 4323,
"s": 4309,
"text": "mohit baliyan"
},
{
"code": null,
"e": 4336,
"s": 4323,
"text": "simmytarika5"
},
{
"code": null,
"e": 4352,
"s": 4336,
"text": "utkarshanand221"
},
{
"code": null,
"e": 4369,
"s": 4352,
"text": "Machine Learning"
},
{
"code": null,
"e": 4382,
"s": 4369,
"text": "Mathematical"
},
{
"code": null,
"e": 4395,
"s": 4382,
"text": "Mathematical"
},
{
"code": null,
"e": 4412,
"s": 4395,
"text": "Machine Learning"
}
] |
PHP | MySQL WHERE Clause
|
03 Mar, 2018
The WHERE Clause is used to filter only those records that are fulfilled by a specific condition given by the user. in other words, the SQL WHERE clause is used to restrict the number of rows affected by a SELECT, UPDATE or DELETE query.
Syntax :The basic syntax of the where clause is –SELECT Column1 , Column2 , ....FROM Table_NameWHERE Condition
Let us consider the following table “Data” with three columns ‘FirstName’, ‘LastName’ and ‘Age’.
To select all the rows where the “Firstname” is “ram”, we will use the following code :
Where Clause using Procedural Method :
<?php$link = mysqli_connect("localhost", "root", "", "Mydb"); if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error());} $sql = "SELECT * FROM Data WHERE Firstname='ram'";if($res = mysqli_query($link, $sql)){ if(mysqli_num_rows($res) > 0){ echo "<table>"; echo "<tr>"; echo "<th>Firstname</th>"; echo "<th>Lastname</th>"; echo "<th>age</th>"; echo "</tr>"; while($row = mysqli_fetch_array($res)){ echo "<tr>"; echo "<td>" . $row['Firstname'] . "</td>"; echo "<td>" . $row['Lastname'] . "</td>"; echo "<td>" . $row['Age'] . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_free_result($res); } else{ echo "No Matching records are found."; }} else{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);} mysqli_close($link);?>
Output :
Code Explanation :
The “res” variable stores the data that is returned by the function mysql_query().Everytime mysqli_fetch_array() is invoked, it returns the next row from the res() set.The while loop is used to loop through all the rows of the table “data”.
The “res” variable stores the data that is returned by the function mysql_query().
Everytime mysqli_fetch_array() is invoked, it returns the next row from the res() set.
The while loop is used to loop through all the rows of the table “data”.
Where Clause using Object Oriented Method :
<?php$mysqli = new mysqli("localhost", "root", "", "Mydb"); if($mysqli === false){ die("ERROR: Could not connect. " . $mysqli->connect_error);} $sql = "SELECT * FROM Data WHERE Firstname='ram'";if($res = $mysqli->query($sql)){ if($res->num_rows > 0){ echo "<table>"; echo "<tr>"; echo "<th>Firstname</th>"; echo "<th>Lastname</th>"; echo "<th>Age</th>"; echo "</tr>"; while($row = $res->fetch_array()){ echo "<tr>"; echo "<td>" . $row['Firstname'] . "</td>"; echo "<td>" . $row['Lastname'] . "</td>"; echo "<td>" . $row['Age'] . "</td>"; echo "</tr>"; } echo "</table>"; $res->free(); } else{ echo "No matching records are found."; }} else{ echo "ERROR: Could not able to execute $sql. " . $mysqli->error;} $mysqli->close();?>
Output :
Where Clause using PDO Method :
<?phptry{ $pdo = new PDO("mysql:host=localhost; dbname=Mydb", "root", ""); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);} catch(PDOException $e){ die("ERROR: Could not connect. " . $e->getMessage());} try{ $sql = "SELECT * FROM Data WHERE Firstname='ram'"; $res = $pdo->query($sql); if($res->rowCount() > 0){ echo "<table>"; echo "<tr>"; echo "<th>Firstname</th>"; echo "<th>Lastname</th>"; echo "<th>Age</th>"; echo "</tr>"; while($row = $res->fetch()){ echo "<tr>"; echo "<td>" . $row['Firstname'] . "</td>"; echo "<td>" . $row['Lastname'] . "</td>"; echo "<td>" . $row['Age'] . "</td>"; echo "</tr>"; } echo "</table>"; unset($res); } else{ echo "No records matching are found."; }} catch(PDOException $e){ die("ERROR: Could not able to execute $sql. " . $e->getMessage());} unset($pdo);?>
Output :
mysql
PHP
SQL
Web Technologies
SQL
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
SQL | DDL, DQL, DML, DCL and TCL Commands
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
How to find Nth highest salary from a table
CTE in SQL
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Mar, 2018"
},
{
"code": null,
"e": 266,
"s": 28,
"text": "The WHERE Clause is used to filter only those records that are fulfilled by a specific condition given by the user. in other words, the SQL WHERE clause is used to restrict the number of rows affected by a SELECT, UPDATE or DELETE query."
},
{
"code": null,
"e": 377,
"s": 266,
"text": "Syntax :The basic syntax of the where clause is –SELECT Column1 , Column2 , ....FROM Table_NameWHERE Condition"
},
{
"code": null,
"e": 474,
"s": 377,
"text": "Let us consider the following table “Data” with three columns ‘FirstName’, ‘LastName’ and ‘Age’."
},
{
"code": null,
"e": 562,
"s": 474,
"text": "To select all the rows where the “Firstname” is “ram”, we will use the following code :"
},
{
"code": null,
"e": 601,
"s": 562,
"text": "Where Clause using Procedural Method :"
},
{
"code": "<?php$link = mysqli_connect(\"localhost\", \"root\", \"\", \"Mydb\"); if($link === false){ die(\"ERROR: Could not connect. \" . mysqli_connect_error());} $sql = \"SELECT * FROM Data WHERE Firstname='ram'\";if($res = mysqli_query($link, $sql)){ if(mysqli_num_rows($res) > 0){ echo \"<table>\"; echo \"<tr>\"; echo \"<th>Firstname</th>\"; echo \"<th>Lastname</th>\"; echo \"<th>age</th>\"; echo \"</tr>\"; while($row = mysqli_fetch_array($res)){ echo \"<tr>\"; echo \"<td>\" . $row['Firstname'] . \"</td>\"; echo \"<td>\" . $row['Lastname'] . \"</td>\"; echo \"<td>\" . $row['Age'] . \"</td>\"; echo \"</tr>\"; } echo \"</table>\"; mysqli_free_result($res); } else{ echo \"No Matching records are found.\"; }} else{ echo \"ERROR: Could not able to execute $sql. \" . mysqli_error($link);} mysqli_close($link);?>",
"e": 1606,
"s": 601,
"text": null
},
{
"code": null,
"e": 1615,
"s": 1606,
"text": "Output :"
},
{
"code": null,
"e": 1634,
"s": 1615,
"text": "Code Explanation :"
},
{
"code": null,
"e": 1875,
"s": 1634,
"text": "The “res” variable stores the data that is returned by the function mysql_query().Everytime mysqli_fetch_array() is invoked, it returns the next row from the res() set.The while loop is used to loop through all the rows of the table “data”."
},
{
"code": null,
"e": 1958,
"s": 1875,
"text": "The “res” variable stores the data that is returned by the function mysql_query()."
},
{
"code": null,
"e": 2045,
"s": 1958,
"text": "Everytime mysqli_fetch_array() is invoked, it returns the next row from the res() set."
},
{
"code": null,
"e": 2118,
"s": 2045,
"text": "The while loop is used to loop through all the rows of the table “data”."
},
{
"code": null,
"e": 2162,
"s": 2118,
"text": "Where Clause using Object Oriented Method :"
},
{
"code": "<?php$mysqli = new mysqli(\"localhost\", \"root\", \"\", \"Mydb\"); if($mysqli === false){ die(\"ERROR: Could not connect. \" . $mysqli->connect_error);} $sql = \"SELECT * FROM Data WHERE Firstname='ram'\";if($res = $mysqli->query($sql)){ if($res->num_rows > 0){ echo \"<table>\"; echo \"<tr>\"; echo \"<th>Firstname</th>\"; echo \"<th>Lastname</th>\"; echo \"<th>Age</th>\"; echo \"</tr>\"; while($row = $res->fetch_array()){ echo \"<tr>\"; echo \"<td>\" . $row['Firstname'] . \"</td>\"; echo \"<td>\" . $row['Lastname'] . \"</td>\"; echo \"<td>\" . $row['Age'] . \"</td>\"; echo \"</tr>\"; } echo \"</table>\"; $res->free(); } else{ echo \"No matching records are found.\"; }} else{ echo \"ERROR: Could not able to execute $sql. \" . $mysqli->error;} $mysqli->close();?>",
"e": 3135,
"s": 2162,
"text": null
},
{
"code": null,
"e": 3144,
"s": 3135,
"text": "Output :"
},
{
"code": null,
"e": 3176,
"s": 3144,
"text": "Where Clause using PDO Method :"
},
{
"code": "<?phptry{ $pdo = new PDO(\"mysql:host=localhost; dbname=Mydb\", \"root\", \"\"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);} catch(PDOException $e){ die(\"ERROR: Could not connect. \" . $e->getMessage());} try{ $sql = \"SELECT * FROM Data WHERE Firstname='ram'\"; $res = $pdo->query($sql); if($res->rowCount() > 0){ echo \"<table>\"; echo \"<tr>\"; echo \"<th>Firstname</th>\"; echo \"<th>Lastname</th>\"; echo \"<th>Age</th>\"; echo \"</tr>\"; while($row = $res->fetch()){ echo \"<tr>\"; echo \"<td>\" . $row['Firstname'] . \"</td>\"; echo \"<td>\" . $row['Lastname'] . \"</td>\"; echo \"<td>\" . $row['Age'] . \"</td>\"; echo \"</tr>\"; } echo \"</table>\"; unset($res); } else{ echo \"No records matching are found.\"; }} catch(PDOException $e){ die(\"ERROR: Could not able to execute $sql. \" . $e->getMessage());} unset($pdo);?>",
"e": 4290,
"s": 3176,
"text": null
},
{
"code": null,
"e": 4299,
"s": 4290,
"text": "Output :"
},
{
"code": null,
"e": 4305,
"s": 4299,
"text": "mysql"
},
{
"code": null,
"e": 4309,
"s": 4305,
"text": "PHP"
},
{
"code": null,
"e": 4313,
"s": 4309,
"text": "SQL"
},
{
"code": null,
"e": 4330,
"s": 4313,
"text": "Web Technologies"
},
{
"code": null,
"e": 4334,
"s": 4330,
"text": "SQL"
},
{
"code": null,
"e": 4338,
"s": 4334,
"text": "PHP"
},
{
"code": null,
"e": 4436,
"s": 4338,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4486,
"s": 4436,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 4526,
"s": 4486,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 4587,
"s": 4526,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 4637,
"s": 4587,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 4682,
"s": 4637,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 4724,
"s": 4682,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 4771,
"s": 4724,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 4789,
"s": 4771,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 4833,
"s": 4789,
"text": "How to find Nth highest salary from a table"
}
] |
Python program to print current hour, minute, second and microsecond
|
09 Dec, 2021
In this article, we are going to discuss how to print current hour, minute, second, and microsecond using Python. In order to print hour, minute and microseconds we need to use DateTime module in Python.
datetime.now().hour(): This method returns the current hour value of the datetime object.
datetime.now().minute(): This method returns the current minute value of the datetime object.
datetime.now().second(): This method returns the current second value of the datetime object.
datetime.now().microsecond(): This method returns the current microsecond value of the datetime object.
Below are the various implementations using examples that depict how to print current hour, minute, second, and microsecond in python.
Example 1: To print time, hour, minute, second, and microsecond
Python3
# importing datetime modulefrom datetime import datetime # now is a method in datetime module is# used to retrieve current data,timemyobj = datetime.now() # printing current hour using hour# classprint("Current hour ", myobj.hour) # printing current minute using minute# classprint("Current minute ", myobj.minute) # printing current second using second# classprint("Current second ", myobj.second) # printing current microsecond using# microsecond classprint("Current microsecond ", myobj.microsecond)
Output:
Example 2: To print object, time, hour, minute, second, and microsecond.
Python3
# importing datetime modulefrom datetime import datetime # now is a method in datetime module is# used to retrieve current data,timemyobj = datetime.now() # printing the object itselfprint("Object:", myobj) # printing current hour using hour# classprint("Current hour ", myobj.hour) # printing current minute using minute# classprint("Current minute ", myobj.minute) # printing current second using second# classprint("Current second ", myobj.second) # printing current microsecond using microsecond# classprint("Current microsecond ", myobj.microsecond)
Output:
simmytarika5
Picked
Python datetime-program
Python-datetime
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": "\n09 Dec, 2021"
},
{
"code": null,
"e": 232,
"s": 28,
"text": "In this article, we are going to discuss how to print current hour, minute, second, and microsecond using Python. In order to print hour, minute and microseconds we need to use DateTime module in Python."
},
{
"code": null,
"e": 322,
"s": 232,
"text": "datetime.now().hour(): This method returns the current hour value of the datetime object."
},
{
"code": null,
"e": 416,
"s": 322,
"text": "datetime.now().minute(): This method returns the current minute value of the datetime object."
},
{
"code": null,
"e": 510,
"s": 416,
"text": "datetime.now().second(): This method returns the current second value of the datetime object."
},
{
"code": null,
"e": 614,
"s": 510,
"text": "datetime.now().microsecond(): This method returns the current microsecond value of the datetime object."
},
{
"code": null,
"e": 749,
"s": 614,
"text": "Below are the various implementations using examples that depict how to print current hour, minute, second, and microsecond in python."
},
{
"code": null,
"e": 813,
"s": 749,
"text": "Example 1: To print time, hour, minute, second, and microsecond"
},
{
"code": null,
"e": 821,
"s": 813,
"text": "Python3"
},
{
"code": "# importing datetime modulefrom datetime import datetime # now is a method in datetime module is# used to retrieve current data,timemyobj = datetime.now() # printing current hour using hour# classprint(\"Current hour \", myobj.hour) # printing current minute using minute# classprint(\"Current minute \", myobj.minute) # printing current second using second# classprint(\"Current second \", myobj.second) # printing current microsecond using# microsecond classprint(\"Current microsecond \", myobj.microsecond)",
"e": 1326,
"s": 821,
"text": null
},
{
"code": null,
"e": 1334,
"s": 1326,
"text": "Output:"
},
{
"code": null,
"e": 1407,
"s": 1334,
"text": "Example 2: To print object, time, hour, minute, second, and microsecond."
},
{
"code": null,
"e": 1415,
"s": 1407,
"text": "Python3"
},
{
"code": "# importing datetime modulefrom datetime import datetime # now is a method in datetime module is# used to retrieve current data,timemyobj = datetime.now() # printing the object itselfprint(\"Object:\", myobj) # printing current hour using hour# classprint(\"Current hour \", myobj.hour) # printing current minute using minute# classprint(\"Current minute \", myobj.minute) # printing current second using second# classprint(\"Current second \", myobj.second) # printing current microsecond using microsecond# classprint(\"Current microsecond \", myobj.microsecond)",
"e": 1973,
"s": 1415,
"text": null
},
{
"code": null,
"e": 1981,
"s": 1973,
"text": "Output:"
},
{
"code": null,
"e": 1994,
"s": 1981,
"text": "simmytarika5"
},
{
"code": null,
"e": 2001,
"s": 1994,
"text": "Picked"
},
{
"code": null,
"e": 2025,
"s": 2001,
"text": "Python datetime-program"
},
{
"code": null,
"e": 2041,
"s": 2025,
"text": "Python-datetime"
},
{
"code": null,
"e": 2048,
"s": 2041,
"text": "Python"
},
{
"code": null,
"e": 2064,
"s": 2048,
"text": "Python Programs"
}
] |
Set the focus to HTML form element using JavaScript
|
20 May, 2019
To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example.
Example 1: The focus() method is set to the input tag when user clicks on Focus button.
<!DOCTYPE html><html> <head> <title> Set focus to HTML form element </title></head> <body> <p> Click on button to set focus on input field </p> <form> <input type="text" id="input1"> <br><br> <button type="button" onclick="focusInput()"> Set Focus </button> </form> <script> function focusInput() { document.getElementById("input1").focus(); } </script></body> </html>
Output:
Before Clicking the button:
After Clicking the button:
Example 2: This example focuses on the input field automatically on page load.
<!DOCTYPE html><html> <head> <title> Set focus to HTML form element </title></head> <body> <p> Click on button to focus on the input field. </p> <form> Name: <input type="text" id="input1"> <br><br> Age: <input type="text" id="input2"> </form> <script> window.onload = function() { document.getElementById("input1").focus(); } </script></body> </html>
Output:
Example 3: The following program focuses on the input field when clicked on Focus button. To blur the focused input field, the blur() property can be used.
<!DOCTYPE html><html> <head> <title> Set focus to HTML form element </title></head> <body> <p> Click on button to focus on the input field. </p> <form> <input type="text" id="input1"> <br><br> <button type="button" onclick="focusInput()"> Focus </button> <button type="button" onclick="blurInput()"> Blur </button> </form> <script> function focusInput() { document.getElementById("input1").focus(); } function blurInput() { document.getElementById("input1").blur(); } </script></body> </html>
Output:
Before Clicking the button:
After Clicking on Focus button:
After Clicking on Blur button:
HTML-DOM
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Roadmap to Learn JavaScript For Beginners
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Differences between Functional Components and Class Components in React
Hide or show elements in HTML using display property
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Roadmap to Learn JavaScript For Beginners
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 May, 2019"
},
{
"code": null,
"e": 215,
"s": 28,
"text": "To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example."
},
{
"code": null,
"e": 303,
"s": 215,
"text": "Example 1: The focus() method is set to the input tag when user clicks on Focus button."
},
{
"code": "<!DOCTYPE html><html> <head> <title> Set focus to HTML form element </title></head> <body> <p> Click on button to set focus on input field </p> <form> <input type=\"text\" id=\"input1\"> <br><br> <button type=\"button\" onclick=\"focusInput()\"> Set Focus </button> </form> <script> function focusInput() { document.getElementById(\"input1\").focus(); } </script></body> </html> ",
"e": 836,
"s": 303,
"text": null
},
{
"code": null,
"e": 844,
"s": 836,
"text": "Output:"
},
{
"code": null,
"e": 872,
"s": 844,
"text": "Before Clicking the button:"
},
{
"code": null,
"e": 899,
"s": 872,
"text": "After Clicking the button:"
},
{
"code": null,
"e": 978,
"s": 899,
"text": "Example 2: This example focuses on the input field automatically on page load."
},
{
"code": "<!DOCTYPE html><html> <head> <title> Set focus to HTML form element </title></head> <body> <p> Click on button to focus on the input field. </p> <form> Name: <input type=\"text\" id=\"input1\"> <br><br> Age: <input type=\"text\" id=\"input2\"> </form> <script> window.onload = function() { document.getElementById(\"input1\").focus(); } </script></body> </html> ",
"e": 1478,
"s": 978,
"text": null
},
{
"code": null,
"e": 1486,
"s": 1478,
"text": "Output:"
},
{
"code": null,
"e": 1642,
"s": 1486,
"text": "Example 3: The following program focuses on the input field when clicked on Focus button. To blur the focused input field, the blur() property can be used."
},
{
"code": "<!DOCTYPE html><html> <head> <title> Set focus to HTML form element </title></head> <body> <p> Click on button to focus on the input field. </p> <form> <input type=\"text\" id=\"input1\"> <br><br> <button type=\"button\" onclick=\"focusInput()\"> Focus </button> <button type=\"button\" onclick=\"blurInput()\"> Blur </button> </form> <script> function focusInput() { document.getElementById(\"input1\").focus(); } function blurInput() { document.getElementById(\"input1\").blur(); } </script></body> </html> ",
"e": 2359,
"s": 1642,
"text": null
},
{
"code": null,
"e": 2367,
"s": 2359,
"text": "Output:"
},
{
"code": null,
"e": 2395,
"s": 2367,
"text": "Before Clicking the button:"
},
{
"code": null,
"e": 2427,
"s": 2395,
"text": "After Clicking on Focus button:"
},
{
"code": null,
"e": 2458,
"s": 2427,
"text": "After Clicking on Blur button:"
},
{
"code": null,
"e": 2467,
"s": 2458,
"text": "HTML-DOM"
},
{
"code": null,
"e": 2474,
"s": 2467,
"text": "Picked"
},
{
"code": null,
"e": 2485,
"s": 2474,
"text": "JavaScript"
},
{
"code": null,
"e": 2502,
"s": 2485,
"text": "Web Technologies"
},
{
"code": null,
"e": 2529,
"s": 2502,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2627,
"s": 2529,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2669,
"s": 2627,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2730,
"s": 2669,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2770,
"s": 2730,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2842,
"s": 2770,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2895,
"s": 2842,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2957,
"s": 2895,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2990,
"s": 2957,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3032,
"s": 2990,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3093,
"s": 3032,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Python program to check the validity of a Password
|
23 Jun, 2022
In this program, we will be taking a password as a combination of alphanumeric characters along with special characters, and checking whether the password is valid or not with the help of a few conditions.
Primary conditions for password validation:
Minimum 8 characters.The alphabet must be between [a-z]At least one alphabet should be of Upper Case [A-Z]At least 1 number or digit between [0-9].At least 1 character from [ _ or @ or $ ].
Minimum 8 characters.
The alphabet must be between [a-z]
At least one alphabet should be of Upper Case [A-Z]
At least 1 number or digit between [0-9].
At least 1 character from [ _ or @ or $ ].
Examples:
Input : R@m@_f0rtu9e$
Output : Valid Password
Input : Rama_fortune$
Output : Invalid Password
Explanation: Number is missing
Input : Rama#fortu9e
Output : Invalid Password
Explanation: Must consist from _ or @ or $
Here we have used the re module that provides support for regular expressions in Python. Along with this the re.search() method returns False (if the first parameter is not found in the second parameter) This method is best suited for testing a regular expression more than extracting data. We have used the re.search() to check the validation of alphabets, digits, or special characters. To check for white spaces we use the “\s” which comes in the module of the regular expression.
Python3
# Python program to check validation of password# Module of regular expression is used with search()import repassword = "R@m@_f0rtu9e$& quotflag = 0while True: if (len(password) & lt 8): flag = -1 break elif not re.search(& quot [a-z]" , password): flag = -1 break elif not re.search(& quot [A-Z]" , password): flag = -1 break elif not re.search(& quot [0-9]" , password): flag = -1 break elif not re.search(& quot [_@$]" , password): flag = -1 break elif re.search(& quot \s" , password): flag = -1 break else: flag = 0 print(& quot Valid Password & quot ) break if flag == -1: print(& quot Not a Valid Password & quot )
Python3
l, u, p, d = 0, 0, 0, 0s = "R@m@_f0rtu9e$"if (len(s) >= 8): for i in s: # counting lowercase alphabets if (i.islower()): l+=1 # counting uppercase alphabets if (i.isupper()): u+=1 # counting digits if (i.isdigit()): d+=1 # counting the mentioned special characters if(i=='@'or i=='$' or i=='_'): p+=1 if (l>=1 and u>=1 and p>=1 and d>=1 and l+p+u+d==len(s)): print("Valid Password")else: print("Invalid Password")
Way 3: Without using any built-in method
Python3
l, u, p, d = 0, 0, 0, 0s = "R@m@_f0rtu9e$"capitalalphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZ"smallalphabets="abcdefghijklmnopqrstuvwxyz"specialchar="$@_"digits="0123456789"if (len(s) >= 8): for i in s: # counting lowercase alphabets if (i in smallalphabets): l+=1 # counting uppercase alphabets if (i in capitalalphabets): u+=1 # counting digits if (i in digits): d+=1 # counting the mentioned special characters if(i in specialchar): p+=1 if (l>=1 and u>=1 and p>=1 and d>=1 and l+p+u+d==len(s)): print("Valid Password")else: print("Invalid Password")
Valid Password
Divyu_Pandey
kogantibhavya
Python Regex-programs
Python string-programs
python-regex
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
How to Install PIP on Windows ?
Python String | replace()
Python Classes and Objects
Introduction To PYTHON
Python OOPs Concepts
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 260,
"s": 54,
"text": "In this program, we will be taking a password as a combination of alphanumeric characters along with special characters, and checking whether the password is valid or not with the help of a few conditions."
},
{
"code": null,
"e": 304,
"s": 260,
"text": "Primary conditions for password validation:"
},
{
"code": null,
"e": 494,
"s": 304,
"text": "Minimum 8 characters.The alphabet must be between [a-z]At least one alphabet should be of Upper Case [A-Z]At least 1 number or digit between [0-9].At least 1 character from [ _ or @ or $ ]."
},
{
"code": null,
"e": 516,
"s": 494,
"text": "Minimum 8 characters."
},
{
"code": null,
"e": 551,
"s": 516,
"text": "The alphabet must be between [a-z]"
},
{
"code": null,
"e": 603,
"s": 551,
"text": "At least one alphabet should be of Upper Case [A-Z]"
},
{
"code": null,
"e": 645,
"s": 603,
"text": "At least 1 number or digit between [0-9]."
},
{
"code": null,
"e": 688,
"s": 645,
"text": "At least 1 character from [ _ or @ or $ ]."
},
{
"code": null,
"e": 698,
"s": 688,
"text": "Examples:"
},
{
"code": null,
"e": 916,
"s": 698,
"text": "Input : R@m@_f0rtu9e$\nOutput : Valid Password\n\nInput : Rama_fortune$\nOutput : Invalid Password\nExplanation: Number is missing\n\nInput : Rama#fortu9e \nOutput : Invalid Password\nExplanation: Must consist from _ or @ or $"
},
{
"code": null,
"e": 1401,
"s": 916,
"text": "Here we have used the re module that provides support for regular expressions in Python. Along with this the re.search() method returns False (if the first parameter is not found in the second parameter) This method is best suited for testing a regular expression more than extracting data. We have used the re.search() to check the validation of alphabets, digits, or special characters. To check for white spaces we use the “\\s” which comes in the module of the regular expression. "
},
{
"code": null,
"e": 1409,
"s": 1401,
"text": "Python3"
},
{
"code": "# Python program to check validation of password# Module of regular expression is used with search()import repassword = \"R@m@_f0rtu9e$& quotflag = 0while True: if (len(password) & lt 8): flag = -1 break elif not re.search(& quot [a-z]\" , password): flag = -1 break elif not re.search(& quot [A-Z]\" , password): flag = -1 break elif not re.search(& quot [0-9]\" , password): flag = -1 break elif not re.search(& quot [_@$]\" , password): flag = -1 break elif re.search(& quot \\s\" , password): flag = -1 break else: flag = 0 print(& quot Valid Password & quot ) break if flag == -1: print(& quot Not a Valid Password & quot )",
"e": 2441,
"s": 1409,
"text": null
},
{
"code": null,
"e": 2449,
"s": 2441,
"text": "Python3"
},
{
"code": "l, u, p, d = 0, 0, 0, 0s = \"R@m@_f0rtu9e$\"if (len(s) >= 8): for i in s: # counting lowercase alphabets if (i.islower()): l+=1 # counting uppercase alphabets if (i.isupper()): u+=1 # counting digits if (i.isdigit()): d+=1 # counting the mentioned special characters if(i=='@'or i=='$' or i=='_'): p+=1 if (l>=1 and u>=1 and p>=1 and d>=1 and l+p+u+d==len(s)): print(\"Valid Password\")else: print(\"Invalid Password\")",
"e": 3018,
"s": 2449,
"text": null
},
{
"code": null,
"e": 3059,
"s": 3018,
"text": "Way 3: Without using any built-in method"
},
{
"code": null,
"e": 3067,
"s": 3059,
"text": "Python3"
},
{
"code": "l, u, p, d = 0, 0, 0, 0s = \"R@m@_f0rtu9e$\"capitalalphabets=\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"smallalphabets=\"abcdefghijklmnopqrstuvwxyz\"specialchar=\"$@_\"digits=\"0123456789\"if (len(s) >= 8): for i in s: # counting lowercase alphabets if (i in smallalphabets): l+=1 # counting uppercase alphabets if (i in capitalalphabets): u+=1 # counting digits if (i in digits): d+=1 # counting the mentioned special characters if(i in specialchar): p+=1 if (l>=1 and u>=1 and p>=1 and d>=1 and l+p+u+d==len(s)): print(\"Valid Password\")else: print(\"Invalid Password\")",
"e": 3766,
"s": 3067,
"text": null
},
{
"code": null,
"e": 3781,
"s": 3766,
"text": "Valid Password"
},
{
"code": null,
"e": 3794,
"s": 3781,
"text": "Divyu_Pandey"
},
{
"code": null,
"e": 3808,
"s": 3794,
"text": "kogantibhavya"
},
{
"code": null,
"e": 3830,
"s": 3808,
"text": "Python Regex-programs"
},
{
"code": null,
"e": 3853,
"s": 3830,
"text": "Python string-programs"
},
{
"code": null,
"e": 3866,
"s": 3853,
"text": "python-regex"
},
{
"code": null,
"e": 3880,
"s": 3866,
"text": "python-string"
},
{
"code": null,
"e": 3887,
"s": 3880,
"text": "Python"
},
{
"code": null,
"e": 3985,
"s": 3887,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4003,
"s": 3985,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4025,
"s": 4003,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4067,
"s": 4025,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4099,
"s": 4067,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4125,
"s": 4099,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4152,
"s": 4125,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4175,
"s": 4152,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4196,
"s": 4175,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4225,
"s": 4196,
"text": "*args and **kwargs in Python"
}
] |
Java Program to Use Methods of Column to Get Column Name in JDBC
|
15 Jul, 2021
Java Database Connectivity or JDBC is a Java API (application programming interface) used to perform database operations through Java application. It allows the execution of SQL commands for the creation of tables and data manipulation through Java application. Java supports java.sql package which contains inbuilt methods for accessing and processing data stored in a database. The methods in java.sql throw SQL exceptions hence the code block must be either placed within a try block and let the catch block handle exceptions if any else add throws clause to the main method.
Procedure:
The forName() is a static method of class which is used to load the driver.Next the connection to the database is established using the getConnection() method of DriverManager class. The getConnection() accepts the URLs, username and password to establish a connection. The methods defined in the Statement interface is used to interact with the database.First, the table is created and then records are inserted into the table.The sql commands are batched together using addBatch() and executed all at once using executeBatch() method.The records in the table are fetched into the ResultSet.The getMetaData() method of ResultSet is used to get the metadata of the records fetched into the ResultSet.The getColumnCount() and getColumnName() methods of ResultSetMetaData interface is used to get the number of columns and name of each column in the table.
The forName() is a static method of class which is used to load the driver.
Next the connection to the database is established using the getConnection() method of DriverManager class. The getConnection() accepts the URLs, username and password to establish a connection. The methods defined in the Statement interface is used to interact with the database.First, the table is created and then records are inserted into the table.The sql commands are batched together using addBatch() and executed all at once using executeBatch() method.The records in the table are fetched into the ResultSet.The getMetaData() method of ResultSet is used to get the metadata of the records fetched into the ResultSet.The getColumnCount() and getColumnName() methods of ResultSetMetaData interface is used to get the number of columns and name of each column in the table.
First, the table is created and then records are inserted into the table.
The sql commands are batched together using addBatch() and executed all at once using executeBatch() method.
The records in the table are fetched into the ResultSet.
The getMetaData() method of ResultSet is used to get the metadata of the records fetched into the ResultSet.
The getColumnCount() and getColumnName() methods of ResultSetMetaData interface is used to get the number of columns and name of each column in the table.
Example 1:
Java
// Java Program to Use Methods of Column// to get column name in JDBC // Step 1: Importing DB filesimport java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.Statement; // Class to get columnspublic class GFG { // Main driver method public static void main(String args[]) { try { // Step 2: Loading and registering drivers // Loading driver class // using forName() method Class.forName("oracle.jdbc.OracleDriver"); // Step 3: Establishing te connection Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe", "username", "password"); Statement s = con.createStatement(); // Step 4: Create a statement String sql1 = "CREATE TABLE ACADEMY(COURSE_ID VARCHAR2(20) PRIMARY KEY, COURSE_NAME VARCHAR2(20),MENTOR VARCHAR2(20),COURSE_FEE NUMBER)"; // Step 5: Process the query // Inserting records in the table String sql2 = "INSERT INTO ACADEMY VALUES('C101','MATH','ROBERT',5000)"; String sql3 = "INSERT INTO ACADEMY VALUES('C102','PHYSICS','JANE',8000)"; String sql4 = "INSERT INTO ACADEMY VALUES('C103','HISTORY','ADAM',6000)"; String sql5 = "INSERT INTO ACADEMY VALUES('C104','BIOLOGY','MARIE',5000)"; String sql6 = "INSERT INTO ACADEMY VALUES('C105','ENGLISH','ALBERT',3000)"; s.addBatch(sql1); s.addBatch(sql2); s.addBatch(sql3); s.addBatch(sql4); s.addBatch(sql5); s.addBatch(sql6); // Step 6: Execute the statements // executing the sql commands s.executeBatch(); // Obtaining the resultset ResultSet rs = s.executeQuery("SELECT * FROM ACADEMY"); while (rs.next()) { System.out.println( rs.getString(1) + "\t\t" + rs.getString(2) + "\t\t" + rs.getString(3) + "\t\t" + rs.getString(4)); } // Retrieving the ResultSetMetadata object ResultSetMetaData rsMetaData = rs.getMetaData(); System.out.println( "List of column names in the current table: "); // Retrieving the list of column names int count = rsMetaData.getColumnCount(); for (int i = 1; i& lt; = count; i++) { System.out.print(rsMetaData.getColumnName(i) + "\t"); } // Step 7: Close the connection con.commit(); con.close(); } // Catch block to handle exceptions catch (Exception e) { // Print the exception System.out.println(e); } }}
Output:
Example 2:
Java
// Java Program to Use Methods of Column// to get column name in JDBC // Step 1: Importing DB filesimport java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.Statement; // Classpublic class GFG { // Main driver method public static void main(String args[]) { // Try block to check if exception occurs try { // Step 2: Loading and registering drivers // Loading driver class // using forName() method Class.forName("oracle.jdbc.OracleDriver"); // Step 3: Establish a connection // Create connection object Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe", "cse", "cse"); Statement s = con.createStatement(); // Step 4: Create a starement/s // create table String sql1 = "CREATE TABLE STUDENT(STUDENTID VARCHAR2(20) PRIMARY KEY, NAME VARCHAR2(20), DEPARTMENT VARCHAR2(10))"; // insert records in the table String sql2 = "INSERT INTO STUDENT VALUES('S001','JOE','CSE')"; String sql3 = "INSERT INTO STUDENT VALUES('S002','BECK','IT')"; String sql4 = "INSERT INTO STUDENT VALUES('S003','KANE','ECE')"; String sql5 = "INSERT INTO STUDENT VALUES('S004','FALLON','CSE')"; String sql6 = "INSERT INTO STUDENT VALUES('S005','LIAM','CSE')"; // Step 5: Execute the query s.addBatch(sql1); s.addBatch(sql2); s.addBatch(sql3); s.addBatch(sql4); s.addBatch(sql5); s.addBatch(sql6); // Executing the sql commands s.executeBatch(); // Obtaining the resultset ResultSet rs = s.executeQuery("SELECT * FROM STUDENT"); // Retrieving the ResultSetMetadata object ResultSetMetaData rsMetaData = rs.getMetaData(); // Retrieving the list of column names int count = rsMetaData.getColumnCount(); // Step 6: Process the statements for (int i = 1; i <= count; i++) { System.out.print(rsMetaData.getColumnName(i) + "\t"); } System.out.println( "\n----------------------------------------------------------------"); while (rs.next()) { System.out.println(rs.getString(1) + "\t\t" + rs.getString(2) + "\t" + rs.getString(3)); } // Step 7: Close the connection con.commit(); con.close(); } // Catch block to handle if exception occurs catch (Exception e) { // Print the exception System.out.println(e); } }}
Output:
akshaysingh98088
JDBC
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Jul, 2021"
},
{
"code": null,
"e": 608,
"s": 28,
"text": "Java Database Connectivity or JDBC is a Java API (application programming interface) used to perform database operations through Java application. It allows the execution of SQL commands for the creation of tables and data manipulation through Java application. Java supports java.sql package which contains inbuilt methods for accessing and processing data stored in a database. The methods in java.sql throw SQL exceptions hence the code block must be either placed within a try block and let the catch block handle exceptions if any else add throws clause to the main method. "
},
{
"code": null,
"e": 619,
"s": 608,
"text": "Procedure:"
},
{
"code": null,
"e": 1474,
"s": 619,
"text": "The forName() is a static method of class which is used to load the driver.Next the connection to the database is established using the getConnection() method of DriverManager class. The getConnection() accepts the URLs, username and password to establish a connection. The methods defined in the Statement interface is used to interact with the database.First, the table is created and then records are inserted into the table.The sql commands are batched together using addBatch() and executed all at once using executeBatch() method.The records in the table are fetched into the ResultSet.The getMetaData() method of ResultSet is used to get the metadata of the records fetched into the ResultSet.The getColumnCount() and getColumnName() methods of ResultSetMetaData interface is used to get the number of columns and name of each column in the table."
},
{
"code": null,
"e": 1550,
"s": 1474,
"text": "The forName() is a static method of class which is used to load the driver."
},
{
"code": null,
"e": 2330,
"s": 1550,
"text": "Next the connection to the database is established using the getConnection() method of DriverManager class. The getConnection() accepts the URLs, username and password to establish a connection. The methods defined in the Statement interface is used to interact with the database.First, the table is created and then records are inserted into the table.The sql commands are batched together using addBatch() and executed all at once using executeBatch() method.The records in the table are fetched into the ResultSet.The getMetaData() method of ResultSet is used to get the metadata of the records fetched into the ResultSet.The getColumnCount() and getColumnName() methods of ResultSetMetaData interface is used to get the number of columns and name of each column in the table."
},
{
"code": null,
"e": 2404,
"s": 2330,
"text": "First, the table is created and then records are inserted into the table."
},
{
"code": null,
"e": 2513,
"s": 2404,
"text": "The sql commands are batched together using addBatch() and executed all at once using executeBatch() method."
},
{
"code": null,
"e": 2570,
"s": 2513,
"text": "The records in the table are fetched into the ResultSet."
},
{
"code": null,
"e": 2679,
"s": 2570,
"text": "The getMetaData() method of ResultSet is used to get the metadata of the records fetched into the ResultSet."
},
{
"code": null,
"e": 2834,
"s": 2679,
"text": "The getColumnCount() and getColumnName() methods of ResultSetMetaData interface is used to get the number of columns and name of each column in the table."
},
{
"code": null,
"e": 2845,
"s": 2834,
"text": "Example 1:"
},
{
"code": null,
"e": 2850,
"s": 2845,
"text": "Java"
},
{
"code": "// Java Program to Use Methods of Column// to get column name in JDBC // Step 1: Importing DB filesimport java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.Statement; // Class to get columnspublic class GFG { // Main driver method public static void main(String args[]) { try { // Step 2: Loading and registering drivers // Loading driver class // using forName() method Class.forName(\"oracle.jdbc.OracleDriver\"); // Step 3: Establishing te connection Connection con = DriverManager.getConnection( \"jdbc:oracle:thin:@localhost:1521:xe\", \"username\", \"password\"); Statement s = con.createStatement(); // Step 4: Create a statement String sql1 = \"CREATE TABLE ACADEMY(COURSE_ID VARCHAR2(20) PRIMARY KEY, COURSE_NAME VARCHAR2(20),MENTOR VARCHAR2(20),COURSE_FEE NUMBER)\"; // Step 5: Process the query // Inserting records in the table String sql2 = \"INSERT INTO ACADEMY VALUES('C101','MATH','ROBERT',5000)\"; String sql3 = \"INSERT INTO ACADEMY VALUES('C102','PHYSICS','JANE',8000)\"; String sql4 = \"INSERT INTO ACADEMY VALUES('C103','HISTORY','ADAM',6000)\"; String sql5 = \"INSERT INTO ACADEMY VALUES('C104','BIOLOGY','MARIE',5000)\"; String sql6 = \"INSERT INTO ACADEMY VALUES('C105','ENGLISH','ALBERT',3000)\"; s.addBatch(sql1); s.addBatch(sql2); s.addBatch(sql3); s.addBatch(sql4); s.addBatch(sql5); s.addBatch(sql6); // Step 6: Execute the statements // executing the sql commands s.executeBatch(); // Obtaining the resultset ResultSet rs = s.executeQuery(\"SELECT * FROM ACADEMY\"); while (rs.next()) { System.out.println( rs.getString(1) + \"\\t\\t\" + rs.getString(2) + \"\\t\\t\" + rs.getString(3) + \"\\t\\t\" + rs.getString(4)); } // Retrieving the ResultSetMetadata object ResultSetMetaData rsMetaData = rs.getMetaData(); System.out.println( \"List of column names in the current table: \"); // Retrieving the list of column names int count = rsMetaData.getColumnCount(); for (int i = 1; i& lt; = count; i++) { System.out.print(rsMetaData.getColumnName(i) + \"\\t\"); } // Step 7: Close the connection con.commit(); con.close(); } // Catch block to handle exceptions catch (Exception e) { // Print the exception System.out.println(e); } }}",
"e": 5850,
"s": 2850,
"text": null
},
{
"code": null,
"e": 5859,
"s": 5850,
"text": "Output: "
},
{
"code": null,
"e": 5871,
"s": 5859,
"text": "Example 2: "
},
{
"code": null,
"e": 5876,
"s": 5871,
"text": "Java"
},
{
"code": "// Java Program to Use Methods of Column// to get column name in JDBC // Step 1: Importing DB filesimport java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.Statement; // Classpublic class GFG { // Main driver method public static void main(String args[]) { // Try block to check if exception occurs try { // Step 2: Loading and registering drivers // Loading driver class // using forName() method Class.forName(\"oracle.jdbc.OracleDriver\"); // Step 3: Establish a connection // Create connection object Connection con = DriverManager.getConnection( \"jdbc:oracle:thin:@localhost:1521:xe\", \"cse\", \"cse\"); Statement s = con.createStatement(); // Step 4: Create a starement/s // create table String sql1 = \"CREATE TABLE STUDENT(STUDENTID VARCHAR2(20) PRIMARY KEY, NAME VARCHAR2(20), DEPARTMENT VARCHAR2(10))\"; // insert records in the table String sql2 = \"INSERT INTO STUDENT VALUES('S001','JOE','CSE')\"; String sql3 = \"INSERT INTO STUDENT VALUES('S002','BECK','IT')\"; String sql4 = \"INSERT INTO STUDENT VALUES('S003','KANE','ECE')\"; String sql5 = \"INSERT INTO STUDENT VALUES('S004','FALLON','CSE')\"; String sql6 = \"INSERT INTO STUDENT VALUES('S005','LIAM','CSE')\"; // Step 5: Execute the query s.addBatch(sql1); s.addBatch(sql2); s.addBatch(sql3); s.addBatch(sql4); s.addBatch(sql5); s.addBatch(sql6); // Executing the sql commands s.executeBatch(); // Obtaining the resultset ResultSet rs = s.executeQuery(\"SELECT * FROM STUDENT\"); // Retrieving the ResultSetMetadata object ResultSetMetaData rsMetaData = rs.getMetaData(); // Retrieving the list of column names int count = rsMetaData.getColumnCount(); // Step 6: Process the statements for (int i = 1; i <= count; i++) { System.out.print(rsMetaData.getColumnName(i) + \"\\t\"); } System.out.println( \"\\n----------------------------------------------------------------\"); while (rs.next()) { System.out.println(rs.getString(1) + \"\\t\\t\" + rs.getString(2) + \"\\t\" + rs.getString(3)); } // Step 7: Close the connection con.commit(); con.close(); } // Catch block to handle if exception occurs catch (Exception e) { // Print the exception System.out.println(e); } }}",
"e": 8885,
"s": 5876,
"text": null
},
{
"code": null,
"e": 8894,
"s": 8885,
"text": "Output: "
},
{
"code": null,
"e": 8913,
"s": 8896,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 8918,
"s": 8913,
"text": "JDBC"
},
{
"code": null,
"e": 8925,
"s": 8918,
"text": "Picked"
},
{
"code": null,
"e": 8949,
"s": 8925,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 8954,
"s": 8949,
"text": "Java"
},
{
"code": null,
"e": 8968,
"s": 8954,
"text": "Java Programs"
},
{
"code": null,
"e": 8987,
"s": 8968,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8992,
"s": 8987,
"text": "Java"
}
] |
Generic Constructors and Interfaces in Java
|
28 Jan, 2021
Generics make a class, interface and, method, consider all (reference) types that are given dynamically as parameters. This ensures type safety. Generic class parameters are specified in angle brackets “<>” after the class name as of the instance variable.
Generic constructors are the same as generic methods. For generic constructors after the public keyword and before the class name the type parameter must be placed. Constructors can be invoked with any type of a parameter after defining a generic constructor. A constructor is a block of code that initializes the newly created object. It is an instance method with no return type. The name of the constructor is same as the class name. Constructors can be Generic, despite its class is not Generic.
Implementation:
Example
Java
// Java Program to illustrate Generic constructors // Importing input output classesimport java.io.*; // Class 1// Generic classclass GenericConstructor { // Member variable of this class private double v; // Constructor of this class where // T is typename and t is object <T extends Number> GenericConstructor(T t) { // Converting input number type to double // using the doubleValue() method v = t.doubleValue(); } // Method of this class void show() { // Print statement whenever method is called System.out.println("v: " + v); }} // Class 2 - Implementation class// Main classclass GFG { // Main driver method public static void main(String[] args) { // Display message System.out.println("Number to Double Conversion:"); // Creating objects of type GenericConstructor i.e // og above class and providing custom inputs to // constructor as parameters GenericConstructor obj1 = new GenericConstructor(10); GenericConstructor obj2 = new GenericConstructor(136.8F); // Calling method - show() on the objects // using the dot operator obj1.show(); obj2.show(); }}
Number to Double Conversion:
v: 10.0
v: 136.8000030517578
Output explanation: Here GenericConstructor() states a parameter of a generic type which is a subclass of Number. GenericConstructor() can be called with any numeric type like Integer, Float, or Double. So, in spite of GenericConstructor() is not a generic class, its constructor is generic.
Generic Interfaces in Java are the interfaces that deal with abstract data types. Interface help in the independent manipulation of java collections from representation details. They are used to achieving multiple inheritance in java forming hierarchies. They differ from the java class. These include all abstract methods only, have static and final variables only. The only reference can be created to interface, not objects, Unlike class, these don’t contain any constructors, instance variables. This involves the “implements” keyword. These are similar to generic classes.
The benefits of Generic Interface are as follows:
This is implemented for different data types.It allows putting constraints i.e. bounds on data types for which interface is implemented.
This is implemented for different data types.
It allows putting constraints i.e. bounds on data types for which interface is implemented.
Syntax:
interface interface-Name < type-parameter-list > {//....}
class class-name <type-parameter-list> implements interface-name <type-arguments-list> {//...}
Implementation: The following example creates an interface ‘MinMax’ which involves very basic methods such as min(), max() just in order to illustrate as they return the minimum and maximum values of given objects.
Example
Java
// Java Program to illustrate Generic interfaces // Importing java input output classesimport java.io.*; // An interface that extends Comparableinterface MinMax<T extends Comparable<T> > { // Declaring abstract methods // Method with no body is abstract method T min(); T max();} // Class 1 - Sub-class// class extending Comparable and implementing interfaceclass MyClass<T extends Comparable<T> > implements MinMax<T> { // Member variable of 'MyClass' class T[] values; // Constructor of 'MyClass' class MyClass(T[] obj) { values = obj; } // Now, defining min() and max() methods // for MimMax interface computation // Defining abstract min() method public T min() { // 'T' is typename and 'o1' is object_name T o1 = values[0]; // Iterating via for loop over elements using // length() method to get access of minimum element for (int i = 1; i < values.length; i++) if (values[i].compareTo(o1) < 0) o1 = values[i]; // Return the minimum element in an array return o1; } // Defining abstract max() method public T max() { // 'T' is typename and 'o1' is object_name T o1 = values[0]; // Iterating via for loop over elements using // length() method to get access of minimum element for (int i = 1; i < values.length; i++) if (values[i].compareTo(o1) > 0) o1 = values[i]; // Return the maximum element in an array return o1; }} // Class 2 - Main class// Implementation classclass GFG { // Main driver method public static void main(String[] args) { // Custom entries in an array Integer arr[] = { 3, 6, 2, 8, 6 }; // Create an object of type as that of above class // by declaring Integer type objects, and // passing above array to constructor MyClass<Integer> obj1 = new MyClass<Integer>(arr); // Calling min() and max() methods over object, and // printing the minimum value from array elements System.out.println("Minimum value: " + obj1.min()); // printing the maximum value from array elements System.out.println("Maximum value: " + obj1.max()); }}
Minimum value: 2
Maximum value: 8
Output explanation: Here interface is declared with type parameter T, and its upper bound is Comparable which is in java.lang. This states how objects are compared based on type of objects. Above T is declared by MyClass and further passed to MinMax as MinMax needs a type that implements Comparable and implementing class(MyClass) should have same bounds.
Note: Once a bound is established, it is not necessary to state it again in implements clause. If a class implements generic interface, then class must be generic so that it takes a type parameter passed to interface.
Java-Constructors
Java-Generics
java-interfaces
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jan, 2021"
},
{
"code": null,
"e": 311,
"s": 54,
"text": "Generics make a class, interface and, method, consider all (reference) types that are given dynamically as parameters. This ensures type safety. Generic class parameters are specified in angle brackets “<>” after the class name as of the instance variable."
},
{
"code": null,
"e": 813,
"s": 311,
"text": "Generic constructors are the same as generic methods. For generic constructors after the public keyword and before the class name the type parameter must be placed. Constructors can be invoked with any type of a parameter after defining a generic constructor. A constructor is a block of code that initializes the newly created object. It is an instance method with no return type. The name of the constructor is same as the class name. Constructors can be Generic, despite its class is not Generic. "
},
{
"code": null,
"e": 830,
"s": 813,
"text": "Implementation: "
},
{
"code": null,
"e": 838,
"s": 830,
"text": "Example"
},
{
"code": null,
"e": 843,
"s": 838,
"text": "Java"
},
{
"code": "// Java Program to illustrate Generic constructors // Importing input output classesimport java.io.*; // Class 1// Generic classclass GenericConstructor { // Member variable of this class private double v; // Constructor of this class where // T is typename and t is object <T extends Number> GenericConstructor(T t) { // Converting input number type to double // using the doubleValue() method v = t.doubleValue(); } // Method of this class void show() { // Print statement whenever method is called System.out.println(\"v: \" + v); }} // Class 2 - Implementation class// Main classclass GFG { // Main driver method public static void main(String[] args) { // Display message System.out.println(\"Number to Double Conversion:\"); // Creating objects of type GenericConstructor i.e // og above class and providing custom inputs to // constructor as parameters GenericConstructor obj1 = new GenericConstructor(10); GenericConstructor obj2 = new GenericConstructor(136.8F); // Calling method - show() on the objects // using the dot operator obj1.show(); obj2.show(); }}",
"e": 2098,
"s": 843,
"text": null
},
{
"code": null,
"e": 2156,
"s": 2098,
"text": "Number to Double Conversion:\nv: 10.0\nv: 136.8000030517578"
},
{
"code": null,
"e": 2448,
"s": 2156,
"text": "Output explanation: Here GenericConstructor() states a parameter of a generic type which is a subclass of Number. GenericConstructor() can be called with any numeric type like Integer, Float, or Double. So, in spite of GenericConstructor() is not a generic class, its constructor is generic."
},
{
"code": null,
"e": 3026,
"s": 2448,
"text": "Generic Interfaces in Java are the interfaces that deal with abstract data types. Interface help in the independent manipulation of java collections from representation details. They are used to achieving multiple inheritance in java forming hierarchies. They differ from the java class. These include all abstract methods only, have static and final variables only. The only reference can be created to interface, not objects, Unlike class, these don’t contain any constructors, instance variables. This involves the “implements” keyword. These are similar to generic classes."
},
{
"code": null,
"e": 3076,
"s": 3026,
"text": "The benefits of Generic Interface are as follows:"
},
{
"code": null,
"e": 3213,
"s": 3076,
"text": "This is implemented for different data types.It allows putting constraints i.e. bounds on data types for which interface is implemented."
},
{
"code": null,
"e": 3259,
"s": 3213,
"text": "This is implemented for different data types."
},
{
"code": null,
"e": 3351,
"s": 3259,
"text": "It allows putting constraints i.e. bounds on data types for which interface is implemented."
},
{
"code": null,
"e": 3359,
"s": 3351,
"text": "Syntax:"
},
{
"code": null,
"e": 3513,
"s": 3359,
"text": "interface interface-Name < type-parameter-list > {//....}\n\nclass class-name <type-parameter-list> implements interface-name <type-arguments-list> {//...}"
},
{
"code": null,
"e": 3728,
"s": 3513,
"text": "Implementation: The following example creates an interface ‘MinMax’ which involves very basic methods such as min(), max() just in order to illustrate as they return the minimum and maximum values of given objects."
},
{
"code": null,
"e": 3736,
"s": 3728,
"text": "Example"
},
{
"code": null,
"e": 3741,
"s": 3736,
"text": "Java"
},
{
"code": "// Java Program to illustrate Generic interfaces // Importing java input output classesimport java.io.*; // An interface that extends Comparableinterface MinMax<T extends Comparable<T> > { // Declaring abstract methods // Method with no body is abstract method T min(); T max();} // Class 1 - Sub-class// class extending Comparable and implementing interfaceclass MyClass<T extends Comparable<T> > implements MinMax<T> { // Member variable of 'MyClass' class T[] values; // Constructor of 'MyClass' class MyClass(T[] obj) { values = obj; } // Now, defining min() and max() methods // for MimMax interface computation // Defining abstract min() method public T min() { // 'T' is typename and 'o1' is object_name T o1 = values[0]; // Iterating via for loop over elements using // length() method to get access of minimum element for (int i = 1; i < values.length; i++) if (values[i].compareTo(o1) < 0) o1 = values[i]; // Return the minimum element in an array return o1; } // Defining abstract max() method public T max() { // 'T' is typename and 'o1' is object_name T o1 = values[0]; // Iterating via for loop over elements using // length() method to get access of minimum element for (int i = 1; i < values.length; i++) if (values[i].compareTo(o1) > 0) o1 = values[i]; // Return the maximum element in an array return o1; }} // Class 2 - Main class// Implementation classclass GFG { // Main driver method public static void main(String[] args) { // Custom entries in an array Integer arr[] = { 3, 6, 2, 8, 6 }; // Create an object of type as that of above class // by declaring Integer type objects, and // passing above array to constructor MyClass<Integer> obj1 = new MyClass<Integer>(arr); // Calling min() and max() methods over object, and // printing the minimum value from array elements System.out.println(\"Minimum value: \" + obj1.min()); // printing the maximum value from array elements System.out.println(\"Maximum value: \" + obj1.max()); }}",
"e": 6020,
"s": 3741,
"text": null
},
{
"code": null,
"e": 6054,
"s": 6020,
"text": "Minimum value: 2\nMaximum value: 8"
},
{
"code": null,
"e": 6413,
"s": 6054,
"text": "Output explanation: Here interface is declared with type parameter T, and its upper bound is Comparable which is in java.lang. This states how objects are compared based on type of objects. Above T is declared by MyClass and further passed to MinMax as MinMax needs a type that implements Comparable and implementing class(MyClass) should have same bounds. "
},
{
"code": null,
"e": 6631,
"s": 6413,
"text": "Note: Once a bound is established, it is not necessary to state it again in implements clause. If a class implements generic interface, then class must be generic so that it takes a type parameter passed to interface."
},
{
"code": null,
"e": 6649,
"s": 6631,
"text": "Java-Constructors"
},
{
"code": null,
"e": 6663,
"s": 6649,
"text": "Java-Generics"
},
{
"code": null,
"e": 6679,
"s": 6663,
"text": "java-interfaces"
},
{
"code": null,
"e": 6684,
"s": 6679,
"text": "Java"
},
{
"code": null,
"e": 6689,
"s": 6684,
"text": "Java"
}
] |
Synopsys Recruitment Process - GeeksforGeeks
|
28 Jun, 2021
About Company
Recruitment Process
Questions Asked in Synopsys
Interview Experiences
Where to Apply ?
Synopsys, Inc., an American company, is the leading company by sales in the Electronic Design Automation industry. Synopsys’ first and best-known product is Design Compiler, a logic-synthesis tool. Synopsys offers a wide range of other products used in the design of an application-specific integrated circuit. Products include logic synthesis, behavioral synthesis, place and route, static timing analysis, formal verification, hardware description language (SystemC, SystemVerilog/Verilog, VHDL) simulators as well as transistor-level circuit simulation. The simulators include development and debugging environments which assist in the design of the logic for chips and computer systems.
In 2016, Synopsys was placed at position #80 in Forbes’ list of America’s Best Employers. Also, placed at position #827 in 2016 and at position #909 in 2015 in Fortune 500 list. Know more about Synopsys
Synopsys conducts 5-8 rounds to select freshers as Software Engineer in their organisation.
Written Round
Technical Round 1
Technical Round 2
Technical Round 3
Technical Round 4
Technical Round 5
HR Round 1
HR Round 2
Academic Criteria :
75 percent or above in B.Tech, Class X and XII.
No backlogs at the time of interview
Online Round :Written round oftenly consists of questions Quantitative Aptitude, Logical Ability, C, C++, Algorithm, Data structures, Digital Design. To be prepared for aptitude section you can practice from our Placement Section.
Technical Rounds:The students who clear the written round are called for Technical Interview.To clear this round you should be clear with your basics. You should be prepared with Data structures and Algorithms, and C language. Students will be expected to write codes in the interview. They could also be ask questions from resume. You may be asked puzzles in this round. To be prepared for puzzles you can practice from our Puzzles section.
HR Round :You can expected general HR questions like :1. Tell me about Yourself2. Why Synopsys?3. What will you do if you get offer from Google/Facebook, etc ?4. What kind of culture do you want to work in?5. What are your strengths and weaknesses ?6. Questions form resume
Number of CoinsMerge Two Sorted ArraysExpression Tree (Function Problem)Operations on Binary Min Heap (Function Problem)Lowest Common Ancestor in a BST (Function Problem)Merge two sorted linked lists (Function Problem)Check for Balanced Tree (Function Problem)Height of Binary Tree (Function Problem)What is virtual path?What is virtual channel?more >>
Number of Coins
Merge Two Sorted Arrays
Expression Tree (Function Problem)
Operations on Binary Min Heap (Function Problem)
Lowest Common Ancestor in a BST (Function Problem)
Merge two sorted linked lists (Function Problem)
Check for Balanced Tree (Function Problem)
Height of Binary Tree (Function Problem)
What is virtual path?
What is virtual channel?
more >>
It is always beneficial if you know what it is to be there at that moment. So, to give you an advantage, we provide you Interview Experiences of candidates who have been in your situation earlier. Make the most of it.
Synopsys Interview Experiences
Synopsys careers
Synopsys Official Website
This article is contributed by Amit Khandelwal. 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.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
|
[
{
"code": null,
"e": 29498,
"s": 29470,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 29512,
"s": 29498,
"text": "About Company"
},
{
"code": null,
"e": 29532,
"s": 29512,
"text": "Recruitment Process"
},
{
"code": null,
"e": 29560,
"s": 29532,
"text": "Questions Asked in Synopsys"
},
{
"code": null,
"e": 29582,
"s": 29560,
"text": "Interview Experiences"
},
{
"code": null,
"e": 29599,
"s": 29582,
"text": "Where to Apply ?"
},
{
"code": null,
"e": 30290,
"s": 29599,
"text": "Synopsys, Inc., an American company, is the leading company by sales in the Electronic Design Automation industry. Synopsys’ first and best-known product is Design Compiler, a logic-synthesis tool. Synopsys offers a wide range of other products used in the design of an application-specific integrated circuit. Products include logic synthesis, behavioral synthesis, place and route, static timing analysis, formal verification, hardware description language (SystemC, SystemVerilog/Verilog, VHDL) simulators as well as transistor-level circuit simulation. The simulators include development and debugging environments which assist in the design of the logic for chips and computer systems."
},
{
"code": null,
"e": 30493,
"s": 30290,
"text": "In 2016, Synopsys was placed at position #80 in Forbes’ list of America’s Best Employers. Also, placed at position #827 in 2016 and at position #909 in 2015 in Fortune 500 list. Know more about Synopsys"
},
{
"code": null,
"e": 30585,
"s": 30493,
"text": "Synopsys conducts 5-8 rounds to select freshers as Software Engineer in their organisation."
},
{
"code": null,
"e": 30599,
"s": 30585,
"text": "Written Round"
},
{
"code": null,
"e": 30617,
"s": 30599,
"text": "Technical Round 1"
},
{
"code": null,
"e": 30635,
"s": 30617,
"text": "Technical Round 2"
},
{
"code": null,
"e": 30653,
"s": 30635,
"text": "Technical Round 3"
},
{
"code": null,
"e": 30671,
"s": 30653,
"text": "Technical Round 4"
},
{
"code": null,
"e": 30689,
"s": 30671,
"text": "Technical Round 5"
},
{
"code": null,
"e": 30700,
"s": 30689,
"text": "HR Round 1"
},
{
"code": null,
"e": 30711,
"s": 30700,
"text": "HR Round 2"
},
{
"code": null,
"e": 30731,
"s": 30711,
"text": "Academic Criteria :"
},
{
"code": null,
"e": 30779,
"s": 30731,
"text": "75 percent or above in B.Tech, Class X and XII."
},
{
"code": null,
"e": 30816,
"s": 30779,
"text": "No backlogs at the time of interview"
},
{
"code": null,
"e": 31047,
"s": 30816,
"text": "Online Round :Written round oftenly consists of questions Quantitative Aptitude, Logical Ability, C, C++, Algorithm, Data structures, Digital Design. To be prepared for aptitude section you can practice from our Placement Section."
},
{
"code": null,
"e": 31489,
"s": 31047,
"text": "Technical Rounds:The students who clear the written round are called for Technical Interview.To clear this round you should be clear with your basics. You should be prepared with Data structures and Algorithms, and C language. Students will be expected to write codes in the interview. They could also be ask questions from resume. You may be asked puzzles in this round. To be prepared for puzzles you can practice from our Puzzles section."
},
{
"code": null,
"e": 31763,
"s": 31489,
"text": "HR Round :You can expected general HR questions like :1. Tell me about Yourself2. Why Synopsys?3. What will you do if you get offer from Google/Facebook, etc ?4. What kind of culture do you want to work in?5. What are your strengths and weaknesses ?6. Questions form resume"
},
{
"code": null,
"e": 32116,
"s": 31763,
"text": "Number of CoinsMerge Two Sorted ArraysExpression Tree (Function Problem)Operations on Binary Min Heap (Function Problem)Lowest Common Ancestor in a BST (Function Problem)Merge two sorted linked lists (Function Problem)Check for Balanced Tree (Function Problem)Height of Binary Tree (Function Problem)What is virtual path?What is virtual channel?more >>"
},
{
"code": null,
"e": 32132,
"s": 32116,
"text": "Number of Coins"
},
{
"code": null,
"e": 32156,
"s": 32132,
"text": "Merge Two Sorted Arrays"
},
{
"code": null,
"e": 32191,
"s": 32156,
"text": "Expression Tree (Function Problem)"
},
{
"code": null,
"e": 32240,
"s": 32191,
"text": "Operations on Binary Min Heap (Function Problem)"
},
{
"code": null,
"e": 32291,
"s": 32240,
"text": "Lowest Common Ancestor in a BST (Function Problem)"
},
{
"code": null,
"e": 32340,
"s": 32291,
"text": "Merge two sorted linked lists (Function Problem)"
},
{
"code": null,
"e": 32383,
"s": 32340,
"text": "Check for Balanced Tree (Function Problem)"
},
{
"code": null,
"e": 32424,
"s": 32383,
"text": "Height of Binary Tree (Function Problem)"
},
{
"code": null,
"e": 32446,
"s": 32424,
"text": "What is virtual path?"
},
{
"code": null,
"e": 32471,
"s": 32446,
"text": "What is virtual channel?"
},
{
"code": null,
"e": 32479,
"s": 32471,
"text": "more >>"
},
{
"code": null,
"e": 32697,
"s": 32479,
"text": "It is always beneficial if you know what it is to be there at that moment. So, to give you an advantage, we provide you Interview Experiences of candidates who have been in your situation earlier. Make the most of it."
},
{
"code": null,
"e": 32728,
"s": 32697,
"text": "Synopsys Interview Experiences"
},
{
"code": null,
"e": 32745,
"s": 32728,
"text": "Synopsys careers"
},
{
"code": null,
"e": 32771,
"s": 32745,
"text": "Synopsys Official Website"
},
{
"code": null,
"e": 33070,
"s": 32771,
"text": "This article is contributed by Amit Khandelwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 33195,
"s": 33070,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
}
] |
Python | Pandas Series.str.extract()
|
27 Mar, 2019
Series.str can be used to access the values of the series as strings and apply several methods to it. Pandas Series.str.extract() function is used to extract capture groups in the regex pat as columns in a DataFrame. For each subject string in the Series, extract groups from the first match of regular expression pat.
Syntax: Series.str.extract(pat, flags=0, expand=True)
Parameter :pat : Regular expression pattern with capturing groups.flags : int, default 0 (no flags)expand : If True, return DataFrame with one column per capture group.
Returns : DataFrame or Series or Index
Example #1: Use Series.str.extract() function to extract groups from the string in the underlying data of the given series object.
# importing pandas as pdimport pandas as pd # importing re for regular expressionsimport re # Creating the Seriessr = pd.Series(['New_York', 'Lisbon', 'Tokyo', 'Paris', 'Munich']) # Creating the indexidx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = idx # Print the seriesprint(sr)
Output :
Now we will use Series.str.extract() function to extract groups from the strings in the given series object.
# extract groups having a vowel followed by# any characterresult = sr.str.extract(pat = '([aeiou].)') # print the resultprint(result)
Output :
As we can see in the output, the Series.str.extract() function has returned a dataframe containing a column of the extracted group.
Example #2 : Use Series.str.extract() function to extract groups from the string in the underlying data of the given series object.
# importing pandas as pdimport pandas as pd # importing re for regular expressionsimport re # Creating the Seriessr = pd.Series(['Mike', 'Alessa', 'Nick', 'Kim', 'Britney']) # Creating the indexidx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5'] # set the indexsr.index = idx # Print the seriesprint(sr)
Output :
Now we will use Series.str.extract() function to extract groups from the strings in the given series object.
# extract groups having any capital letter# followed by 'i' and any other characterresult = sr.str.extract(pat = '([A-Z]i.)') # print the resultprint(result)
Output :
As we can see in the output, the Series.str.extract() function has returned a dataframe containing a column of the extracted group.
Python-pandas
Python-pandas-series-str
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Mar, 2019"
},
{
"code": null,
"e": 347,
"s": 28,
"text": "Series.str can be used to access the values of the series as strings and apply several methods to it. Pandas Series.str.extract() function is used to extract capture groups in the regex pat as columns in a DataFrame. For each subject string in the Series, extract groups from the first match of regular expression pat."
},
{
"code": null,
"e": 401,
"s": 347,
"text": "Syntax: Series.str.extract(pat, flags=0, expand=True)"
},
{
"code": null,
"e": 570,
"s": 401,
"text": "Parameter :pat : Regular expression pattern with capturing groups.flags : int, default 0 (no flags)expand : If True, return DataFrame with one column per capture group."
},
{
"code": null,
"e": 609,
"s": 570,
"text": "Returns : DataFrame or Series or Index"
},
{
"code": null,
"e": 740,
"s": 609,
"text": "Example #1: Use Series.str.extract() function to extract groups from the string in the underlying data of the given series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # importing re for regular expressionsimport re # Creating the Seriessr = pd.Series(['New_York', 'Lisbon', 'Tokyo', 'Paris', 'Munich']) # Creating the indexidx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = idx # Print the seriesprint(sr)",
"e": 1060,
"s": 740,
"text": null
},
{
"code": null,
"e": 1069,
"s": 1060,
"text": "Output :"
},
{
"code": null,
"e": 1178,
"s": 1069,
"text": "Now we will use Series.str.extract() function to extract groups from the strings in the given series object."
},
{
"code": "# extract groups having a vowel followed by# any characterresult = sr.str.extract(pat = '([aeiou].)') # print the resultprint(result)",
"e": 1313,
"s": 1178,
"text": null
},
{
"code": null,
"e": 1322,
"s": 1313,
"text": "Output :"
},
{
"code": null,
"e": 1454,
"s": 1322,
"text": "As we can see in the output, the Series.str.extract() function has returned a dataframe containing a column of the extracted group."
},
{
"code": null,
"e": 1586,
"s": 1454,
"text": "Example #2 : Use Series.str.extract() function to extract groups from the string in the underlying data of the given series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # importing re for regular expressionsimport re # Creating the Seriessr = pd.Series(['Mike', 'Alessa', 'Nick', 'Kim', 'Britney']) # Creating the indexidx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5'] # set the indexsr.index = idx # Print the seriesprint(sr)",
"e": 1900,
"s": 1586,
"text": null
},
{
"code": null,
"e": 1909,
"s": 1900,
"text": "Output :"
},
{
"code": null,
"e": 2018,
"s": 1909,
"text": "Now we will use Series.str.extract() function to extract groups from the strings in the given series object."
},
{
"code": "# extract groups having any capital letter# followed by 'i' and any other characterresult = sr.str.extract(pat = '([A-Z]i.)') # print the resultprint(result)",
"e": 2177,
"s": 2018,
"text": null
},
{
"code": null,
"e": 2186,
"s": 2177,
"text": "Output :"
},
{
"code": null,
"e": 2318,
"s": 2186,
"text": "As we can see in the output, the Series.str.extract() function has returned a dataframe containing a column of the extracted group."
},
{
"code": null,
"e": 2332,
"s": 2318,
"text": "Python-pandas"
},
{
"code": null,
"e": 2357,
"s": 2332,
"text": "Python-pandas-series-str"
},
{
"code": null,
"e": 2364,
"s": 2357,
"text": "Python"
}
] |
Objects in Javascript
|
10 Jun, 2022
Objects, in JavaScript, is the most important data-type and forms the building blocks for modern JavaScript. These objects are quite different from JavaScript’s primitive data-types(Number, String, Boolean, null, undefined and symbol) in the sense that while these primitive data-types all store a single value each (depending on their types).
Objects are more complex and each object may contain any combination of these primitive data-types as well as reference data-types.
An object, is a reference data type. Variables that are assigned a reference value are given a reference or a pointer to that value. That reference or pointer points to the location in memory where the object is stored. The variables don’t actually store the value.
Loosely speaking, objects in JavaScript may be defined as an unordered collection of related data, of primitive or reference types, in the form of “key: value” pairs. These keys can be variables or functions and are called properties and methods, respectively, in the context of an object.
An object can be created with figure brackets {...} with an optional list of properties. A property is a “key: value” pair, where a key is a string (also called a “property name”), and value can be anything. Let us visualize this with the following syntax for creating an object in JavaScript.
Syntax:
let object_name = {
key_name : value,
...
}
Now after understanding and visualizing the object creation syntax, let us look at an example of a JavaScript Object below :
let school = {
name : "Vivekananda School",
location : "Delhi",
established : "1971"
}
In the above example “name”, “location”, “established” are all “keys” and “Vivekananda School”, “Delhi” and 1971 are values of these keys respectively. Each of these keys is referred to as properties of the object. An object in JavaScript may also have a function as a member, in which case it will be known as a method of that object. Let us see such an example :
javascript
// javascript code demonstrating a simple objectlet school = { name: 'Vivekananda School', location : 'Delhi', established : '1971', displayInfo : function(){ console.log(`${school.name} was established in ${school.established} at ${school.location}`); }}school.displayInfo();
Output: In the above example, “displayinfo” is a method of the school object that is being used to work with the object’s data, stored in its properties.
Properties of JavaScript Object
The property names can be strings or numbers. In case the property names are numbers, they must be accessed using the “bracket notation” like this :
javascript
let school = { name: 'Vivekananda School', location : 'Delhi', established : '1971', 20 : 1000, displayInfo : function(){ console.log(`The value of the key 20 is ${school['20']}`); }}school.displayInfo();
Output: But more on the bracket notation later. Property names can also be strings with more than one space separated words. In which case, these property names must be enclosed in quotes :
let school = {
"school name" : "Vivekananda School",
}
Like property names which are numbers, they must also be accessed using the bracket notation. Like if we want to access the ‘Vivekananda’ from ‘Vivekananda School’ we can do something like this:
javascript
// bracket notationlet school = { name: 'Vivekananda School', displayInfo : function(){ console.log(`${school.name.split(' ')[0]}`); }}school.displayInfo(); // Vivekananda
Output: In the above code, we made use of bracket notation and also split method provided by JavaScript which you will learn about in strings article.
Inherited Properties
Inherited properties of an object are those properties which have been inherited from the object’s prototype, as opposed to being defined for the object itself, which is known as the object’s Own property. To verify if a property is an objects Own property, we can use the hasOwnProperty method. Property Attributes Data properties in JavaScript have four attributes.
value: The property’s value.
writable: When true, the property’s value can be changed
enumerable: When true, the property can be iterated over by “for-in” enumeration. Otherwise, the property is said to be non-enumerable.
configurable: If false, attempts to delete the property, change the property to be an access-or property, or change its attributes (other than [[Value]], or changing [[Writable]] to false) will fail.
javascript
// hasOwnProperty code in jsconst object1 = new Object();object1.property1 = 42; console.log(object1.hasOwnProperty('property1')); // true
Output:
Creating Objects
There are several ways or syntax’s to create objects. One of which, known as the Object literal syntax, we have already used. Besides the object literal syntax, objects in JavaScript may also be created using the constructors, Object Constructor or the prototype pattern.
Using the Object literal syntax : Object literal syntax uses the {...} notation to initialize an object an its methods/properties directly. Let us look at an example of creating objects using this method :
Using the Object literal syntax : Object literal syntax uses the {...} notation to initialize an object an its methods/properties directly. Let us look at an example of creating objects using this method :
var obj = {
member1 : value1,
member2 : value2,
};
These members can be anything – strings, numbers, functions, arrays or even other objects. An object like this is referred to as an object literal. This is different from other methods of object creation which involve using constructors and classes or prototypes, which have been discussed below.Object Constructor : Another way to create objects in JavaScript involves using the “Object” constructor. The Object constructor creates an object wrapper for the given value. This, used in conjunction with the “new” keyword allows us to initialize new objects. Example :
These members can be anything – strings, numbers, functions, arrays or even other objects. An object like this is referred to as an object literal. This is different from other methods of object creation which involve using constructors and classes or prototypes, which have been discussed below.
Object Constructor : Another way to create objects in JavaScript involves using the “Object” constructor. The Object constructor creates an object wrapper for the given value. This, used in conjunction with the “new” keyword allows us to initialize new objects. Example :
javascript
const school = new Object();school.name = 'Vivekanada school';school.location = 'Delhi';school.established = 1971; school.displayInfo = function(){ console.log(`${school.name} was established in ${school.established} at ${school.location}`);} school.displayInfo();
Output: The two methods mentioned above are not well suited to programs that require the creation of multiple objects of the same kind, as it would involve repeatedly writing the above lines of code for each such object. To deal with this problem, we can make use of two other methods of object creation in JavaScript that reduces this burden significantly, as mentioned below:Constructors: Constructors in JavaScript, like in most other OOP languages, provides a template for creation of objects. In other words, it defines a set of properties and methods that would be common to all objects initialized using the constructor. Let us see an example :
Output: The two methods mentioned above are not well suited to programs that require the creation of multiple objects of the same kind, as it would involve repeatedly writing the above lines of code for each such object. To deal with this problem, we can make use of two other methods of object creation in JavaScript that reduces this burden significantly, as mentioned below:
Constructors: Constructors in JavaScript, like in most other OOP languages, provides a template for creation of objects. In other words, it defines a set of properties and methods that would be common to all objects initialized using the constructor. Let us see an example :
javascript
function Vehicle(name, maker) { this.name = name; this.maker = maker;} let car1 = new Vehicle('Fiesta', 'Ford');let car2 = new Vehicle('Santa Fe', 'Hyundai') console.log(car1.name); // Output: Fiestaconsole.log(car2.name); // Output: Santa Fe
Output: Notice the usage of the “new” keyword before the function Vehicle. Using the “new” keyword in this manner before any function turns it into a constructor. What the “new Vehicle()” actually does is :It creates a new object and sets the constructor property of the object to schools (It is important to note that this property is a special default property that is not enumerable and cannot be changed by setting a “constructor: someFunction” property manually).Then, it sets up the object to work with the Vehicle function’s prototype object ( Each function in JavaScript gets a prototype object, which is initially just an empty object but can be modified.The object, when instantiated inherits all properties from its constructor’s prototype object).Then calls Vehicle() in the context of the new object, which means that when the “this” keyword is encountered in the constructor(vehicle()), it refers to the new object that was created in the first step.Once this is finished, the newly created object is returned to car1 and car2(in the above example).Prototypes : Another way to create objects involves using prototypes. Every JavaScript function has a prototype object property by default(it is empty by default). Methods or properties may be attached to this property. A detailed description of prototypes is beyond the scope of this introduction to objects. However you may familiarize yourself with the basic syntax used as below:
Output: Notice the usage of the “new” keyword before the function Vehicle. Using the “new” keyword in this manner before any function turns it into a constructor. What the “new Vehicle()” actually does is :It creates a new object and sets the constructor property of the object to schools (It is important to note that this property is a special default property that is not enumerable and cannot be changed by setting a “constructor: someFunction” property manually).Then, it sets up the object to work with the Vehicle function’s prototype object ( Each function in JavaScript gets a prototype object, which is initially just an empty object but can be modified.The object, when instantiated inherits all properties from its constructor’s prototype object).Then calls Vehicle() in the context of the new object, which means that when the “this” keyword is encountered in the constructor(vehicle()), it refers to the new object that was created in the first step.Once this is finished, the newly created object is returned to car1 and car2(in the above example).
It creates a new object and sets the constructor property of the object to schools (It is important to note that this property is a special default property that is not enumerable and cannot be changed by setting a “constructor: someFunction” property manually).
Then, it sets up the object to work with the Vehicle function’s prototype object ( Each function in JavaScript gets a prototype object, which is initially just an empty object but can be modified.The object, when instantiated inherits all properties from its constructor’s prototype object).
Then calls Vehicle() in the context of the new object, which means that when the “this” keyword is encountered in the constructor(vehicle()), it refers to the new object that was created in the first step.
Once this is finished, the newly created object is returned to car1 and car2(in the above example).
Prototypes : Another way to create objects involves using prototypes. Every JavaScript function has a prototype object property by default(it is empty by default). Methods or properties may be attached to this property. A detailed description of prototypes is beyond the scope of this introduction to objects. However you may familiarize yourself with the basic syntax used as below:
let obj = Object.create(prototype_object, propertiesObject)
// the second propertiesObject argument is optional
An example of making use of the Object.create() method is:
An example of making use of the Object.create() method is:
javascript
let footballers = { position: "Striker"} let footballer1 = Object.create(footballers); // Output : Striker console.log(footballer1.position);
Output: In the above example footballers served as a prototype for creating the object “footballer1”. All objects created in this way inherits all properties and methods from its prototype objects. Prototypes can have prototypes and those can have prototypes and so on. This is referred to as prototype chaining in JavaScript. This chain terminates with the Object.prototype which is the default prototype fallback for all objects. JavaScript objects, by default, inherit properties and methods from Object.prototype but these may easily be overridden. It is also interesting to note that the default prototype is not always Object.prototype.For example Strings and Arrays have their own default prototypes – String.prototype and Array.prototype respectively.
Output: In the above example footballers served as a prototype for creating the object “footballer1”. All objects created in this way inherits all properties and methods from its prototype objects. Prototypes can have prototypes and those can have prototypes and so on. This is referred to as prototype chaining in JavaScript. This chain terminates with the Object.prototype which is the default prototype fallback for all objects. JavaScript objects, by default, inherit properties and methods from Object.prototype but these may easily be overridden. It is also interesting to note that the default prototype is not always Object.prototype.For example Strings and Arrays have their own default prototypes – String.prototype and Array.prototype respectively.
Accessing Object Members
Object members(properties or methods) can be accessed using the :
dot notation :
dot notation :
(objectName.memberName)
javascript
let school = { name : "Vivekanada", location : "Delhi", established : 1971, 20 : 1000, displayinfo : function() { console.log(`${school.name} was established in ${school.established} at ${school.location}`); } } console.log(school.name); console.log(school.established);
Output: Bracket Notation :
Output:
Bracket Notation :
objectName["memberName"]
javascript
let school = { name : "Vivekanada School", location : "Delhi", established : 1995, 20 : 1000, displayinfo : function() { document.write(`${school.name} was established in ${school.established} at ${school.location}`); }} // Output : Vivekanada Schoolconsole.log(school['name']); // Output: 1000console.log(school['20']);
Output:
Output:
Unlike the dot notation, the bracket keyword works with any string combination, including, but not limited to multi-word strings. For example:
somePerson.first name // invalid
somePerson["first name"] // valid
Unlike the dot notation, the bracket notation can also contain names which are results of any expressions variables whose values are computed at run-time. For instance :
let key = "first name" somePerson[key] = "Name Surname"
Similar operations are not possible while using the dot notation.
Iterating over all keys of an object
To iterate over all existing enumerable keys of an object, we may use the for...in construct. It is worth noting that this allows us to access only those properties of an object which are enumerable (Recall that enumerable is one of the four attributes of data properties). For instance, properties inherited from the Object.prototype are not enumerable. But, enumerable properties inherited from somewhere can also be accessed using the for...in construct Example:
javascript
let person = { gender : "male"} var person1 = Object.create(person);person1.name = "Adam";person1.age = 45;person1.nationality = "Australian"; for (let key in person1) {// Output : name, age, nationality// and gender console.log(key);}
Output:
Deleting Properties
To Delete a property of an object we can make use of the delete operator. An example of its usage has been listed below:
javascript
let obj1 = { propfirst : "Name"} // Output : Nameconsole.log(obj1.propfirst);delete obj1.propfirst // Output : undefinedconsole.log(obj1.propfirst);
Output: It is important to note that we can not delete inherited properties or non-configurable properties in this manner. For example :
javascript
let obj1 = { propfirst : "Name"}// Output : Nameconsole.log(obj1.propfirst) let obj2 = Object.create(obj1); // Output : Name console.log(obj2.propfirst); // Output : true. console.log(delete obj2.propfirst); // Surprisingly Note that this will return true // regardless of whether the deletion was successful // Output : Name console.log(obj2.propfirst);
Output:
Supported Browsers:
Google Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Opera 3 and above
Safari 1 and above
Internet Explorer 3 and above
immukul
kumargaurav97520
amansingla
javascript-basics
javascript-oop
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Jun, 2022"
},
{
"code": null,
"e": 396,
"s": 52,
"text": "Objects, in JavaScript, is the most important data-type and forms the building blocks for modern JavaScript. These objects are quite different from JavaScript’s primitive data-types(Number, String, Boolean, null, undefined and symbol) in the sense that while these primitive data-types all store a single value each (depending on their types)."
},
{
"code": null,
"e": 528,
"s": 396,
"text": "Objects are more complex and each object may contain any combination of these primitive data-types as well as reference data-types."
},
{
"code": null,
"e": 794,
"s": 528,
"text": "An object, is a reference data type. Variables that are assigned a reference value are given a reference or a pointer to that value. That reference or pointer points to the location in memory where the object is stored. The variables don’t actually store the value."
},
{
"code": null,
"e": 1084,
"s": 794,
"text": "Loosely speaking, objects in JavaScript may be defined as an unordered collection of related data, of primitive or reference types, in the form of “key: value” pairs. These keys can be variables or functions and are called properties and methods, respectively, in the context of an object."
},
{
"code": null,
"e": 1378,
"s": 1084,
"text": "An object can be created with figure brackets {...} with an optional list of properties. A property is a “key: value” pair, where a key is a string (also called a “property name”), and value can be anything. Let us visualize this with the following syntax for creating an object in JavaScript."
},
{
"code": null,
"e": 1386,
"s": 1378,
"text": "Syntax:"
},
{
"code": null,
"e": 1438,
"s": 1386,
"text": "let object_name = {\n key_name : value,\n ...\n}"
},
{
"code": null,
"e": 1563,
"s": 1438,
"text": "Now after understanding and visualizing the object creation syntax, let us look at an example of a JavaScript Object below :"
},
{
"code": null,
"e": 1662,
"s": 1563,
"text": "let school = {\n name : \"Vivekananda School\",\n location : \"Delhi\",\n established : \"1971\"\n}"
},
{
"code": null,
"e": 2028,
"s": 1662,
"text": "In the above example “name”, “location”, “established” are all “keys” and “Vivekananda School”, “Delhi” and 1971 are values of these keys respectively. Each of these keys is referred to as properties of the object. An object in JavaScript may also have a function as a member, in which case it will be known as a method of that object. Let us see such an example : "
},
{
"code": null,
"e": 2039,
"s": 2028,
"text": "javascript"
},
{
"code": "// javascript code demonstrating a simple objectlet school = { name: 'Vivekananda School', location : 'Delhi', established : '1971', displayInfo : function(){ console.log(`${school.name} was established in ${school.established} at ${school.location}`); }}school.displayInfo(); ",
"e": 2353,
"s": 2039,
"text": null
},
{
"code": null,
"e": 2508,
"s": 2353,
"text": "Output: In the above example, “displayinfo” is a method of the school object that is being used to work with the object’s data, stored in its properties."
},
{
"code": null,
"e": 2540,
"s": 2508,
"text": "Properties of JavaScript Object"
},
{
"code": null,
"e": 2690,
"s": 2540,
"text": "The property names can be strings or numbers. In case the property names are numbers, they must be accessed using the “bracket notation” like this : "
},
{
"code": null,
"e": 2701,
"s": 2690,
"text": "javascript"
},
{
"code": "let school = { name: 'Vivekananda School', location : 'Delhi', established : '1971', 20 : 1000, displayInfo : function(){ console.log(`The value of the key 20 is ${school['20']}`); }}school.displayInfo(); ",
"e": 2933,
"s": 2701,
"text": null
},
{
"code": null,
"e": 3124,
"s": 2933,
"text": "Output: But more on the bracket notation later. Property names can also be strings with more than one space separated words. In which case, these property names must be enclosed in quotes :"
},
{
"code": null,
"e": 3183,
"s": 3124,
"text": "let school = {\n \"school name\" : \"Vivekananda School\",\n}"
},
{
"code": null,
"e": 3379,
"s": 3183,
"text": "Like property names which are numbers, they must also be accessed using the bracket notation. Like if we want to access the ‘Vivekananda’ from ‘Vivekananda School’ we can do something like this: "
},
{
"code": null,
"e": 3390,
"s": 3379,
"text": "javascript"
},
{
"code": "// bracket notationlet school = { name: 'Vivekananda School', displayInfo : function(){ console.log(`${school.name.split(' ')[0]}`); }}school.displayInfo(); // Vivekananda",
"e": 3578,
"s": 3390,
"text": null
},
{
"code": null,
"e": 3730,
"s": 3578,
"text": "Output: In the above code, we made use of bracket notation and also split method provided by JavaScript which you will learn about in strings article."
},
{
"code": null,
"e": 3751,
"s": 3730,
"text": "Inherited Properties"
},
{
"code": null,
"e": 4119,
"s": 3751,
"text": "Inherited properties of an object are those properties which have been inherited from the object’s prototype, as opposed to being defined for the object itself, which is known as the object’s Own property. To verify if a property is an objects Own property, we can use the hasOwnProperty method. Property Attributes Data properties in JavaScript have four attributes."
},
{
"code": null,
"e": 4148,
"s": 4119,
"text": "value: The property’s value."
},
{
"code": null,
"e": 4205,
"s": 4148,
"text": "writable: When true, the property’s value can be changed"
},
{
"code": null,
"e": 4341,
"s": 4205,
"text": "enumerable: When true, the property can be iterated over by “for-in” enumeration. Otherwise, the property is said to be non-enumerable."
},
{
"code": null,
"e": 4541,
"s": 4341,
"text": "configurable: If false, attempts to delete the property, change the property to be an access-or property, or change its attributes (other than [[Value]], or changing [[Writable]] to false) will fail."
},
{
"code": null,
"e": 4552,
"s": 4541,
"text": "javascript"
},
{
"code": "// hasOwnProperty code in jsconst object1 = new Object();object1.property1 = 42; console.log(object1.hasOwnProperty('property1')); // true",
"e": 4691,
"s": 4552,
"text": null
},
{
"code": null,
"e": 4700,
"s": 4691,
"text": "Output: "
},
{
"code": null,
"e": 4717,
"s": 4700,
"text": "Creating Objects"
},
{
"code": null,
"e": 4989,
"s": 4717,
"text": "There are several ways or syntax’s to create objects. One of which, known as the Object literal syntax, we have already used. Besides the object literal syntax, objects in JavaScript may also be created using the constructors, Object Constructor or the prototype pattern."
},
{
"code": null,
"e": 5195,
"s": 4989,
"text": "Using the Object literal syntax : Object literal syntax uses the {...} notation to initialize an object an its methods/properties directly. Let us look at an example of creating objects using this method :"
},
{
"code": null,
"e": 5401,
"s": 5195,
"text": "Using the Object literal syntax : Object literal syntax uses the {...} notation to initialize an object an its methods/properties directly. Let us look at an example of creating objects using this method :"
},
{
"code": null,
"e": 5460,
"s": 5401,
"text": "var obj = {\n member1 : value1,\n member2 : value2,\n};"
},
{
"code": null,
"e": 6029,
"s": 5460,
"text": "These members can be anything – strings, numbers, functions, arrays or even other objects. An object like this is referred to as an object literal. This is different from other methods of object creation which involve using constructors and classes or prototypes, which have been discussed below.Object Constructor : Another way to create objects in JavaScript involves using the “Object” constructor. The Object constructor creates an object wrapper for the given value. This, used in conjunction with the “new” keyword allows us to initialize new objects. Example : "
},
{
"code": null,
"e": 6326,
"s": 6029,
"text": "These members can be anything – strings, numbers, functions, arrays or even other objects. An object like this is referred to as an object literal. This is different from other methods of object creation which involve using constructors and classes or prototypes, which have been discussed below."
},
{
"code": null,
"e": 6599,
"s": 6326,
"text": "Object Constructor : Another way to create objects in JavaScript involves using the “Object” constructor. The Object constructor creates an object wrapper for the given value. This, used in conjunction with the “new” keyword allows us to initialize new objects. Example : "
},
{
"code": null,
"e": 6610,
"s": 6599,
"text": "javascript"
},
{
"code": "const school = new Object();school.name = 'Vivekanada school';school.location = 'Delhi';school.established = 1971; school.displayInfo = function(){ console.log(`${school.name} was established in ${school.established} at ${school.location}`);} school.displayInfo();",
"e": 6887,
"s": 6610,
"text": null
},
{
"code": null,
"e": 7541,
"s": 6887,
"text": "Output: The two methods mentioned above are not well suited to programs that require the creation of multiple objects of the same kind, as it would involve repeatedly writing the above lines of code for each such object. To deal with this problem, we can make use of two other methods of object creation in JavaScript that reduces this burden significantly, as mentioned below:Constructors: Constructors in JavaScript, like in most other OOP languages, provides a template for creation of objects. In other words, it defines a set of properties and methods that would be common to all objects initialized using the constructor. Let us see an example : "
},
{
"code": null,
"e": 7920,
"s": 7541,
"text": "Output: The two methods mentioned above are not well suited to programs that require the creation of multiple objects of the same kind, as it would involve repeatedly writing the above lines of code for each such object. To deal with this problem, we can make use of two other methods of object creation in JavaScript that reduces this burden significantly, as mentioned below:"
},
{
"code": null,
"e": 8196,
"s": 7920,
"text": "Constructors: Constructors in JavaScript, like in most other OOP languages, provides a template for creation of objects. In other words, it defines a set of properties and methods that would be common to all objects initialized using the constructor. Let us see an example : "
},
{
"code": null,
"e": 8207,
"s": 8196,
"text": "javascript"
},
{
"code": "function Vehicle(name, maker) { this.name = name; this.maker = maker;} let car1 = new Vehicle('Fiesta', 'Ford');let car2 = new Vehicle('Santa Fe', 'Hyundai') console.log(car1.name); // Output: Fiestaconsole.log(car2.name); // Output: Santa Fe",
"e": 8460,
"s": 8207,
"text": null
},
{
"code": null,
"e": 9908,
"s": 8460,
"text": "Output: Notice the usage of the “new” keyword before the function Vehicle. Using the “new” keyword in this manner before any function turns it into a constructor. What the “new Vehicle()” actually does is :It creates a new object and sets the constructor property of the object to schools (It is important to note that this property is a special default property that is not enumerable and cannot be changed by setting a “constructor: someFunction” property manually).Then, it sets up the object to work with the Vehicle function’s prototype object ( Each function in JavaScript gets a prototype object, which is initially just an empty object but can be modified.The object, when instantiated inherits all properties from its constructor’s prototype object).Then calls Vehicle() in the context of the new object, which means that when the “this” keyword is encountered in the constructor(vehicle()), it refers to the new object that was created in the first step.Once this is finished, the newly created object is returned to car1 and car2(in the above example).Prototypes : Another way to create objects involves using prototypes. Every JavaScript function has a prototype object property by default(it is empty by default). Methods or properties may be attached to this property. A detailed description of prototypes is beyond the scope of this introduction to objects. However you may familiarize yourself with the basic syntax used as below:"
},
{
"code": null,
"e": 10973,
"s": 9908,
"text": "Output: Notice the usage of the “new” keyword before the function Vehicle. Using the “new” keyword in this manner before any function turns it into a constructor. What the “new Vehicle()” actually does is :It creates a new object and sets the constructor property of the object to schools (It is important to note that this property is a special default property that is not enumerable and cannot be changed by setting a “constructor: someFunction” property manually).Then, it sets up the object to work with the Vehicle function’s prototype object ( Each function in JavaScript gets a prototype object, which is initially just an empty object but can be modified.The object, when instantiated inherits all properties from its constructor’s prototype object).Then calls Vehicle() in the context of the new object, which means that when the “this” keyword is encountered in the constructor(vehicle()), it refers to the new object that was created in the first step.Once this is finished, the newly created object is returned to car1 and car2(in the above example)."
},
{
"code": null,
"e": 11236,
"s": 10973,
"text": "It creates a new object and sets the constructor property of the object to schools (It is important to note that this property is a special default property that is not enumerable and cannot be changed by setting a “constructor: someFunction” property manually)."
},
{
"code": null,
"e": 11528,
"s": 11236,
"text": "Then, it sets up the object to work with the Vehicle function’s prototype object ( Each function in JavaScript gets a prototype object, which is initially just an empty object but can be modified.The object, when instantiated inherits all properties from its constructor’s prototype object)."
},
{
"code": null,
"e": 11734,
"s": 11528,
"text": "Then calls Vehicle() in the context of the new object, which means that when the “this” keyword is encountered in the constructor(vehicle()), it refers to the new object that was created in the first step."
},
{
"code": null,
"e": 11834,
"s": 11734,
"text": "Once this is finished, the newly created object is returned to car1 and car2(in the above example)."
},
{
"code": null,
"e": 12218,
"s": 11834,
"text": "Prototypes : Another way to create objects involves using prototypes. Every JavaScript function has a prototype object property by default(it is empty by default). Methods or properties may be attached to this property. A detailed description of prototypes is beyond the scope of this introduction to objects. However you may familiarize yourself with the basic syntax used as below:"
},
{
"code": null,
"e": 12340,
"s": 12218,
"text": "let obj = Object.create(prototype_object, propertiesObject)\n // the second propertiesObject argument is optional"
},
{
"code": null,
"e": 12400,
"s": 12340,
"text": "An example of making use of the Object.create() method is: "
},
{
"code": null,
"e": 12460,
"s": 12400,
"text": "An example of making use of the Object.create() method is: "
},
{
"code": null,
"e": 12471,
"s": 12460,
"text": "javascript"
},
{
"code": "let footballers = { position: \"Striker\"} let footballer1 = Object.create(footballers); // Output : Striker console.log(footballer1.position);",
"e": 12624,
"s": 12471,
"text": null
},
{
"code": null,
"e": 13385,
"s": 12624,
"text": "Output: In the above example footballers served as a prototype for creating the object “footballer1”. All objects created in this way inherits all properties and methods from its prototype objects. Prototypes can have prototypes and those can have prototypes and so on. This is referred to as prototype chaining in JavaScript. This chain terminates with the Object.prototype which is the default prototype fallback for all objects. JavaScript objects, by default, inherit properties and methods from Object.prototype but these may easily be overridden. It is also interesting to note that the default prototype is not always Object.prototype.For example Strings and Arrays have their own default prototypes – String.prototype and Array.prototype respectively."
},
{
"code": null,
"e": 14146,
"s": 13385,
"text": "Output: In the above example footballers served as a prototype for creating the object “footballer1”. All objects created in this way inherits all properties and methods from its prototype objects. Prototypes can have prototypes and those can have prototypes and so on. This is referred to as prototype chaining in JavaScript. This chain terminates with the Object.prototype which is the default prototype fallback for all objects. JavaScript objects, by default, inherit properties and methods from Object.prototype but these may easily be overridden. It is also interesting to note that the default prototype is not always Object.prototype.For example Strings and Arrays have their own default prototypes – String.prototype and Array.prototype respectively."
},
{
"code": null,
"e": 14171,
"s": 14146,
"text": "Accessing Object Members"
},
{
"code": null,
"e": 14237,
"s": 14171,
"text": "Object members(properties or methods) can be accessed using the :"
},
{
"code": null,
"e": 14252,
"s": 14237,
"text": "dot notation :"
},
{
"code": null,
"e": 14267,
"s": 14252,
"text": "dot notation :"
},
{
"code": null,
"e": 14291,
"s": 14267,
"text": "(objectName.memberName)"
},
{
"code": null,
"e": 14302,
"s": 14291,
"text": "javascript"
},
{
"code": "let school = { name : \"Vivekanada\", location : \"Delhi\", established : 1971, 20 : 1000, displayinfo : function() { console.log(`${school.name} was established in ${school.established} at ${school.location}`); } } console.log(school.name); console.log(school.established);",
"e": 14607,
"s": 14302,
"text": null
},
{
"code": null,
"e": 14634,
"s": 14607,
"text": "Output: Bracket Notation :"
},
{
"code": null,
"e": 14643,
"s": 14634,
"text": "Output: "
},
{
"code": null,
"e": 14662,
"s": 14643,
"text": "Bracket Notation :"
},
{
"code": null,
"e": 14688,
"s": 14662,
"text": " objectName[\"memberName\"]"
},
{
"code": null,
"e": 14699,
"s": 14688,
"text": "javascript"
},
{
"code": "let school = { name : \"Vivekanada School\", location : \"Delhi\", established : 1995, 20 : 1000, displayinfo : function() { document.write(`${school.name} was established in ${school.established} at ${school.location}`); }} // Output : Vivekanada Schoolconsole.log(school['name']); // Output: 1000console.log(school['20']);",
"e": 15054,
"s": 14699,
"text": null
},
{
"code": null,
"e": 15063,
"s": 15054,
"text": "Output: "
},
{
"code": null,
"e": 15072,
"s": 15063,
"text": "Output: "
},
{
"code": null,
"e": 15215,
"s": 15072,
"text": "Unlike the dot notation, the bracket keyword works with any string combination, including, but not limited to multi-word strings. For example:"
},
{
"code": null,
"e": 15286,
"s": 15215,
"text": "somePerson.first name // invalid\n somePerson[\"first name\"] // valid"
},
{
"code": null,
"e": 15456,
"s": 15286,
"text": "Unlike the dot notation, the bracket notation can also contain names which are results of any expressions variables whose values are computed at run-time. For instance :"
},
{
"code": null,
"e": 15512,
"s": 15456,
"text": "let key = \"first name\" somePerson[key] = \"Name Surname\""
},
{
"code": null,
"e": 15578,
"s": 15512,
"text": "Similar operations are not possible while using the dot notation."
},
{
"code": null,
"e": 15615,
"s": 15578,
"text": "Iterating over all keys of an object"
},
{
"code": null,
"e": 16082,
"s": 15615,
"text": "To iterate over all existing enumerable keys of an object, we may use the for...in construct. It is worth noting that this allows us to access only those properties of an object which are enumerable (Recall that enumerable is one of the four attributes of data properties). For instance, properties inherited from the Object.prototype are not enumerable. But, enumerable properties inherited from somewhere can also be accessed using the for...in construct Example: "
},
{
"code": null,
"e": 16093,
"s": 16082,
"text": "javascript"
},
{
"code": "let person = { gender : \"male\"} var person1 = Object.create(person);person1.name = \"Adam\";person1.age = 45;person1.nationality = \"Australian\"; for (let key in person1) {// Output : name, age, nationality// and gender console.log(key);} ",
"e": 16344,
"s": 16093,
"text": null
},
{
"code": null,
"e": 16353,
"s": 16344,
"text": "Output: "
},
{
"code": null,
"e": 16373,
"s": 16353,
"text": "Deleting Properties"
},
{
"code": null,
"e": 16495,
"s": 16373,
"text": "To Delete a property of an object we can make use of the delete operator. An example of its usage has been listed below: "
},
{
"code": null,
"e": 16506,
"s": 16495,
"text": "javascript"
},
{
"code": "let obj1 = { propfirst : \"Name\"} // Output : Nameconsole.log(obj1.propfirst);delete obj1.propfirst // Output : undefinedconsole.log(obj1.propfirst); ",
"e": 16670,
"s": 16506,
"text": null
},
{
"code": null,
"e": 16809,
"s": 16670,
"text": "Output: It is important to note that we can not delete inherited properties or non-configurable properties in this manner. For example : "
},
{
"code": null,
"e": 16820,
"s": 16809,
"text": "javascript"
},
{
"code": "let obj1 = { propfirst : \"Name\"}// Output : Nameconsole.log(obj1.propfirst) let obj2 = Object.create(obj1); // Output : Name console.log(obj2.propfirst); // Output : true. console.log(delete obj2.propfirst); // Surprisingly Note that this will return true // regardless of whether the deletion was successful // Output : Name console.log(obj2.propfirst);",
"e": 17203,
"s": 16820,
"text": null
},
{
"code": null,
"e": 17212,
"s": 17203,
"text": "Output: "
},
{
"code": null,
"e": 17232,
"s": 17212,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 17258,
"s": 17232,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 17276,
"s": 17258,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 17296,
"s": 17276,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 17314,
"s": 17296,
"text": "Opera 3 and above"
},
{
"code": null,
"e": 17333,
"s": 17314,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 17363,
"s": 17333,
"text": "Internet Explorer 3 and above"
},
{
"code": null,
"e": 17371,
"s": 17363,
"text": "immukul"
},
{
"code": null,
"e": 17388,
"s": 17371,
"text": "kumargaurav97520"
},
{
"code": null,
"e": 17399,
"s": 17388,
"text": "amansingla"
},
{
"code": null,
"e": 17417,
"s": 17399,
"text": "javascript-basics"
},
{
"code": null,
"e": 17432,
"s": 17417,
"text": "javascript-oop"
},
{
"code": null,
"e": 17443,
"s": 17432,
"text": "JavaScript"
},
{
"code": null,
"e": 17460,
"s": 17443,
"text": "Web Technologies"
}
] |
Python string | digits
|
16 Oct, 2018
In Python3, string.digits is a pre-initialized string used as string constant. In Python, string.digits will give the lowercase letters ‘0123456789’.
Syntax : string.digits
Parameters : Doesn’t take any parameter, since it’s not a function.
Returns : Return all digit letters.
Note : Make sure to import string library function inorder to use string.digits
Code #1 :
# import string library function import string # Storing the value in variable result result = string.digits # Printing the value print(result)
Output :
0123456789
Code #2 : Given code checks if the string input has only digit letters
# importing string library function import string # Function checks if input string # har only digits or not def check(value): for letter in value: # If anything other than digit # letter is present, then return # False, else return True if letter not in string.digits: return False return True # Driver Code input1 = "0123 456 789"print(input1, "--> ", check(input1)) input2 = "12.0124"print(input2, "--> ", check(input2)) input3 = "12345"print(input3, "--> ", check(input3))
Output:
0123 456 789 --> False
12.0124 --> False
12345 --> True
Applications :The string constant digits can be used in many practical applications. Let’s see a code explaining how to use digits to generate strong random passwords of given size.
# Importing random to generate # random string sequence import random # Importing string library function import string def rand_pass(size): # Takes random choices from # ascii_letters and digits generate_pass = ''.join([random.choice( string.ascii_uppercase + string.ascii_lowercase + string.digits) for n in range(size)]) return generate_pass # Driver Code password = rand_pass(10) print(password)
Output:
2R8gaoDKqn
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n16 Oct, 2018"
},
{
"code": null,
"e": 203,
"s": 53,
"text": "In Python3, string.digits is a pre-initialized string used as string constant. In Python, string.digits will give the lowercase letters ‘0123456789’."
},
{
"code": null,
"e": 226,
"s": 203,
"text": "Syntax : string.digits"
},
{
"code": null,
"e": 294,
"s": 226,
"text": "Parameters : Doesn’t take any parameter, since it’s not a function."
},
{
"code": null,
"e": 330,
"s": 294,
"text": "Returns : Return all digit letters."
},
{
"code": null,
"e": 410,
"s": 330,
"text": "Note : Make sure to import string library function inorder to use string.digits"
},
{
"code": null,
"e": 420,
"s": 410,
"text": "Code #1 :"
},
{
"code": "# import string library function import string # Storing the value in variable result result = string.digits # Printing the value print(result) ",
"e": 573,
"s": 420,
"text": null
},
{
"code": null,
"e": 582,
"s": 573,
"text": "Output :"
},
{
"code": null,
"e": 593,
"s": 582,
"text": "0123456789"
},
{
"code": null,
"e": 665,
"s": 593,
"text": " Code #2 : Given code checks if the string input has only digit letters"
},
{
"code": "# importing string library function import string # Function checks if input string # har only digits or not def check(value): for letter in value: # If anything other than digit # letter is present, then return # False, else return True if letter not in string.digits: return False return True # Driver Code input1 = \"0123 456 789\"print(input1, \"--> \", check(input1)) input2 = \"12.0124\"print(input2, \"--> \", check(input2)) input3 = \"12345\"print(input3, \"--> \", check(input3)) ",
"e": 1227,
"s": 665,
"text": null
},
{
"code": null,
"e": 1235,
"s": 1227,
"text": "Output:"
},
{
"code": null,
"e": 1294,
"s": 1235,
"text": "0123 456 789 --> False\n12.0124 --> False\n12345 --> True"
},
{
"code": null,
"e": 1476,
"s": 1294,
"text": "Applications :The string constant digits can be used in many practical applications. Let’s see a code explaining how to use digits to generate strong random passwords of given size."
},
{
"code": "# Importing random to generate # random string sequence import random # Importing string library function import string def rand_pass(size): # Takes random choices from # ascii_letters and digits generate_pass = ''.join([random.choice( string.ascii_uppercase + string.ascii_lowercase + string.digits) for n in range(size)]) return generate_pass # Driver Code password = rand_pass(10) print(password) ",
"e": 2080,
"s": 1476,
"text": null
},
{
"code": null,
"e": 2088,
"s": 2080,
"text": "Output:"
},
{
"code": null,
"e": 2099,
"s": 2088,
"text": "2R8gaoDKqn"
},
{
"code": null,
"e": 2113,
"s": 2099,
"text": "python-string"
},
{
"code": null,
"e": 2120,
"s": 2113,
"text": "Python"
}
] |
Can we return this keyword from a method in java?
|
The "this" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables, and methods.
Yes, you can return this in Java i.e. The following statement is valid.
return this;
When you return "this" from a method the current object will be returned.
In the following Java example, the class Student has two private variables name and age. From a method setValues() we are reading values from user and assigning them to these (instance) variables and returning the current object.
public class Student {
private String name;
private int age;
public Student SetValues(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the student: ");
String name = sc.nextLine();
System.out.println("Enter the age of the student: ");
int age = sc.nextInt();
this.name = name;
this.age = age;
return this;
}
public void display() {
System.out.println("name: "+name);
System.out.println("age: "+age);
}
public static void main(String args[]) {
Student obj = new Student();
obj = obj.SettingValues();
obj.display();
}
}
Enter the name of the student:
Krishna Kasyap
Enter the age of the student:
21
name: Krishna Kasyap
age: 21
|
[
{
"code": null,
"e": 1273,
"s": 1062,
"text": "The \"this\" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables, and methods."
},
{
"code": null,
"e": 1345,
"s": 1273,
"text": "Yes, you can return this in Java i.e. The following statement is valid."
},
{
"code": null,
"e": 1358,
"s": 1345,
"text": "return this;"
},
{
"code": null,
"e": 1432,
"s": 1358,
"text": "When you return \"this\" from a method the current object will be returned."
},
{
"code": null,
"e": 1662,
"s": 1432,
"text": "In the following Java example, the class Student has two private variables name and age. From a method setValues() we are reading values from user and assigning them to these (instance) variables and returning the current object."
},
{
"code": null,
"e": 2311,
"s": 1662,
"text": "public class Student {\n private String name;\n private int age;\n public Student SetValues(){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the name of the student: \");\n String name = sc.nextLine();\n System.out.println(\"Enter the age of the student: \");\n int age = sc.nextInt();\n this.name = name;\n this.age = age;\n return this;\n }\n public void display() {\n System.out.println(\"name: \"+name);\n System.out.println(\"age: \"+age);\n }\n public static void main(String args[]) {\n Student obj = new Student();\n obj = obj.SettingValues();\n obj.display();\n }\n}"
},
{
"code": null,
"e": 2419,
"s": 2311,
"text": "Enter the name of the student:\nKrishna Kasyap\nEnter the age of the student:\n21\nname: Krishna Kasyap\nage: 21"
}
] |
How does underscore "_" work in Python files?
|
The underscore (_) is special in Python. There are 5 cases for using the underscore in Python.
1. For storing the value of last expression in interpreter.
The python interpreter stores the last expression value to the special variable called ‘_’.
>>> 12 + 10
22
>>> _
22
2. For ignoring the specific values.
The underscore is also used for ignoring the specific values in several languages like elixir, erlang, python, etc. If you don’t need the specific values or the values are not used, just assign the values to underscore.
>>> _, _, a = (1, 2, 3)
>>> a
3
3. To give special meaning to name of variables and functions.
Variable names with single preceding underscores are used for private variables, functions, classes. Anything with this convention are ignored in from module import *. There are many other conventions you can check out at: https://hackernoon.com/understanding-the-underscore-of-python-309d1a029edc
4. To separate the digits of number literal value.
In python, to avoid having to deal with extremely large numbers, you can put underscores to make numbers easily readable.
>>> a = 7_200_000_000 # 7.2 billion easily readable
>>> a
7200000000
Note that the last feature was added to python in v3.6
|
[
{
"code": null,
"e": 1157,
"s": 1062,
"text": "The underscore (_) is special in Python. There are 5 cases for using the underscore in Python."
},
{
"code": null,
"e": 1217,
"s": 1157,
"text": "1. For storing the value of last expression in interpreter."
},
{
"code": null,
"e": 1309,
"s": 1217,
"text": "The python interpreter stores the last expression value to the special variable called ‘_’."
},
{
"code": null,
"e": 1333,
"s": 1309,
"text": ">>> 12 + 10\n22\n>>> _\n22"
},
{
"code": null,
"e": 1370,
"s": 1333,
"text": "2. For ignoring the specific values."
},
{
"code": null,
"e": 1590,
"s": 1370,
"text": "The underscore is also used for ignoring the specific values in several languages like elixir, erlang, python, etc. If you don’t need the specific values or the values are not used, just assign the values to underscore."
},
{
"code": null,
"e": 1622,
"s": 1590,
"text": ">>> _, _, a = (1, 2, 3)\n>>> a\n3"
},
{
"code": null,
"e": 1685,
"s": 1622,
"text": "3. To give special meaning to name of variables and functions."
},
{
"code": null,
"e": 1983,
"s": 1685,
"text": "Variable names with single preceding underscores are used for private variables, functions, classes. Anything with this convention are ignored in from module import *. There are many other conventions you can check out at: https://hackernoon.com/understanding-the-underscore-of-python-309d1a029edc"
},
{
"code": null,
"e": 2034,
"s": 1983,
"text": "4. To separate the digits of number literal value."
},
{
"code": null,
"e": 2156,
"s": 2034,
"text": "In python, to avoid having to deal with extremely large numbers, you can put underscores to make numbers easily readable."
},
{
"code": null,
"e": 2227,
"s": 2156,
"text": ">>> a = 7_200_000_000 # 7.2 billion easily readable\n>>> a\n7200000000"
},
{
"code": null,
"e": 2282,
"s": 2227,
"text": "Note that the last feature was added to python in v3.6"
}
] |
How to adjust the alignments of the text in JavaFX?
|
You can set a fixed width for the text in user space by setting the value to the wrappingWidth property. Once you do so, given width is considered as the boundary of the text in user coordinates and, the text is arranged width in the given width.
If you haven’t given any value for this property, by default, the length longest line in the text is considered as the width of the bounding box.
Text alignment is the arrangement of the text horizontally within the bounding box. You can adjust the alignment of the text using the setTextAlignment() method. This method accepts one of the constants of the enum named TextAlignment and adjusts the text accordingly. This enum provides 3 constants −
CENTER − Aligns the text in the center of the bounding box.
CENTER − Aligns the text in the center of the bounding box.
JUSTIFY − Justifies the text alignment within the bounding box.
JUSTIFY − Justifies the text alignment within the bounding box.
LEFT − Aligns the text to the left.
LEFT − Aligns the text to the left.
RIGHT − Aligns the text to the right.
RIGHT − Aligns the text to the right.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
public class TextAllignment extends Application {
public void start(Stage stage) throws FileNotFoundException {
//Reading the contents of a text file.
InputStream inputStream = new FileInputStream("D:\\sample.txt");
Scanner sc = new Scanner(inputStream);
StringBuffer sb = new StringBuffer();
while(sc.hasNext()) {
sb.append(" "+sc.nextLine()+"\n");
}
//Creating a text object
Text text = new Text(10.0, 25.0, sb.toString());
//Wrapping the text
text.setWrappingWidth(565);
//Setting the alignment
text.setTextAlignment(TextAlignment.Right);
//Setting the stage
Group root = new Group(text);
Scene scene = new Scene(root, 595, 150, Color.BEIGE);
stage.setTitle("Text Alignment");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Assume following are the contents of the sample.txt file −
Tutorials Point originated from the idea that there exists a class of readers who respond better
to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms.
The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated,
we worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of
tutorials and allied articles on topics ranging from programming languages to web designing to academics
and much more.
In the same way, if you change the alignment value you will get the outputs
accordingly as −
LEFT −
CENTER −
JUSTIFY −
|
[
{
"code": null,
"e": 1309,
"s": 1062,
"text": "You can set a fixed width for the text in user space by setting the value to the wrappingWidth property. Once you do so, given width is considered as the boundary of the text in user coordinates and, the text is arranged width in the given width."
},
{
"code": null,
"e": 1455,
"s": 1309,
"text": "If you haven’t given any value for this property, by default, the length longest line in the text is considered as the width of the bounding box."
},
{
"code": null,
"e": 1757,
"s": 1455,
"text": "Text alignment is the arrangement of the text horizontally within the bounding box. You can adjust the alignment of the text using the setTextAlignment() method. This method accepts one of the constants of the enum named TextAlignment and adjusts the text accordingly. This enum provides 3 constants −"
},
{
"code": null,
"e": 1817,
"s": 1757,
"text": "CENTER − Aligns the text in the center of the bounding box."
},
{
"code": null,
"e": 1877,
"s": 1817,
"text": "CENTER − Aligns the text in the center of the bounding box."
},
{
"code": null,
"e": 1941,
"s": 1877,
"text": "JUSTIFY − Justifies the text alignment within the bounding box."
},
{
"code": null,
"e": 2005,
"s": 1941,
"text": "JUSTIFY − Justifies the text alignment within the bounding box."
},
{
"code": null,
"e": 2041,
"s": 2005,
"text": "LEFT − Aligns the text to the left."
},
{
"code": null,
"e": 2077,
"s": 2041,
"text": "LEFT − Aligns the text to the left."
},
{
"code": null,
"e": 2115,
"s": 2077,
"text": "RIGHT − Aligns the text to the right."
},
{
"code": null,
"e": 2153,
"s": 2115,
"text": "RIGHT − Aligns the text to the right."
},
{
"code": null,
"e": 3413,
"s": 2153,
"text": "import java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.InputStream;\nimport java.util.Scanner;\nimport javafx.application.Application;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\nimport javafx.scene.text.Text;\nimport javafx.scene.text.TextAlignment;\npublic class TextAllignment extends Application {\n public void start(Stage stage) throws FileNotFoundException {\n //Reading the contents of a text file.\n InputStream inputStream = new FileInputStream(\"D:\\\\sample.txt\");\n Scanner sc = new Scanner(inputStream);\n StringBuffer sb = new StringBuffer();\n while(sc.hasNext()) {\n sb.append(\" \"+sc.nextLine()+\"\\n\");\n }\n //Creating a text object\n Text text = new Text(10.0, 25.0, sb.toString());\n //Wrapping the text\n text.setWrappingWidth(565);\n //Setting the alignment\n text.setTextAlignment(TextAlignment.Right);\n //Setting the stage\n Group root = new Group(text);\n Scene scene = new Scene(root, 595, 150, Color.BEIGE);\n stage.setTitle(\"Text Alignment\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
},
{
"code": null,
"e": 3472,
"s": 3413,
"text": "Assume following are the contents of the sample.txt file −"
},
{
"code": null,
"e": 4004,
"s": 3472,
"text": "Tutorials Point originated from the idea that there exists a class of readers who respond better \nto online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms.\nThe journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, \nwe worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of \ntutorials and allied articles on topics ranging from programming languages to web designing to academics \nand much more."
},
{
"code": null,
"e": 4097,
"s": 4004,
"text": "In the same way, if you change the alignment value you will get the outputs\naccordingly as −"
},
{
"code": null,
"e": 4104,
"s": 4097,
"text": "LEFT −"
},
{
"code": null,
"e": 4113,
"s": 4104,
"text": "CENTER −"
},
{
"code": null,
"e": 4123,
"s": 4113,
"text": "JUSTIFY −"
}
] |
JavaScript subtraction of two float values?
|
To correctly subtract two float values, use parseFloat() along with toFixed().
Following is the code −
var firstValue=4.3;
var secondValue=3.8;
console.log("The first Value="+parseFloat(firstValue).toFixed(1)+" The
second Value="+parseFloat(secondValue).toFixed(1))
var result = parseFloat(firstValue).toFixed(1) -
parseFloat(secondValue).toFixed(1);
console.log("Result is="+result);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo309.js.
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo309.js
The first Value=4.3 The second Value=3.8
Result is=0.5
|
[
{
"code": null,
"e": 1141,
"s": 1062,
"text": "To correctly subtract two float values, use parseFloat() along with toFixed()."
},
{
"code": null,
"e": 1165,
"s": 1141,
"text": "Following is the code −"
},
{
"code": null,
"e": 1447,
"s": 1165,
"text": "var firstValue=4.3;\nvar secondValue=3.8;\nconsole.log(\"The first Value=\"+parseFloat(firstValue).toFixed(1)+\" The\nsecond Value=\"+parseFloat(secondValue).toFixed(1))\nvar result = parseFloat(firstValue).toFixed(1) -\nparseFloat(secondValue).toFixed(1);\nconsole.log(\"Result is=\"+result);"
},
{
"code": null,
"e": 1513,
"s": 1447,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1531,
"s": 1513,
"text": "node fileName.js."
},
{
"code": null,
"e": 1565,
"s": 1531,
"text": "Here, my file name is demo309.js."
},
{
"code": null,
"e": 1606,
"s": 1565,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1711,
"s": 1606,
"text": "PS C:\\Users\\Amit\\javascript-code> node demo309.js\nThe first Value=4.3 The second Value=3.8\nResult is=0.5"
}
] |
Longest Common Subsequence of two arrays out of which one array consists of distinct elements only - GeeksforGeeks
|
15 Jun, 2021
Given two arrays firstArr[], consisting of distinct elements only, and secondArr[], the task is to find the length of LCS between these 2 arrays.
Examples:
Input: firstArr[] = {3, 5, 1, 8}, secondArr[] = {3, 3, 5, 3, 8}Output: 3.Explanation: LCS between these two arrays is {3, 5, 8}.
Input : firstArr[] = {1, 2, 1}, secondArr[] = {3}Output: 0
Naive Approach: Follow the steps below to solve the problem using the simplest possible approach:
Initialize an array dp[][] such that dp[i][j] stores longest common subsequence of firstArr[ :i] and secondArr[ :j].
Traverse the array firstArr[] and for every array element of the array firstArr[], traverse the array secondArr[].
If firstArr[i] = secondArr[j]: Set dp[i][j] = dp[i – 1][j – 1] + 1.
Otherwise: Set dp[i][j] = max(dp[ i – 1][j], dp[i][j – 1]).
Time Complexity: O(N * M), where N and M are the sizes of the arrays firstArr[] and secondArr[] respectively. Auxiliary Space: O(N * M)
Efficient Approach: To optimize the above approach, follow the steps below:
Initialize a Map, say mp, to store the mappings map[firstArr[i]] = i, i.e. map elements of the first array to their respective indices.
Since the elements which are present in secondArr[] but not in the firstArr[] are not useful at all, as they can never be a part of a common subsequence, traverse the array secondArr[] andfor each array element, check if it is present in the Map or not.
If found to be true, push map[secondArr[i]] into a temporary Array. Otherwise ignore it.
Find the Longest Increasing Subsequence (LIS) of the obtained temporary array and print its length as the required answer.
Illustration:
firstArr[] = {3, 5, 1, 8} secondArr={3, 3, 4, 5, 3, 8} Mapping: 3->0, 5->1, 1->2, 8->3 (From firstArr) tempArr[] = {0, 0, 1, 0, 3} Therefore, length of LIS of tempArr[] = 3 ({0, 1, 3})
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the Longest Common// Subsequence between the two arraysint LCS(vector<int>& firstArr, vector<int>& secondArr){ // Maps elements of firstArr[] // to their respective indices unordered_map<int, int> mp; // Traverse the array firstArr[] for (int i = 0; i < firstArr.size(); i++) { mp[firstArr[i]] = i + 1; } // Stores the indices of common elements // between firstArr[] and secondArr[] vector<int> tempArr; // Traverse the array secondArr[] for (int i = 0; i < secondArr.size(); i++) { // If current element exists in the Map if (mp.find(secondArr[i]) != mp.end()) { tempArr.push_back(mp[secondArr[i]]); } } // Stores lIS from tempArr[] vector<int> tail; tail.push_back(tempArr[0]); for (int i = 1; i < tempArr.size(); i++) { if (tempArr[i] > tail.back()) tail.push_back(tempArr[i]); else if (tempArr[i] < tail[0]) tail[0] = tempArr[i]; else { auto it = lower_bound(tail.begin(), tail.end(), tempArr[i]); *it = tempArr[i]; } } return (int)tail.size();} // Driver Codeint main(){ vector<int> firstArr = { 3, 5, 1, 8 }; vector<int> secondArr = { 3, 3, 5, 3, 8 }; cout << LCS(firstArr, secondArr); return 0;}
// Java program to to implement// the above approachimport java.util.*;class GFG{ // Function to find the Longest Common// Subsequence between the two arraysstatic int LCS(int[] firstArr,int[] secondArr){ // Maps elements of firstArr[] // to their respective indices HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>(); // Traverse the array firstArr[] for (int i = 0; i < firstArr.length; i++) { mp.put(firstArr[i], i + 1); } // Stores the indices of common elements // between firstArr[] and secondArr[] Vector<Integer> tempArr = new Vector<>(); // Traverse the array secondArr[] for (int i = 0; i < secondArr.length; i++) { // If current element exists in the Map if (mp.containsKey(secondArr[i])) { tempArr.add(mp.get(secondArr[i])); } } // Stores lIS from tempArr[] Vector<Integer> tail = new Vector<>(); tail.add(tempArr.get(0)); for (int i = 1; i < tempArr.size(); i++) { if (tempArr.get(i) > tail.lastElement()) tail.add(tempArr.get(i)); else if (tempArr.get(i) < tail.get(0)) tail.add(0, tempArr.get(i)); } return (int)tail.size();} // Driver Codepublic static void main(String[] args){ int[] firstArr = { 3, 5, 1, 8 }; int[] secondArr = { 3, 3, 5, 3, 8 }; System.out.print(LCS(firstArr, secondArr));}} // This code is contributed by gauravrajput1
# Python3 program to to implement# the above approachfrom bisect import bisect_left # Function to find the Longest Common# Subsequence between the two arraysdef LCS(firstArr, secondArr): # Maps elements of firstArr[] # to their respective indices mp = {} # Traverse the array firstArr[] for i in range(len(firstArr)): mp[firstArr[i]] = i + 1 # Stores the indices of common elements # between firstArr[] and secondArr[] tempArr = [] # Traverse the array secondArr[] for i in range(len(secondArr)): # If current element exists in the Map if (secondArr[i] in mp): tempArr.append(mp[secondArr[i]]) # Stores lIS from tempArr[] tail = [] tail.append(tempArr[0]) for i in range(1, len(tempArr)): if (tempArr[i] > tail[-1]): tail.append(tempArr[i]) elif (tempArr[i] < tail[0]): tail[0] = tempArr[i] else : it = bisect_left(tail, tempArr[i]) it = tempArr[i] return len(tail) # Driver Codeif __name__ == '__main__': firstArr = [3, 5, 1, 8 ] secondArr = [3, 3, 5, 3, 8 ] print (LCS(firstArr, secondArr)) # This code is contributed by mohit kumar 29
// C# program to to implement// the above approachusing System;using System.Collections.Generic;public class GFG{ // Function to find the longest Common// Subsequence between the two arraysstatic int LCS(int[] firstArr,int[] secondArr){ // Maps elements of firstArr[] // to their respective indices Dictionary<int,int> mp = new Dictionary<int,int>(); // Traverse the array firstArr[] for (int i = 0; i < firstArr.Length; i++) { mp.Add(firstArr[i], i + 1); } // Stores the indices of common elements // between firstArr[] and secondArr[] List<int> tempArr = new List<int>(); // Traverse the array secondArr[] for (int i = 0; i < secondArr.Length; i++) { // If current element exists in the Map if (mp.ContainsKey(secondArr[i])) { tempArr.Add(mp[secondArr[i]]); } } // Stores lIS from tempArr[] List<int> tail = new List<int>(); tail.Add(tempArr[0]); for (int i = 1; i < tempArr.Count; i++) { if (tempArr[i] > tail[tail.Count-1]) tail.Add(tempArr[i]); else if (tempArr[i] < tail[0]) tail.Insert(0, tempArr[i]); } return (int)tail.Count;} // Driver Codepublic static void Main(String[] args){ int[] firstArr = { 3, 5, 1, 8 }; int[] secondArr = { 3, 3, 5, 3, 8 }; Console.Write(LCS(firstArr, secondArr));}} // This code is contributed by Rajput-Ji.
<script> // Javascript program to to implement// the above approach // Function to find the longest Common// Subsequence between the two arraysfunction LCS(firstArr, secondArr){ // Maps elements of firstArr[] // to their respective indices let mp = new Map() // Traverse the array firstArr[] for(let i = 0; i < firstArr.length; i++) { mp.set(firstArr[i], i + 1); } // Stores the indices of common elements // between firstArr[] and secondArr[] let tempArr = []; // Traverse the array secondArr[] for(let i = 0; i < secondArr.length; i++) { // If current element exists in the Map if (mp.has(secondArr[i])) { tempArr.push(mp.get(secondArr[i])); } } // Stores lIS from tempArr[] let tail = []; tail.push(tempArr[0]); for(let i = 1; i < tempArr.length; i++) { if (tempArr[i] > tail[tail.length - 1]) tail.push(tempArr[i]); else if (tempArr[i] < tail[0]) tail.unshift(0, tempArr[i]); } return tail.length;} // Driver Codelet firstArr = [ 3, 5, 1, 8 ];let secondArr = [ 3, 3, 5, 3, 8 ]; document.write(LCS(firstArr, secondArr)); // This code is contributed by gfgking </script>
3
Time Complexity: O(NlogN)Auxiliary Space: O(N)
mohit kumar 29
GauravRajput1
Rajput-Ji
gfgking
Binary Search
cpp-map
LCS
LIS
subsequence
Technical Scripter 2020
Arrays
Dynamic Programming
Hash
Mathematical
Searching
Technical Scripter
Arrays
Searching
Hash
Dynamic Programming
Mathematical
LCS
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
|
[
{
"code": null,
"e": 25197,
"s": 25169,
"text": "\n15 Jun, 2021"
},
{
"code": null,
"e": 25343,
"s": 25197,
"text": "Given two arrays firstArr[], consisting of distinct elements only, and secondArr[], the task is to find the length of LCS between these 2 arrays."
},
{
"code": null,
"e": 25353,
"s": 25343,
"text": "Examples:"
},
{
"code": null,
"e": 25482,
"s": 25353,
"text": "Input: firstArr[] = {3, 5, 1, 8}, secondArr[] = {3, 3, 5, 3, 8}Output: 3.Explanation: LCS between these two arrays is {3, 5, 8}."
},
{
"code": null,
"e": 25541,
"s": 25482,
"text": "Input : firstArr[] = {1, 2, 1}, secondArr[] = {3}Output: 0"
},
{
"code": null,
"e": 25639,
"s": 25541,
"text": "Naive Approach: Follow the steps below to solve the problem using the simplest possible approach:"
},
{
"code": null,
"e": 25756,
"s": 25639,
"text": "Initialize an array dp[][] such that dp[i][j] stores longest common subsequence of firstArr[ :i] and secondArr[ :j]."
},
{
"code": null,
"e": 25871,
"s": 25756,
"text": "Traverse the array firstArr[] and for every array element of the array firstArr[], traverse the array secondArr[]."
},
{
"code": null,
"e": 25939,
"s": 25871,
"text": "If firstArr[i] = secondArr[j]: Set dp[i][j] = dp[i – 1][j – 1] + 1."
},
{
"code": null,
"e": 25999,
"s": 25939,
"text": "Otherwise: Set dp[i][j] = max(dp[ i – 1][j], dp[i][j – 1])."
},
{
"code": null,
"e": 26135,
"s": 25999,
"text": "Time Complexity: O(N * M), where N and M are the sizes of the arrays firstArr[] and secondArr[] respectively. Auxiliary Space: O(N * M)"
},
{
"code": null,
"e": 26212,
"s": 26135,
"text": "Efficient Approach: To optimize the above approach, follow the steps below: "
},
{
"code": null,
"e": 26348,
"s": 26212,
"text": "Initialize a Map, say mp, to store the mappings map[firstArr[i]] = i, i.e. map elements of the first array to their respective indices."
},
{
"code": null,
"e": 26602,
"s": 26348,
"text": "Since the elements which are present in secondArr[] but not in the firstArr[] are not useful at all, as they can never be a part of a common subsequence, traverse the array secondArr[] andfor each array element, check if it is present in the Map or not."
},
{
"code": null,
"e": 26691,
"s": 26602,
"text": "If found to be true, push map[secondArr[i]] into a temporary Array. Otherwise ignore it."
},
{
"code": null,
"e": 26814,
"s": 26691,
"text": "Find the Longest Increasing Subsequence (LIS) of the obtained temporary array and print its length as the required answer."
},
{
"code": null,
"e": 26829,
"s": 26814,
"text": "Illustration: "
},
{
"code": null,
"e": 27015,
"s": 26829,
"text": "firstArr[] = {3, 5, 1, 8} secondArr={3, 3, 4, 5, 3, 8} Mapping: 3->0, 5->1, 1->2, 8->3 (From firstArr) tempArr[] = {0, 0, 1, 0, 3} Therefore, length of LIS of tempArr[] = 3 ({0, 1, 3}) "
},
{
"code": null,
"e": 27067,
"s": 27015,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27071,
"s": 27067,
"text": "C++"
},
{
"code": null,
"e": 27076,
"s": 27071,
"text": "Java"
},
{
"code": null,
"e": 27084,
"s": 27076,
"text": "Python3"
},
{
"code": null,
"e": 27087,
"s": 27084,
"text": "C#"
},
{
"code": null,
"e": 27098,
"s": 27087,
"text": "Javascript"
},
{
"code": "// C++ program to to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the Longest Common// Subsequence between the two arraysint LCS(vector<int>& firstArr, vector<int>& secondArr){ // Maps elements of firstArr[] // to their respective indices unordered_map<int, int> mp; // Traverse the array firstArr[] for (int i = 0; i < firstArr.size(); i++) { mp[firstArr[i]] = i + 1; } // Stores the indices of common elements // between firstArr[] and secondArr[] vector<int> tempArr; // Traverse the array secondArr[] for (int i = 0; i < secondArr.size(); i++) { // If current element exists in the Map if (mp.find(secondArr[i]) != mp.end()) { tempArr.push_back(mp[secondArr[i]]); } } // Stores lIS from tempArr[] vector<int> tail; tail.push_back(tempArr[0]); for (int i = 1; i < tempArr.size(); i++) { if (tempArr[i] > tail.back()) tail.push_back(tempArr[i]); else if (tempArr[i] < tail[0]) tail[0] = tempArr[i]; else { auto it = lower_bound(tail.begin(), tail.end(), tempArr[i]); *it = tempArr[i]; } } return (int)tail.size();} // Driver Codeint main(){ vector<int> firstArr = { 3, 5, 1, 8 }; vector<int> secondArr = { 3, 3, 5, 3, 8 }; cout << LCS(firstArr, secondArr); return 0;}",
"e": 28581,
"s": 27098,
"text": null
},
{
"code": "// Java program to to implement// the above approachimport java.util.*;class GFG{ // Function to find the Longest Common// Subsequence between the two arraysstatic int LCS(int[] firstArr,int[] secondArr){ // Maps elements of firstArr[] // to their respective indices HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>(); // Traverse the array firstArr[] for (int i = 0; i < firstArr.length; i++) { mp.put(firstArr[i], i + 1); } // Stores the indices of common elements // between firstArr[] and secondArr[] Vector<Integer> tempArr = new Vector<>(); // Traverse the array secondArr[] for (int i = 0; i < secondArr.length; i++) { // If current element exists in the Map if (mp.containsKey(secondArr[i])) { tempArr.add(mp.get(secondArr[i])); } } // Stores lIS from tempArr[] Vector<Integer> tail = new Vector<>(); tail.add(tempArr.get(0)); for (int i = 1; i < tempArr.size(); i++) { if (tempArr.get(i) > tail.lastElement()) tail.add(tempArr.get(i)); else if (tempArr.get(i) < tail.get(0)) tail.add(0, tempArr.get(i)); } return (int)tail.size();} // Driver Codepublic static void main(String[] args){ int[] firstArr = { 3, 5, 1, 8 }; int[] secondArr = { 3, 3, 5, 3, 8 }; System.out.print(LCS(firstArr, secondArr));}} // This code is contributed by gauravrajput1",
"e": 30014,
"s": 28581,
"text": null
},
{
"code": "# Python3 program to to implement# the above approachfrom bisect import bisect_left # Function to find the Longest Common# Subsequence between the two arraysdef LCS(firstArr, secondArr): # Maps elements of firstArr[] # to their respective indices mp = {} # Traverse the array firstArr[] for i in range(len(firstArr)): mp[firstArr[i]] = i + 1 # Stores the indices of common elements # between firstArr[] and secondArr[] tempArr = [] # Traverse the array secondArr[] for i in range(len(secondArr)): # If current element exists in the Map if (secondArr[i] in mp): tempArr.append(mp[secondArr[i]]) # Stores lIS from tempArr[] tail = [] tail.append(tempArr[0]) for i in range(1, len(tempArr)): if (tempArr[i] > tail[-1]): tail.append(tempArr[i]) elif (tempArr[i] < tail[0]): tail[0] = tempArr[i] else : it = bisect_left(tail, tempArr[i]) it = tempArr[i] return len(tail) # Driver Codeif __name__ == '__main__': firstArr = [3, 5, 1, 8 ] secondArr = [3, 3, 5, 3, 8 ] print (LCS(firstArr, secondArr)) # This code is contributed by mohit kumar 29",
"e": 31210,
"s": 30014,
"text": null
},
{
"code": "// C# program to to implement// the above approachusing System;using System.Collections.Generic;public class GFG{ // Function to find the longest Common// Subsequence between the two arraysstatic int LCS(int[] firstArr,int[] secondArr){ // Maps elements of firstArr[] // to their respective indices Dictionary<int,int> mp = new Dictionary<int,int>(); // Traverse the array firstArr[] for (int i = 0; i < firstArr.Length; i++) { mp.Add(firstArr[i], i + 1); } // Stores the indices of common elements // between firstArr[] and secondArr[] List<int> tempArr = new List<int>(); // Traverse the array secondArr[] for (int i = 0; i < secondArr.Length; i++) { // If current element exists in the Map if (mp.ContainsKey(secondArr[i])) { tempArr.Add(mp[secondArr[i]]); } } // Stores lIS from tempArr[] List<int> tail = new List<int>(); tail.Add(tempArr[0]); for (int i = 1; i < tempArr.Count; i++) { if (tempArr[i] > tail[tail.Count-1]) tail.Add(tempArr[i]); else if (tempArr[i] < tail[0]) tail.Insert(0, tempArr[i]); } return (int)tail.Count;} // Driver Codepublic static void Main(String[] args){ int[] firstArr = { 3, 5, 1, 8 }; int[] secondArr = { 3, 3, 5, 3, 8 }; Console.Write(LCS(firstArr, secondArr));}} // This code is contributed by Rajput-Ji.",
"e": 32622,
"s": 31210,
"text": null
},
{
"code": "<script> // Javascript program to to implement// the above approach // Function to find the longest Common// Subsequence between the two arraysfunction LCS(firstArr, secondArr){ // Maps elements of firstArr[] // to their respective indices let mp = new Map() // Traverse the array firstArr[] for(let i = 0; i < firstArr.length; i++) { mp.set(firstArr[i], i + 1); } // Stores the indices of common elements // between firstArr[] and secondArr[] let tempArr = []; // Traverse the array secondArr[] for(let i = 0; i < secondArr.length; i++) { // If current element exists in the Map if (mp.has(secondArr[i])) { tempArr.push(mp.get(secondArr[i])); } } // Stores lIS from tempArr[] let tail = []; tail.push(tempArr[0]); for(let i = 1; i < tempArr.length; i++) { if (tempArr[i] > tail[tail.length - 1]) tail.push(tempArr[i]); else if (tempArr[i] < tail[0]) tail.unshift(0, tempArr[i]); } return tail.length;} // Driver Codelet firstArr = [ 3, 5, 1, 8 ];let secondArr = [ 3, 3, 5, 3, 8 ]; document.write(LCS(firstArr, secondArr)); // This code is contributed by gfgking </script>",
"e": 33875,
"s": 32622,
"text": null
},
{
"code": null,
"e": 33877,
"s": 33875,
"text": "3"
},
{
"code": null,
"e": 33926,
"s": 33879,
"text": "Time Complexity: O(NlogN)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 33941,
"s": 33926,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 33955,
"s": 33941,
"text": "GauravRajput1"
},
{
"code": null,
"e": 33965,
"s": 33955,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 33973,
"s": 33965,
"text": "gfgking"
},
{
"code": null,
"e": 33987,
"s": 33973,
"text": "Binary Search"
},
{
"code": null,
"e": 33995,
"s": 33987,
"text": "cpp-map"
},
{
"code": null,
"e": 33999,
"s": 33995,
"text": "LCS"
},
{
"code": null,
"e": 34003,
"s": 33999,
"text": "LIS"
},
{
"code": null,
"e": 34015,
"s": 34003,
"text": "subsequence"
},
{
"code": null,
"e": 34039,
"s": 34015,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 34046,
"s": 34039,
"text": "Arrays"
},
{
"code": null,
"e": 34066,
"s": 34046,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34071,
"s": 34066,
"text": "Hash"
},
{
"code": null,
"e": 34084,
"s": 34071,
"text": "Mathematical"
},
{
"code": null,
"e": 34094,
"s": 34084,
"text": "Searching"
},
{
"code": null,
"e": 34113,
"s": 34094,
"text": "Technical Scripter"
},
{
"code": null,
"e": 34120,
"s": 34113,
"text": "Arrays"
},
{
"code": null,
"e": 34130,
"s": 34120,
"text": "Searching"
},
{
"code": null,
"e": 34135,
"s": 34130,
"text": "Hash"
},
{
"code": null,
"e": 34155,
"s": 34135,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34168,
"s": 34155,
"text": "Mathematical"
},
{
"code": null,
"e": 34172,
"s": 34168,
"text": "LCS"
},
{
"code": null,
"e": 34186,
"s": 34172,
"text": "Binary Search"
},
{
"code": null,
"e": 34284,
"s": 34186,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34293,
"s": 34284,
"text": "Comments"
},
{
"code": null,
"e": 34306,
"s": 34293,
"text": "Old Comments"
},
{
"code": null,
"e": 34354,
"s": 34306,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 34398,
"s": 34354,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 34421,
"s": 34398,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 34453,
"s": 34421,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 34467,
"s": 34453,
"text": "Linear Search"
},
{
"code": null,
"e": 34496,
"s": 34467,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 34526,
"s": 34496,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 34560,
"s": 34526,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 34591,
"s": 34560,
"text": "Bellman–Ford Algorithm | DP-23"
}
] |
How to add Analog Clock in ReactJS ? - GeeksforGeeks
|
14 Dec, 2021
In this article, we are going to learn how we can add Analog Clock in ReactJs. React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies.
Approach: To add our Analog clock we are going to use the analog-clock-react package because it is powerful, lightweight, and fully customizable. After that, we will add our clock on our homepage using the installed package.
Create ReactJs Application: You can create a new ReactJs project using the below command:
npx create-react-app gfg
Install the required package: Now we will install the analog-clock-react package using the below command:
npm i analog-clock-react
Project Structure: It will look like this.
Adding Clock: In this example, we are going to add the clock on the homepage of our app using the package that we installed. For this, add the below content in the App.js file.
App.js
import AnalogClock from 'analog-clock-react'; export default function ReactClock() { let options = { width: "300px", border: true, borderColor: "#2e2e2e", baseColor: "#17a2b8", centerColor: "#459cff", centerBorderColor: "#ffffff", handColors: { second: "#d81c7a", minute: "#ffffff", hour: "#ffffff" } }; return ( <div> <h2>React Clock - GeeksforGeeks</h2> <AnalogClock {...options} /> </div> )}
Explanation: In the above example first, we are importing the AnalogClock component from the analog-clock-react package. After that, we are creating an options variable and storing the settings in this variable. Then we are using our AnalogClock component to display the clock.
Steps to run the application: Run the below command in the terminal to run the app.
npm start
Output:
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to set background images in ReactJS ?
How to navigate on path by button click in react router ?
How to create a table in ReactJS ?
ReactJS useNavigate() Hook
Axios in React: A Guide for Beginners
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24708,
"s": 24680,
"text": "\n14 Dec, 2021"
},
{
"code": null,
"e": 24980,
"s": 24708,
"text": "In this article, we are going to learn how we can add Analog Clock in ReactJs. React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies."
},
{
"code": null,
"e": 25205,
"s": 24980,
"text": "Approach: To add our Analog clock we are going to use the analog-clock-react package because it is powerful, lightweight, and fully customizable. After that, we will add our clock on our homepage using the installed package."
},
{
"code": null,
"e": 25295,
"s": 25205,
"text": "Create ReactJs Application: You can create a new ReactJs project using the below command:"
},
{
"code": null,
"e": 25320,
"s": 25295,
"text": "npx create-react-app gfg"
},
{
"code": null,
"e": 25426,
"s": 25320,
"text": "Install the required package: Now we will install the analog-clock-react package using the below command:"
},
{
"code": null,
"e": 25451,
"s": 25426,
"text": "npm i analog-clock-react"
},
{
"code": null,
"e": 25494,
"s": 25451,
"text": "Project Structure: It will look like this."
},
{
"code": null,
"e": 25671,
"s": 25494,
"text": "Adding Clock: In this example, we are going to add the clock on the homepage of our app using the package that we installed. For this, add the below content in the App.js file."
},
{
"code": null,
"e": 25678,
"s": 25671,
"text": "App.js"
},
{
"code": "import AnalogClock from 'analog-clock-react'; export default function ReactClock() { let options = { width: \"300px\", border: true, borderColor: \"#2e2e2e\", baseColor: \"#17a2b8\", centerColor: \"#459cff\", centerBorderColor: \"#ffffff\", handColors: { second: \"#d81c7a\", minute: \"#ffffff\", hour: \"#ffffff\" } }; return ( <div> <h2>React Clock - GeeksforGeeks</h2> <AnalogClock {...options} /> </div> )}",
"e": 26137,
"s": 25678,
"text": null
},
{
"code": null,
"e": 26415,
"s": 26137,
"text": "Explanation: In the above example first, we are importing the AnalogClock component from the analog-clock-react package. After that, we are creating an options variable and storing the settings in this variable. Then we are using our AnalogClock component to display the clock."
},
{
"code": null,
"e": 26499,
"s": 26415,
"text": "Steps to run the application: Run the below command in the terminal to run the app."
},
{
"code": null,
"e": 26509,
"s": 26499,
"text": "npm start"
},
{
"code": null,
"e": 26517,
"s": 26509,
"text": "Output:"
},
{
"code": null,
"e": 26533,
"s": 26517,
"text": "React-Questions"
},
{
"code": null,
"e": 26541,
"s": 26533,
"text": "ReactJS"
},
{
"code": null,
"e": 26558,
"s": 26541,
"text": "Web Technologies"
},
{
"code": null,
"e": 26656,
"s": 26558,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26665,
"s": 26656,
"text": "Comments"
},
{
"code": null,
"e": 26678,
"s": 26665,
"text": "Old Comments"
},
{
"code": null,
"e": 26720,
"s": 26678,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 26778,
"s": 26720,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 26813,
"s": 26778,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 26840,
"s": 26813,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 26878,
"s": 26840,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 26920,
"s": 26878,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26953,
"s": 26920,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27015,
"s": 26953,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27065,
"s": 27015,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
HTML - <isindex> tag
|
The HTML <isindex> tag is used for querying a document through a text field. The tag can be used anywhere but head tag is preferable. It is a deprecated tag and should not be used.
<!Doctype html>
<html>
<head>
<title>HTML isindex Tag</title>
<isindex prompt = "Search" />
</head>
</html>
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <isindex> tag also supports the following additional attributes −
This tag supports all the event attributes described in − HTML Events Reference
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2555,
"s": 2374,
"text": "The HTML <isindex> tag is used for querying a document through a text field. The tag can be used anywhere but head tag is preferable. It is a deprecated tag and should not be used."
},
{
"code": null,
"e": 2683,
"s": 2555,
"text": "<!Doctype html>\n<html>\n\n <head>\n <title>HTML isindex Tag</title>\n <isindex prompt = \"Search\" />\n </head>\n\n</html>"
},
{
"code": null,
"e": 2767,
"s": 2683,
"text": "This tag supports all the global attributes described in − HTML Attribute Reference"
},
{
"code": null,
"e": 2842,
"s": 2767,
"text": "The HTML <isindex> tag also supports the following additional attributes −"
},
{
"code": null,
"e": 2922,
"s": 2842,
"text": "This tag supports all the event attributes described in − HTML Events Reference"
},
{
"code": null,
"e": 2955,
"s": 2922,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2969,
"s": 2955,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3004,
"s": 2969,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3018,
"s": 3004,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3053,
"s": 3018,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3070,
"s": 3053,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3105,
"s": 3070,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3136,
"s": 3105,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3169,
"s": 3136,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3200,
"s": 3169,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3235,
"s": 3200,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3266,
"s": 3235,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3273,
"s": 3266,
"text": " Print"
},
{
"code": null,
"e": 3284,
"s": 3273,
"text": " Add Notes"
}
] |
How to generate ObjectID in MongoDB?
|
To generate ObjectID, use the below syntax in the MonogDB shell −
new ObjectId()
Let us implement the above syntax to generate ObjectID in MongoDB −
> new ObjectId()
ObjectId("5cd7bf2f6d78f205348bc646")
> new ObjectId()
ObjectId("5cd7bf316d78f205348bc647")
> new ObjectId()
ObjectId("5cd7bf336d78f205348bc648")
> new ObjectId()
ObjectId("5cd7bf346d78f205348bc649")
> new ObjectId()
ObjectId("5cd7bf356d78f205348bc64a")
> new ObjectId()
ObjectId("5cd7bf396d78f205348bc64b")
> new ObjectId()
ObjectId("5cd7bf3a6d78f205348bc64c")
As shown above, every time you will get a new ObjectId.
|
[
{
"code": null,
"e": 1128,
"s": 1062,
"text": "To generate ObjectID, use the below syntax in the MonogDB shell −"
},
{
"code": null,
"e": 1143,
"s": 1128,
"text": "new ObjectId()"
},
{
"code": null,
"e": 1211,
"s": 1143,
"text": "Let us implement the above syntax to generate ObjectID in MongoDB −"
},
{
"code": null,
"e": 1595,
"s": 1211,
"text": "> new ObjectId()\nObjectId(\"5cd7bf2f6d78f205348bc646\")\n\n> new ObjectId()\nObjectId(\"5cd7bf316d78f205348bc647\")\n\n> new ObjectId()\nObjectId(\"5cd7bf336d78f205348bc648\")\n\n> new ObjectId()\nObjectId(\"5cd7bf346d78f205348bc649\")\n\n> new ObjectId()\nObjectId(\"5cd7bf356d78f205348bc64a\")\n\n> new ObjectId()\nObjectId(\"5cd7bf396d78f205348bc64b\")\n\n> new ObjectId()\nObjectId(\"5cd7bf3a6d78f205348bc64c\")"
},
{
"code": null,
"e": 1651,
"s": 1595,
"text": "As shown above, every time you will get a new ObjectId."
}
] |
Express.js res.end() Function - GeeksforGeeks
|
05 May, 2021
The res.end() function is used to end the response process. This method actually comes from the Node core, specifically the response.end() method of HTTP.ServerResponse. Use to quickly end the response without any data.Syntax:
res.end([data] [, encoding])
Parameters: The default encoding is ‘utf8’ and the data parameter is basically the data with which the user wants to end the response.Return Value: It returns on Object.Installation of express module:
You can visit the link to Install express module. You can install this package by using this command.
You can visit the link to Install express module. You can install this package by using this command.
npm install express
After installing the express module, you can check your express version in command prompt using the command.
After installing the express module, you can check your express version in command prompt using the command.
npm version express
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.
node index.js
Example 1: Filename: index.js
javascript
var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ res.end();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Steps to run the program:
The project structure will look like this:
The project structure will look like this:
Make sure you have installed express module using the following command:
Make sure you have installed express module using the following command:
npm install express
Run index.js file using below command:
Run index.js file using below command:
node index.js
Output:
Output:
Server listening on PORT 3000
Now open your browser and go to http://localhost:3000/ and you will see blank response as this function is use to quickly end the response without any data.
Now open your browser and go to http://localhost:3000/ and you will see blank response as this function is use to quickly end the response without any data.
Example 2: Filename: index.js
javascript
var express = require('express');var app = express();var PORT = 3000; // With middlewareapp.use('/user', function(req, res, next){ console.log("/user called") res.end();}) app.get('/user', function(req, res){ console.log("User Page") res.end();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Run index.js file using below command:
node index.js
Now open your browser and go to http://localhost:3000/user, then you will see the following output on your console:
Server listening on PORT 3000
/user called
Reference: https://expressjs.com/en/4x/api.html#res.end
simmytarika5
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
How to update NPM ?
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": 29199,
"s": 29171,
"text": "\n05 May, 2021"
},
{
"code": null,
"e": 29428,
"s": 29199,
"text": "The res.end() function is used to end the response process. This method actually comes from the Node core, specifically the response.end() method of HTTP.ServerResponse. Use to quickly end the response without any data.Syntax: "
},
{
"code": null,
"e": 29457,
"s": 29428,
"text": "res.end([data] [, encoding])"
},
{
"code": null,
"e": 29660,
"s": 29457,
"text": "Parameters: The default encoding is ‘utf8’ and the data parameter is basically the data with which the user wants to end the response.Return Value: It returns on Object.Installation of express module: "
},
{
"code": null,
"e": 29764,
"s": 29660,
"text": "You can visit the link to Install express module. You can install this package by using this command. "
},
{
"code": null,
"e": 29868,
"s": 29764,
"text": "You can visit the link to Install express module. You can install this package by using this command. "
},
{
"code": null,
"e": 29888,
"s": 29868,
"text": "npm install express"
},
{
"code": null,
"e": 29999,
"s": 29888,
"text": "After installing the express module, you can check your express version in command prompt using the command. "
},
{
"code": null,
"e": 30110,
"s": 29999,
"text": "After installing the express module, you can check your express version in command prompt using the command. "
},
{
"code": null,
"e": 30130,
"s": 30110,
"text": "npm version express"
},
{
"code": null,
"e": 30267,
"s": 30130,
"text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. "
},
{
"code": null,
"e": 30404,
"s": 30267,
"text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. "
},
{
"code": null,
"e": 30418,
"s": 30404,
"text": "node index.js"
},
{
"code": null,
"e": 30450,
"s": 30418,
"text": "Example 1: Filename: index.js "
},
{
"code": null,
"e": 30461,
"s": 30450,
"text": "javascript"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ res.end();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 30717,
"s": 30461,
"text": null
},
{
"code": null,
"e": 30745,
"s": 30717,
"text": "Steps to run the program: "
},
{
"code": null,
"e": 30790,
"s": 30745,
"text": "The project structure will look like this: "
},
{
"code": null,
"e": 30835,
"s": 30790,
"text": "The project structure will look like this: "
},
{
"code": null,
"e": 30910,
"s": 30835,
"text": "Make sure you have installed express module using the following command: "
},
{
"code": null,
"e": 30985,
"s": 30910,
"text": "Make sure you have installed express module using the following command: "
},
{
"code": null,
"e": 31005,
"s": 30985,
"text": "npm install express"
},
{
"code": null,
"e": 31046,
"s": 31005,
"text": "Run index.js file using below command: "
},
{
"code": null,
"e": 31087,
"s": 31046,
"text": "Run index.js file using below command: "
},
{
"code": null,
"e": 31101,
"s": 31087,
"text": "node index.js"
},
{
"code": null,
"e": 31111,
"s": 31101,
"text": "Output: "
},
{
"code": null,
"e": 31121,
"s": 31111,
"text": "Output: "
},
{
"code": null,
"e": 31151,
"s": 31121,
"text": "Server listening on PORT 3000"
},
{
"code": null,
"e": 31311,
"s": 31151,
"text": " Now open your browser and go to http://localhost:3000/ and you will see blank response as this function is use to quickly end the response without any data. "
},
{
"code": null,
"e": 31472,
"s": 31313,
"text": "Now open your browser and go to http://localhost:3000/ and you will see blank response as this function is use to quickly end the response without any data. "
},
{
"code": null,
"e": 31504,
"s": 31472,
"text": "Example 2: Filename: index.js "
},
{
"code": null,
"e": 31515,
"s": 31504,
"text": "javascript"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; // With middlewareapp.use('/user', function(req, res, next){ console.log(\"/user called\") res.end();}) app.get('/user', function(req, res){ console.log(\"User Page\") res.end();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 31892,
"s": 31515,
"text": null
},
{
"code": null,
"e": 31933,
"s": 31892,
"text": "Run index.js file using below command: "
},
{
"code": null,
"e": 31947,
"s": 31933,
"text": "node index.js"
},
{
"code": null,
"e": 32065,
"s": 31947,
"text": "Now open your browser and go to http://localhost:3000/user, then you will see the following output on your console: "
},
{
"code": null,
"e": 32108,
"s": 32065,
"text": "Server listening on PORT 3000\n/user called"
},
{
"code": null,
"e": 32165,
"s": 32108,
"text": "Reference: https://expressjs.com/en/4x/api.html#res.end "
},
{
"code": null,
"e": 32178,
"s": 32165,
"text": "simmytarika5"
},
{
"code": null,
"e": 32189,
"s": 32178,
"text": "Express.js"
},
{
"code": null,
"e": 32197,
"s": 32189,
"text": "Node.js"
},
{
"code": null,
"e": 32214,
"s": 32197,
"text": "Web Technologies"
},
{
"code": null,
"e": 32312,
"s": 32214,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32321,
"s": 32312,
"text": "Comments"
},
{
"code": null,
"e": 32334,
"s": 32321,
"text": "Old Comments"
},
{
"code": null,
"e": 32367,
"s": 32334,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32415,
"s": 32367,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 32448,
"s": 32415,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 32477,
"s": 32448,
"text": "Node.js fs.readFile() Method"
},
{
"code": null,
"e": 32497,
"s": 32477,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 32553,
"s": 32497,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 32586,
"s": 32553,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32648,
"s": 32586,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 32691,
"s": 32648,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Factorial of a large number - GeeksforGeeks
|
19 Jan, 2022
Factorial of a non-negative integer, is the multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720.
We have discussed simple program for factorial.
How to compute factorial of 100 using a C/C++ program? Factorial of 100 has 158 digits. It is not possible to store these many digits even if we use long long int.
Examples :
Input : 100
Output : 933262154439441526816992388562667004-
907159682643816214685929638952175999-
932299156089414639761565182862536979-
208272237582511852109168640000000000-
00000000000000
Input :50
Output : 3041409320171337804361260816606476884-
4377641568960512000000000000
Following is a simple solution where we use an array to store individual digits of the result. The idea is to use basic mathematics for multiplication.
The following is a detailed algorithm for finding factorial.factorial(n) 1) Create an array ‘res[]’ of MAX size where MAX is number of maximum digits in output. 2) Initialize value stored in ‘res[]’ as 1 and initialize ‘res_size’ (size of ‘res[]’) as 1. 3) Do following for all numbers from x = 2 to n. ......a) Multiply x with res[] and update res[] and res_size to store the multiplication result.
How to multiply a number ‘x’ with the number stored in res[]? The idea is to use simple school mathematics. We one by one multiply x with every digit of res[]. The important point to note here is digits are multiplied from rightmost digit to leftmost digit. If we store digits in same order in res[], then it becomes difficult to update res[] without extra space. That is why res[] is maintained in reverse way, i.e., digits from right to left are stored.
multiply(res[], x) 1) Initialize carry as 0. 2) Do following for i = 0 to res_size – 1 ....a) Find value of res[i] * x + carry. Let this value be prod. ....b) Update res[i] by storing last digit of prod in it. ....c) Update carry by storing remaining digits in carry. 3) Put all digits of carry in res[] and increase res_size by number of digits in carry.
Example to show working of multiply(res[], x)
A number 5189 is stored in res[] as following.
res[] = {9, 8, 1, 5}
x = 10
Initialize carry = 0;
i = 0, prod = res[0]*x + carry = 9*10 + 0 = 90.
res[0] = 0, carry = 9
i = 1, prod = res[1]*x + carry = 8*10 + 9 = 89
res[1] = 9, carry = 8
i = 2, prod = res[2]*x + carry = 1*10 + 8 = 18
res[2] = 8, carry = 1
i = 3, prod = res[3]*x + carry = 5*10 + 1 = 51
res[3] = 1, carry = 5
res[4] = carry = 5
res[] = {0, 9, 8, 1, 5}
Below is the implementation of the above algorithm.
NOTE : In the below implementation, maximum digits in the output are assumed as 500. To find a factorial of a much larger number ( > 254), increase the size of an array or increase the value of MAX.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to compute factorial of big numbers#include<iostream>using namespace std; // Maximum number of digits in output#define MAX 500 int multiply(int x, int res[], int res_size); // This function finds factorial of large numbers// and prints themvoid factorial(int n){ int res[MAX]; // Initialize result res[0] = 1; int res_size = 1; // Apply simple factorial formula n! = 1 * 2 * 3 * 4...*n for (int x=2; x<=n; x++) res_size = multiply(x, res, res_size); cout << "Factorial of given number is \n"; for (int i=res_size-1; i>=0; i--) cout << res[i];} // This function multiplies x with the number// represented by res[].// res_size is size of res[] or number of digits in the// number represented by res[]. This function uses simple// school mathematics for multiplication.// This function may value of res_size and returns the// new value of res_sizeint multiply(int x, int res[], int res_size){ int carry = 0; // Initialize carry // One by one multiply n with individual digits of res[] for (int i=0; i<res_size; i++) { int prod = res[i] * x + carry; // Store last digit of 'prod' in res[] res[i] = prod % 10; // Put rest in carry carry = prod/10; } // Put carry in res and increase result size while (carry) { res[res_size] = carry%10; carry = carry/10; res_size++; } return res_size;} // Driver programint main(){ factorial(100); return 0;}
// JAVA program to compute factorial// of big numbersclass GFG { // This function finds factorial of // large numbers and prints them static void factorial(int n) { int res[] = new int[500]; // Initialize result res[0] = 1; int res_size = 1; // Apply simple factorial formula // n! = 1 * 2 * 3 * 4...*n for (int x = 2; x <= n; x++) res_size = multiply(x, res, res_size); System.out.println("Factorial of given number is "); for (int i = res_size - 1; i >= 0; i--) System.out.print(res[i]); } // This function multiplies x with the number // represented by res[]. res_size is size of res[] or // number of digits in the number represented by res[]. // This function uses simple school mathematics for // multiplication. This function may value of res_size // and returns the new value of res_size static int multiply(int x, int res[], int res_size) { int carry = 0; // Initialize carry // One by one multiply n with individual // digits of res[] for (int i = 0; i < res_size; i++) { int prod = res[i] * x + carry; res[i] = prod % 10; // Store last digit of // 'prod' in res[] carry = prod/10; // Put rest in carry } // Put carry in res and increase result size while (carry!=0) { res[res_size] = carry % 10; carry = carry / 10; res_size++; } return res_size; } // Driver program public static void main(String args[]) { factorial(100); }}//This code is contributed by Nikita Tiwari
# Python program to compute factorial# of big numbers import sys # This function finds factorial of large# numbers and prints themdef factorial( n) : res = [None]*500 # Initialize result res[0] = 1 res_size = 1 # Apply simple factorial formula # n! = 1 * 2 * 3 * 4...*n x = 2 while x <= n : res_size = multiply(x, res, res_size) x = x + 1 print ("Factorial of given number is") i = res_size-1 while i >= 0 : sys.stdout.write(str(res[i])) sys.stdout.flush() i = i - 1 # This function multiplies x with the number# represented by res[]. res_size is size of res[]# or number of digits in the number represented# by res[]. This function uses simple school# mathematics for multiplication. This function# may value of res_size and returns the new value# of res_sizedef multiply(x, res,res_size) : carry = 0 # Initialize carry # One by one multiply n with individual # digits of res[] i = 0 while i < res_size : prod = res[i] *x + carry res[i] = prod % 10; # Store last digit of # 'prod' in res[] # make sure floor division is used carry = prod//10; # Put rest in carry i = i + 1 # Put carry in res and increase result size while (carry) : res[res_size] = carry % 10 # make sure floor division is used # to avoid floating value carry = carry // 10 res_size = res_size + 1 return res_size # Driver programfactorial(100) #This code is contributed by Nikita Tiwari.
// C# program to compute// factorial of big numbersusing System; class GFG{ // This function finds factorial // of large numbers and prints them static void factorial(int n) { int []res = new int[500]; // Initialize result res[0] = 1; int res_size = 1; // Apply simple factorial formula // n! = 1 * 2 * 3 * 4...*n for (int x = 2; x <= n; x++) res_size = multiply(x, res, res_size); Console.WriteLine("Factorial of " + "given number is "); for (int i = res_size - 1; i >= 0; i--) Console.Write(res[i]); } // This function multiplies x // with the number represented // by res[]. res_size is size // of res[] or number of digits // in the number represented by // res[]. This function uses // simple school mathematics for // multiplication. This function // may value of res_size and // returns the new value of res_size static int multiply(int x, int []res, int res_size) { int carry = 0; // Initialize carry // One by one multiply n with // individual digits of res[] for (int i = 0; i < res_size; i++) { int prod = res[i] * x + carry; res[i] = prod % 10; // Store last digit of // 'prod' in res[] carry = prod / 10; // Put rest in carry } // Put carry in res and // increase result size while (carry != 0) { res[res_size] = carry % 10; carry = carry / 10; res_size++; } return res_size; } // Driver Code static public void Main () { factorial(100); }} // This code is contributed by ajit
<?php// PHP program to compute factorial// of big numbers // Maximum number of digits in output$MAX = 500; // This function finds factorial of// large numbers and prints themfunction factorial($n){ global $MAX; $res = array_fill(0, $MAX, 0); // Initialize result $res[0] = 1; $res_size = 1; // Apply simple factorial formula // n! = 1 * 2 * 3 * 4...*n for ($x = 2; $x <= $n; $x++) $res_size = multiply($x, $res, $res_size); echo "Factorial of given number is \n"; for ($i = $res_size - 1; $i >= 0; $i--) echo $res[$i];} // This function multiplies x with the number// represented by res[].// res_size is size of res[] or number of// digits in the number represented by res[].// This function uses simple school mathematics// for multiplication. This function may value // of res_size and returns the new value of res_sizefunction multiply($x, &$res, $res_size){ $carry = 0; // Initialize carry // One by one multiply n with individual // digits of res[] for ($i = 0; $i < $res_size; $i++) { $prod = $res[$i] * $x + $carry; // Store last digit of 'prod' in res[] $res[$i] = $prod % 10; // Put rest in carry $carry = (int)($prod / 10); } // Put carry in res and increase // result size while ($carry) { $res[$res_size] = $carry % 10; $carry = (int)($carry / 10); $res_size++; } return $res_size;} // Driver Codefactorial(100); // This code is contributed by chandan_jnu?>
<script> // Javascript program to compute factorial of big numbers // This function finds factorial of large numbers// and prints themfunction factorial(n){ let res = new Array(500); // Initialize result res[0] = 1; let res_size = 1; // Apply simple factorial formula n! = 1 * 2 * 3 * 4...*n for (let x=2; x<=n; x++) res_size = multiply(x, res, res_size); document.write("Factorial of given number is " + "<br>"); for (let i=res_size-1; i>=0; i--) document.write(res[i]);} // This function multiplies x with the number// represented by res[].// res_size is size of res[] or number of digits in the// number represented by res[]. This function uses simple// school mathematics for multiplication.// This function may value of res_size and returns the// new value of res_sizefunction multiply(x, res, res_size){ let carry = 0; // Initialize carry // One by one multiply n with individual digits of res[] for (let i=0; i<res_size; i++) { let prod = res[i] * x + carry; // Store last digit of 'prod' in res[] res[i] = prod % 10; // Put rest in carry carry = Math.floor(prod/10); } // Put carry in res and increase result size while (carry) { res[res_size] = carry%10; carry = Math.floor(carry/10); res_size++; } return res_size;} // Driver program factorial(100); // This code is contributed by Mayank Tyagi </script>
Factorial of given number is
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
The above approach can be optimized in many ways. We will soon be discussing an optimized solution for the same.This article is contributed by Harshit Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Big Integer can also be used to calculate factorial of large numbers.
Java
// Java program to find large// factorials using BigIntegerimport java.math.BigInteger;import java.util.Scanner; public class Example { // Returns Factorial of N static BigInteger factorial(int N) { // Initialize result BigInteger f = new BigInteger("1"); // Or BigInteger.ONE // Multiply f with 2, 3, ...N for (int i = 2; i <= N; i++) f = f.multiply(BigInteger.valueOf(i)); return f; } // Driver method public static void main(String args[]) throws Exception { int N = 20; System.out.println(factorial(N)); }}
2432902008176640000
Linked List can also be used, this approach will not waste any extra space.
C++
#include <bits/stdc++.h> using namespace std; #define rep(i, a, b) for (int i = a; i <= b; i++) using namespace std;// Made a class node containing data and previous pointer as// we are using tail pointerclass Node {public: int data; Node* prev; Node(int n) { data = n; prev = NULL; }}; void Multiply(Node* tail, int n){ Node *temp = tail, *prevNode = tail; // Temp variable for keeping tail int carry = 0; while (temp != NULL) { int data = temp->data * n + carry; temp->data = data % 10; // stores the last digit carry = data / 10; prevNode = temp; temp = temp->prev; // Moving temp by 1 prevNode will // now denote temp } // If carry is greater than 0 then we create another // node for it. while (carry != 0) { prevNode->prev = new Node((int)(carry % 10)); carry /= 10; prevNode = prevNode->prev; }} void print(Node* tail){ if (tail == NULL) // Using tail recursion return; print(tail->prev); cout << tail->data; // Print linked list in reverse order} // Driver codeint main(){ int n = 20; Node tail(1); // Create a node and initialise it by 1 rep(i, 2, n) Multiply(&tail, i); // Run a loop from 2 to n and // multiply with tail's i print(&tail); // Print the linked list cout << endl; return 0;} // This code is contributed by Kingshuk Deb
2432902008176640000
jit_t
Chandan_Kumar
pubg_wala
Versus
nirala96
mayanktyagi1709
itskingshuk
simranarora5sos
rajeev0719singh
amartyaghoshgfg
BrowserStack
factorial
MakeMyTrip
MAQ Software
Microsoft
Morgan Stanley
number-theory
Philips
Combinatorial
Mathematical
Strings
Morgan Stanley
Microsoft
MakeMyTrip
MAQ Software
Philips
BrowserStack
number-theory
Strings
Mathematical
Combinatorial
factorial
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
Make all combinations of size k
Print all subsets of given size of a set
Print all permutations in sorted (lexicographic) order
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Merge two sorted arrays
|
[
{
"code": null,
"e": 24447,
"s": 24419,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 24606,
"s": 24447,
"text": "Factorial of a non-negative integer, is the multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720."
},
{
"code": null,
"e": 24654,
"s": 24606,
"text": "We have discussed simple program for factorial."
},
{
"code": null,
"e": 24819,
"s": 24654,
"text": "How to compute factorial of 100 using a C/C++ program? Factorial of 100 has 158 digits. It is not possible to store these many digits even if we use long long int. "
},
{
"code": null,
"e": 24831,
"s": 24819,
"text": "Examples : "
},
{
"code": null,
"e": 25152,
"s": 24831,
"text": "Input : 100\nOutput : 933262154439441526816992388562667004-\n 907159682643816214685929638952175999-\n 932299156089414639761565182862536979-\n 208272237582511852109168640000000000-\n 00000000000000\n\nInput :50\nOutput : 3041409320171337804361260816606476884-\n 4377641568960512000000000000"
},
{
"code": null,
"e": 25304,
"s": 25152,
"text": "Following is a simple solution where we use an array to store individual digits of the result. The idea is to use basic mathematics for multiplication."
},
{
"code": null,
"e": 25704,
"s": 25304,
"text": "The following is a detailed algorithm for finding factorial.factorial(n) 1) Create an array ‘res[]’ of MAX size where MAX is number of maximum digits in output. 2) Initialize value stored in ‘res[]’ as 1 and initialize ‘res_size’ (size of ‘res[]’) as 1. 3) Do following for all numbers from x = 2 to n. ......a) Multiply x with res[] and update res[] and res_size to store the multiplication result."
},
{
"code": null,
"e": 26160,
"s": 25704,
"text": "How to multiply a number ‘x’ with the number stored in res[]? The idea is to use simple school mathematics. We one by one multiply x with every digit of res[]. The important point to note here is digits are multiplied from rightmost digit to leftmost digit. If we store digits in same order in res[], then it becomes difficult to update res[] without extra space. That is why res[] is maintained in reverse way, i.e., digits from right to left are stored."
},
{
"code": null,
"e": 26516,
"s": 26160,
"text": "multiply(res[], x) 1) Initialize carry as 0. 2) Do following for i = 0 to res_size – 1 ....a) Find value of res[i] * x + carry. Let this value be prod. ....b) Update res[i] by storing last digit of prod in it. ....c) Update carry by storing remaining digits in carry. 3) Put all digits of carry in res[] and increase res_size by number of digits in carry."
},
{
"code": null,
"e": 26987,
"s": 26516,
"text": "Example to show working of multiply(res[], x)\nA number 5189 is stored in res[] as following.\nres[] = {9, 8, 1, 5}\nx = 10\n\nInitialize carry = 0;\n\ni = 0, prod = res[0]*x + carry = 9*10 + 0 = 90.\nres[0] = 0, carry = 9\n\ni = 1, prod = res[1]*x + carry = 8*10 + 9 = 89\nres[1] = 9, carry = 8\n\ni = 2, prod = res[2]*x + carry = 1*10 + 8 = 18\nres[2] = 8, carry = 1\n\ni = 3, prod = res[3]*x + carry = 5*10 + 1 = 51\nres[3] = 1, carry = 5\n\nres[4] = carry = 5\n\nres[] = {0, 9, 8, 1, 5} "
},
{
"code": null,
"e": 27040,
"s": 26987,
"text": "Below is the implementation of the above algorithm. "
},
{
"code": null,
"e": 27239,
"s": 27040,
"text": "NOTE : In the below implementation, maximum digits in the output are assumed as 500. To find a factorial of a much larger number ( > 254), increase the size of an array or increase the value of MAX."
},
{
"code": null,
"e": 27243,
"s": 27239,
"text": "C++"
},
{
"code": null,
"e": 27248,
"s": 27243,
"text": "Java"
},
{
"code": null,
"e": 27256,
"s": 27248,
"text": "Python3"
},
{
"code": null,
"e": 27259,
"s": 27256,
"text": "C#"
},
{
"code": null,
"e": 27263,
"s": 27259,
"text": "PHP"
},
{
"code": null,
"e": 27274,
"s": 27263,
"text": "Javascript"
},
{
"code": "// C++ program to compute factorial of big numbers#include<iostream>using namespace std; // Maximum number of digits in output#define MAX 500 int multiply(int x, int res[], int res_size); // This function finds factorial of large numbers// and prints themvoid factorial(int n){ int res[MAX]; // Initialize result res[0] = 1; int res_size = 1; // Apply simple factorial formula n! = 1 * 2 * 3 * 4...*n for (int x=2; x<=n; x++) res_size = multiply(x, res, res_size); cout << \"Factorial of given number is \\n\"; for (int i=res_size-1; i>=0; i--) cout << res[i];} // This function multiplies x with the number// represented by res[].// res_size is size of res[] or number of digits in the// number represented by res[]. This function uses simple// school mathematics for multiplication.// This function may value of res_size and returns the// new value of res_sizeint multiply(int x, int res[], int res_size){ int carry = 0; // Initialize carry // One by one multiply n with individual digits of res[] for (int i=0; i<res_size; i++) { int prod = res[i] * x + carry; // Store last digit of 'prod' in res[] res[i] = prod % 10; // Put rest in carry carry = prod/10; } // Put carry in res and increase result size while (carry) { res[res_size] = carry%10; carry = carry/10; res_size++; } return res_size;} // Driver programint main(){ factorial(100); return 0;}",
"e": 28771,
"s": 27274,
"text": null
},
{
"code": "// JAVA program to compute factorial// of big numbersclass GFG { // This function finds factorial of // large numbers and prints them static void factorial(int n) { int res[] = new int[500]; // Initialize result res[0] = 1; int res_size = 1; // Apply simple factorial formula // n! = 1 * 2 * 3 * 4...*n for (int x = 2; x <= n; x++) res_size = multiply(x, res, res_size); System.out.println(\"Factorial of given number is \"); for (int i = res_size - 1; i >= 0; i--) System.out.print(res[i]); } // This function multiplies x with the number // represented by res[]. res_size is size of res[] or // number of digits in the number represented by res[]. // This function uses simple school mathematics for // multiplication. This function may value of res_size // and returns the new value of res_size static int multiply(int x, int res[], int res_size) { int carry = 0; // Initialize carry // One by one multiply n with individual // digits of res[] for (int i = 0; i < res_size; i++) { int prod = res[i] * x + carry; res[i] = prod % 10; // Store last digit of // 'prod' in res[] carry = prod/10; // Put rest in carry } // Put carry in res and increase result size while (carry!=0) { res[res_size] = carry % 10; carry = carry / 10; res_size++; } return res_size; } // Driver program public static void main(String args[]) { factorial(100); }}//This code is contributed by Nikita Tiwari",
"e": 30488,
"s": 28771,
"text": null
},
{
"code": "# Python program to compute factorial# of big numbers import sys # This function finds factorial of large# numbers and prints themdef factorial( n) : res = [None]*500 # Initialize result res[0] = 1 res_size = 1 # Apply simple factorial formula # n! = 1 * 2 * 3 * 4...*n x = 2 while x <= n : res_size = multiply(x, res, res_size) x = x + 1 print (\"Factorial of given number is\") i = res_size-1 while i >= 0 : sys.stdout.write(str(res[i])) sys.stdout.flush() i = i - 1 # This function multiplies x with the number# represented by res[]. res_size is size of res[]# or number of digits in the number represented# by res[]. This function uses simple school# mathematics for multiplication. This function# may value of res_size and returns the new value# of res_sizedef multiply(x, res,res_size) : carry = 0 # Initialize carry # One by one multiply n with individual # digits of res[] i = 0 while i < res_size : prod = res[i] *x + carry res[i] = prod % 10; # Store last digit of # 'prod' in res[] # make sure floor division is used carry = prod//10; # Put rest in carry i = i + 1 # Put carry in res and increase result size while (carry) : res[res_size] = carry % 10 # make sure floor division is used # to avoid floating value carry = carry // 10 res_size = res_size + 1 return res_size # Driver programfactorial(100) #This code is contributed by Nikita Tiwari.",
"e": 32065,
"s": 30488,
"text": null
},
{
"code": "// C# program to compute// factorial of big numbersusing System; class GFG{ // This function finds factorial // of large numbers and prints them static void factorial(int n) { int []res = new int[500]; // Initialize result res[0] = 1; int res_size = 1; // Apply simple factorial formula // n! = 1 * 2 * 3 * 4...*n for (int x = 2; x <= n; x++) res_size = multiply(x, res, res_size); Console.WriteLine(\"Factorial of \" + \"given number is \"); for (int i = res_size - 1; i >= 0; i--) Console.Write(res[i]); } // This function multiplies x // with the number represented // by res[]. res_size is size // of res[] or number of digits // in the number represented by // res[]. This function uses // simple school mathematics for // multiplication. This function // may value of res_size and // returns the new value of res_size static int multiply(int x, int []res, int res_size) { int carry = 0; // Initialize carry // One by one multiply n with // individual digits of res[] for (int i = 0; i < res_size; i++) { int prod = res[i] * x + carry; res[i] = prod % 10; // Store last digit of // 'prod' in res[] carry = prod / 10; // Put rest in carry } // Put carry in res and // increase result size while (carry != 0) { res[res_size] = carry % 10; carry = carry / 10; res_size++; } return res_size; } // Driver Code static public void Main () { factorial(100); }} // This code is contributed by ajit",
"e": 33895,
"s": 32065,
"text": null
},
{
"code": "<?php// PHP program to compute factorial// of big numbers // Maximum number of digits in output$MAX = 500; // This function finds factorial of// large numbers and prints themfunction factorial($n){ global $MAX; $res = array_fill(0, $MAX, 0); // Initialize result $res[0] = 1; $res_size = 1; // Apply simple factorial formula // n! = 1 * 2 * 3 * 4...*n for ($x = 2; $x <= $n; $x++) $res_size = multiply($x, $res, $res_size); echo \"Factorial of given number is \\n\"; for ($i = $res_size - 1; $i >= 0; $i--) echo $res[$i];} // This function multiplies x with the number// represented by res[].// res_size is size of res[] or number of// digits in the number represented by res[].// This function uses simple school mathematics// for multiplication. This function may value // of res_size and returns the new value of res_sizefunction multiply($x, &$res, $res_size){ $carry = 0; // Initialize carry // One by one multiply n with individual // digits of res[] for ($i = 0; $i < $res_size; $i++) { $prod = $res[$i] * $x + $carry; // Store last digit of 'prod' in res[] $res[$i] = $prod % 10; // Put rest in carry $carry = (int)($prod / 10); } // Put carry in res and increase // result size while ($carry) { $res[$res_size] = $carry % 10; $carry = (int)($carry / 10); $res_size++; } return $res_size;} // Driver Codefactorial(100); // This code is contributed by chandan_jnu?>",
"e": 35412,
"s": 33895,
"text": null
},
{
"code": "<script> // Javascript program to compute factorial of big numbers // This function finds factorial of large numbers// and prints themfunction factorial(n){ let res = new Array(500); // Initialize result res[0] = 1; let res_size = 1; // Apply simple factorial formula n! = 1 * 2 * 3 * 4...*n for (let x=2; x<=n; x++) res_size = multiply(x, res, res_size); document.write(\"Factorial of given number is \" + \"<br>\"); for (let i=res_size-1; i>=0; i--) document.write(res[i]);} // This function multiplies x with the number// represented by res[].// res_size is size of res[] or number of digits in the// number represented by res[]. This function uses simple// school mathematics for multiplication.// This function may value of res_size and returns the// new value of res_sizefunction multiply(x, res, res_size){ let carry = 0; // Initialize carry // One by one multiply n with individual digits of res[] for (let i=0; i<res_size; i++) { let prod = res[i] * x + carry; // Store last digit of 'prod' in res[] res[i] = prod % 10; // Put rest in carry carry = Math.floor(prod/10); } // Put carry in res and increase result size while (carry) { res[res_size] = carry%10; carry = Math.floor(carry/10); res_size++; } return res_size;} // Driver program factorial(100); // This code is contributed by Mayank Tyagi </script>",
"e": 36861,
"s": 35412,
"text": null
},
{
"code": null,
"e": 37050,
"s": 36861,
"text": "Factorial of given number is \n93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000"
},
{
"code": null,
"e": 37334,
"s": 37050,
"text": "The above approach can be optimized in many ways. We will soon be discussing an optimized solution for the same.This article is contributed by Harshit Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 37404,
"s": 37334,
"text": "Big Integer can also be used to calculate factorial of large numbers."
},
{
"code": null,
"e": 37409,
"s": 37404,
"text": "Java"
},
{
"code": "// Java program to find large// factorials using BigIntegerimport java.math.BigInteger;import java.util.Scanner; public class Example { // Returns Factorial of N static BigInteger factorial(int N) { // Initialize result BigInteger f = new BigInteger(\"1\"); // Or BigInteger.ONE // Multiply f with 2, 3, ...N for (int i = 2; i <= N; i++) f = f.multiply(BigInteger.valueOf(i)); return f; } // Driver method public static void main(String args[]) throws Exception { int N = 20; System.out.println(factorial(N)); }}",
"e": 38023,
"s": 37409,
"text": null
},
{
"code": null,
"e": 38043,
"s": 38023,
"text": "2432902008176640000"
},
{
"code": null,
"e": 38119,
"s": 38043,
"text": "Linked List can also be used, this approach will not waste any extra space."
},
{
"code": null,
"e": 38123,
"s": 38119,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h> using namespace std; #define rep(i, a, b) for (int i = a; i <= b; i++) using namespace std;// Made a class node containing data and previous pointer as// we are using tail pointerclass Node {public: int data; Node* prev; Node(int n) { data = n; prev = NULL; }}; void Multiply(Node* tail, int n){ Node *temp = tail, *prevNode = tail; // Temp variable for keeping tail int carry = 0; while (temp != NULL) { int data = temp->data * n + carry; temp->data = data % 10; // stores the last digit carry = data / 10; prevNode = temp; temp = temp->prev; // Moving temp by 1 prevNode will // now denote temp } // If carry is greater than 0 then we create another // node for it. while (carry != 0) { prevNode->prev = new Node((int)(carry % 10)); carry /= 10; prevNode = prevNode->prev; }} void print(Node* tail){ if (tail == NULL) // Using tail recursion return; print(tail->prev); cout << tail->data; // Print linked list in reverse order} // Driver codeint main(){ int n = 20; Node tail(1); // Create a node and initialise it by 1 rep(i, 2, n) Multiply(&tail, i); // Run a loop from 2 to n and // multiply with tail's i print(&tail); // Print the linked list cout << endl; return 0;} // This code is contributed by Kingshuk Deb",
"e": 39585,
"s": 38123,
"text": null
},
{
"code": null,
"e": 39605,
"s": 39585,
"text": "2432902008176640000"
},
{
"code": null,
"e": 39611,
"s": 39605,
"text": "jit_t"
},
{
"code": null,
"e": 39625,
"s": 39611,
"text": "Chandan_Kumar"
},
{
"code": null,
"e": 39635,
"s": 39625,
"text": "pubg_wala"
},
{
"code": null,
"e": 39642,
"s": 39635,
"text": "Versus"
},
{
"code": null,
"e": 39651,
"s": 39642,
"text": "nirala96"
},
{
"code": null,
"e": 39667,
"s": 39651,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 39679,
"s": 39667,
"text": "itskingshuk"
},
{
"code": null,
"e": 39695,
"s": 39679,
"text": "simranarora5sos"
},
{
"code": null,
"e": 39711,
"s": 39695,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 39727,
"s": 39711,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 39740,
"s": 39727,
"text": "BrowserStack"
},
{
"code": null,
"e": 39750,
"s": 39740,
"text": "factorial"
},
{
"code": null,
"e": 39761,
"s": 39750,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 39774,
"s": 39761,
"text": "MAQ Software"
},
{
"code": null,
"e": 39784,
"s": 39774,
"text": "Microsoft"
},
{
"code": null,
"e": 39799,
"s": 39784,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 39813,
"s": 39799,
"text": "number-theory"
},
{
"code": null,
"e": 39821,
"s": 39813,
"text": "Philips"
},
{
"code": null,
"e": 39835,
"s": 39821,
"text": "Combinatorial"
},
{
"code": null,
"e": 39848,
"s": 39835,
"text": "Mathematical"
},
{
"code": null,
"e": 39856,
"s": 39848,
"text": "Strings"
},
{
"code": null,
"e": 39871,
"s": 39856,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 39881,
"s": 39871,
"text": "Microsoft"
},
{
"code": null,
"e": 39892,
"s": 39881,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 39905,
"s": 39892,
"text": "MAQ Software"
},
{
"code": null,
"e": 39913,
"s": 39905,
"text": "Philips"
},
{
"code": null,
"e": 39926,
"s": 39913,
"text": "BrowserStack"
},
{
"code": null,
"e": 39940,
"s": 39926,
"text": "number-theory"
},
{
"code": null,
"e": 39948,
"s": 39940,
"text": "Strings"
},
{
"code": null,
"e": 39961,
"s": 39948,
"text": "Mathematical"
},
{
"code": null,
"e": 39975,
"s": 39961,
"text": "Combinatorial"
},
{
"code": null,
"e": 39985,
"s": 39975,
"text": "factorial"
},
{
"code": null,
"e": 40083,
"s": 39985,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40092,
"s": 40083,
"text": "Comments"
},
{
"code": null,
"e": 40105,
"s": 40092,
"text": "Old Comments"
},
{
"code": null,
"e": 40182,
"s": 40105,
"text": "Find the Number of Permutations that satisfy the given condition in an array"
},
{
"code": null,
"e": 40239,
"s": 40182,
"text": "Python program to get all subsets of given size of a set"
},
{
"code": null,
"e": 40271,
"s": 40239,
"text": "Make all combinations of size k"
},
{
"code": null,
"e": 40312,
"s": 40271,
"text": "Print all subsets of given size of a set"
},
{
"code": null,
"e": 40367,
"s": 40312,
"text": "Print all permutations in sorted (lexicographic) order"
},
{
"code": null,
"e": 40397,
"s": 40367,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 40412,
"s": 40397,
"text": "C++ Data Types"
},
{
"code": null,
"e": 40455,
"s": 40412,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 40474,
"s": 40455,
"text": "Coin Change | DP-7"
}
] |
Bugzilla - Installation
|
The Bugzilla GIT website is the best way to get Bugzilla. Download and install GIT from the website − https://git-scm.com/download and Run it.
git clone --branch release-X.X-stable https://github.com/bugzilla/bugzilla
C:\bugzilla
Where, "X.X" is the 2-digit version number of the stable release of Bugzilla (e.g. 5.0)
The another way to download Bugzilla is from the following link − https://www.bugzilla.org/download/ and move down to the Stable Release section and select the latest one from the list as shown in the following screenshot. Click on Download Bugzilla 5.0.3.
Bugzilla comes as a 'tarball' (.tar.gz extension), which any competent Windows archiving tool should be able to open.
Bugzilla requires a number of Perl modules to be installed. Some of them are mandatory, and some others, which enable additional features, are optional.
In ActivePerl, these modules are available in the ActiveState repository, and are installed with the ppm tool. Either it can use it on the command line or just type ppm and the user will get a GUI.
Install the following mandatory modules with the following command.
ppm install <modulename>
Some of the most important PERL modules have been described below.
CGI.pm − It is an extensively used Perl module for programming the CGI (Common Gateway Interface) web applications. It helps to provide a consistent API for receiving and processing user inputs.
CGI.pm − It is an extensively used Perl module for programming the CGI (Common Gateway Interface) web applications. It helps to provide a consistent API for receiving and processing user inputs.
Digest-SHA − The Digest-SHA1 module allows you to use the NIST SHA-1 message digest algorithm from within the Perl programs. The algorithm takes as input a message of arbitrary length and produces as output a 160-bit "fingerprint" or "message digest" of the input.
Digest-SHA − The Digest-SHA1 module allows you to use the NIST SHA-1 message digest algorithm from within the Perl programs. The algorithm takes as input a message of arbitrary length and produces as output a 160-bit "fingerprint" or "message digest" of the input.
TimeDate − TimeDate is a class for the representation of time/date combinations, and is part of the Perl TimeDate project.
TimeDate − TimeDate is a class for the representation of time/date combinations, and is part of the Perl TimeDate project.
DateTime − DateTime is a class for the representation of date/time combinations, and is part of the Perl DateTime project.
DateTime − DateTime is a class for the representation of date/time combinations, and is part of the Perl DateTime project.
DateTime-TimeZone − This class is the base class for all time zone objects. A time zone is represented internally as a set of observances, each of which describes the offset from GMT for a given time period.
DateTime-TimeZone − This class is the base class for all time zone objects. A time zone is represented internally as a set of observances, each of which describes the offset from GMT for a given time period.
DBI − It is the standard database interface module for Perl. It defines a set of methods, variables and conventions that provide a consistent database interface independent of the actual database being used.
DBI − It is the standard database interface module for Perl. It defines a set of methods, variables and conventions that provide a consistent database interface independent of the actual database being used.
Template-Toolkit − The Template Toolkit is a collection of Perl modules, which implement a fast, flexible, powerful and extensible template processing system. It can be used for processing any kind of text documents and is input-agnostic.
Template-Toolkit − The Template Toolkit is a collection of Perl modules, which implement a fast, flexible, powerful and extensible template processing system. It can be used for processing any kind of text documents and is input-agnostic.
Email-Sender − The Email-Sender replaces the old and problematic email send library, which did a decent job at handling the simple email sending tasks, but it was not suitable for serious use for a several reasons.
Email-Sender − The Email-Sender replaces the old and problematic email send library, which did a decent job at handling the simple email sending tasks, but it was not suitable for serious use for a several reasons.
Email-MIME − This is an extension of the Email-Simple module. It is majorly used to handle MIME encoded messages. It takes a message as a string, splits it into its constituent parts and allows you to access the different parts of the message.
Email-MIME − This is an extension of the Email-Simple module. It is majorly used to handle MIME encoded messages. It takes a message as a string, splits it into its constituent parts and allows you to access the different parts of the message.
URI − A Uniform Resource Identifier is a compact string of characters that identifies an abstract or physical resource. A URI can be further classified as either a Uniform Resource Locator (URL) or a Uniform Resource Name (URN).
URI − A Uniform Resource Identifier is a compact string of characters that identifies an abstract or physical resource. A URI can be further classified as either a Uniform Resource Locator (URL) or a Uniform Resource Name (URN).
List-MoreUtils − It provides some trivial but commonly needed functionality on lists, which is not going to go into the List-Util module.
List-MoreUtils − It provides some trivial but commonly needed functionality on lists, which is not going to go into the List-Util module.
Math-Random-ISAAC − The ISAAC (Indirection, Shift, Accumulate, Add, and Count) algorithm is designed to take some seed information and produce seemingly random results as the output.
Math-Random-ISAAC − The ISAAC (Indirection, Shift, Accumulate, Add, and Count) algorithm is designed to take some seed information and produce seemingly random results as the output.
File-Slurp − This module provides subs that allow you to read or write files with one simple call. They are designed to be simple, have flexible ways to pass in or get the file content and are very efficient.
File-Slurp − This module provides subs that allow you to read or write files with one simple call. They are designed to be simple, have flexible ways to pass in or get the file content and are very efficient.
JSON-XS − This module converts the Perl data structures to JSON and vice versa. The primary goal of JSON-XS is to be correct and its secondary goal is to be fast.
JSON-XS − This module converts the Perl data structures to JSON and vice versa. The primary goal of JSON-XS is to be correct and its secondary goal is to be fast.
Win32 − The Win32 module contains functions to access Win32 APIs.
Win32 − The Win32 module contains functions to access Win32 APIs.
Win32-API − With this module, you can import and call arbitrary functions from the Win32's Dynamic Link Libraries (DLL), without having to write an XS extension.
Win32-API − With this module, you can import and call arbitrary functions from the Win32's Dynamic Link Libraries (DLL), without having to write an XS extension.
DateTime-TimeZone-Local-Win32 − This module provides methods for determining the local time zone on a Windows platform.
DateTime-TimeZone-Local-Win32 − This module provides methods for determining the local time zone on a Windows platform.
The following modules enable various optional Bugzilla features; try to install these based on your requirements −
GD − The GD module is only required if you want graphical reports.
GD − The GD module is only required if you want graphical reports.
Chart − This module is only required if you would want graphical reports as the GD module.
Chart − This module is only required if you would want graphical reports as the GD module.
Template-GD − This module has the template toolkit for the template plugins.
Template-GD − This module has the template toolkit for the template plugins.
GDTextUtil − This module has the text utilities for use with the GD.
GDTextUtil − This module has the text utilities for use with the GD.
GDGraph − It is a Perl5 module to create charts using the GD module.
GDGraph − It is a Perl5 module to create charts using the GD module.
MIME-tools − MIME-tools is a collection of Perl5 MIME modules for parsing, decoding and generating single or multipart (even nested multipart) MIME messages.
MIME-tools − MIME-tools is a collection of Perl5 MIME modules for parsing, decoding and generating single or multipart (even nested multipart) MIME messages.
libwww-perl − The World Wide Web library for Perl is also called as the libwww-perl. It is a set of Perl modules, which give Perl programming an easy access to send requests to the World Wide Web.
libwww-perl − The World Wide Web library for Perl is also called as the libwww-perl. It is a set of Perl modules, which give Perl programming an easy access to send requests to the World Wide Web.
XML-Twig − It is a Perl module used to process XML documents efficiently. This module offers a tree-oriented interface to a document while still allowing the processing of documents of any size.
XML-Twig − It is a Perl module used to process XML documents efficiently. This module offers a tree-oriented interface to a document while still allowing the processing of documents of any size.
PatchReader − This module has various utilities to read and manipulate patches and CVS.
PatchReader − This module has various utilities to read and manipulate patches and CVS.
perl-ldap − It is a collection of modules that implements LDAP services API for Perl programs. This module may be used to search directories or perform maintenance functions such as adding, deleting or modifying entries.
perl-ldap − It is a collection of modules that implements LDAP services API for Perl programs. This module may be used to search directories or perform maintenance functions such as adding, deleting or modifying entries.
Authen-SASL − This module provides an implementation framework that all protocols should be able to share.
Authen-SASL − This module provides an implementation framework that all protocols should be able to share.
Net-SMTP-SSL − This module provides the SSL support for Net-SMTP 1.04
Net-SMTP-SSL − This module provides the SSL support for Net-SMTP 1.04
RadiusPerl − This module provides simple Radius client facilities.
RadiusPerl − This module provides simple Radius client facilities.
SOAP-Lite − This module is a collection of Perl modules, which provide a simple and lightweight interface to the Simple Object Access Protocol (SOAP) on both the client and the server side.
SOAP-Lite − This module is a collection of Perl modules, which provide a simple and lightweight interface to the Simple Object Access Protocol (SOAP) on both the client and the server side.
XMLRPC-Lite − This Perl module provides a simple interface to the XML-RPC protocol both on client and server side.
XMLRPC-Lite − This Perl module provides a simple interface to the XML-RPC protocol both on client and server side.
JSON-RPC − A set of modules that implement the JSON RPC 2.0 protocols.
JSON-RPC − A set of modules that implement the JSON RPC 2.0 protocols.
Test-Taint − This module has Tools to test taintedness.
Test-Taint − This module has Tools to test taintedness.
HTML-Parser − This module defines a class HTMLParser, which serves as the basis for parsing text files formatted in HTML and XHTML.
HTML-Parser − This module defines a class HTMLParser, which serves as the basis for parsing text files formatted in HTML and XHTML.
HTML-Scrubber − This module helps to sanitize of scrub the html input in a reliable and flexible fashion.
HTML-Scrubber − This module helps to sanitize of scrub the html input in a reliable and flexible fashion.
Encode − This module provides an interface between Perl's strings and the rest of the system.
Encode − This module provides an interface between Perl's strings and the rest of the system.
Encode-Detect − This module is an Encode-Encoding subclass that detects the encoding of data.
Encode-Detect − This module is an Encode-Encoding subclass that detects the encoding of data.
Email-Reply − This module helps in replying to an email or a message.
Email-Reply − This module helps in replying to an email or a message.
HTML-FormatText-WithLinks − This module takes HTML and turns it into plain text, but prints all the links in the HTML as footnotes.
HTML-FormatText-WithLinks − This module takes HTML and turns it into plain text, but prints all the links in the HTML as footnotes.
TheSchwartz − This module is a reliable job queue system.
TheSchwartz − This module is a reliable job queue system.
Daemon-Generic − This module provides a framework for starting, stopping, reconfiguring daemon-like programs.
Daemon-Generic − This module provides a framework for starting, stopping, reconfiguring daemon-like programs.
mod_perl − This module helps in embedding a Perl interpreter into the Apache server.
mod_perl − This module helps in embedding a Perl interpreter into the Apache server.
Apache-SizeLimit − This module allows you to kill the Apache httpd processes, if they grow too large.
Apache-SizeLimit − This module allows you to kill the Apache httpd processes, if they grow too large.
File-MimeInfo − This module is used to determine the mime type of a file.
File-MimeInfo − This module is used to determine the mime type of a file.
IO-stringy − This toolkit mainly provides modules for performing both traditional and object-oriented (i/o) on things other than normal filehandles.
IO-stringy − This toolkit mainly provides modules for performing both traditional and object-oriented (i/o) on things other than normal filehandles.
Cache-Memcached − This module is a client library for the memory cache daemon (memcached).
Cache-Memcached − This module is a client library for the memory cache daemon (memcached).
Text-Markdown − This module is a text-to-HTML filter; it translates an easy-to-read / easy-to-write structured text format into HTML.
Text-Markdown − This module is a text-to-HTML filter; it translates an easy-to-read / easy-to-write structured text format into HTML.
File-Copy-Recursive − This module is a Perl extension for recursively copying files and directories.
File-Copy-Recursive − This module is a Perl extension for recursively copying files and directories.
In Strawberry Perl, use the cpanm script to install modules. Some of the most important modules are already installed by default. The remaining ones can be installed using the following command −
cpanm -l local <modulename>
The list of modules to install will be displayed by using the checksetup.pl command.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2388,
"s": 2245,
"text": "The Bugzilla GIT website is the best way to get Bugzilla. Download and install GIT from the website − https://git-scm.com/download and Run it."
},
{
"code": null,
"e": 2478,
"s": 2388,
"text": "git clone --branch release-X.X-stable https://github.com/bugzilla/bugzilla \nC:\\bugzilla \n"
},
{
"code": null,
"e": 2566,
"s": 2478,
"text": "Where, \"X.X\" is the 2-digit version number of the stable release of Bugzilla (e.g. 5.0)"
},
{
"code": null,
"e": 2823,
"s": 2566,
"text": "The another way to download Bugzilla is from the following link − https://www.bugzilla.org/download/ and move down to the Stable Release section and select the latest one from the list as shown in the following screenshot. Click on Download Bugzilla 5.0.3."
},
{
"code": null,
"e": 2941,
"s": 2823,
"text": "Bugzilla comes as a 'tarball' (.tar.gz extension), which any competent Windows archiving tool should be able to open."
},
{
"code": null,
"e": 3094,
"s": 2941,
"text": "Bugzilla requires a number of Perl modules to be installed. Some of them are mandatory, and some others, which enable additional features, are optional."
},
{
"code": null,
"e": 3292,
"s": 3094,
"text": "In ActivePerl, these modules are available in the ActiveState repository, and are installed with the ppm tool. Either it can use it on the command line or just type ppm and the user will get a GUI."
},
{
"code": null,
"e": 3360,
"s": 3292,
"text": "Install the following mandatory modules with the following command."
},
{
"code": null,
"e": 3387,
"s": 3360,
"text": "ppm install <modulename> \n"
},
{
"code": null,
"e": 3454,
"s": 3387,
"text": "Some of the most important PERL modules have been described below."
},
{
"code": null,
"e": 3649,
"s": 3454,
"text": "CGI.pm − It is an extensively used Perl module for programming the CGI (Common Gateway Interface) web applications. It helps to provide a consistent API for receiving and processing user inputs."
},
{
"code": null,
"e": 3844,
"s": 3649,
"text": "CGI.pm − It is an extensively used Perl module for programming the CGI (Common Gateway Interface) web applications. It helps to provide a consistent API for receiving and processing user inputs."
},
{
"code": null,
"e": 4109,
"s": 3844,
"text": "Digest-SHA − The Digest-SHA1 module allows you to use the NIST SHA-1 message digest algorithm from within the Perl programs. The algorithm takes as input a message of arbitrary length and produces as output a 160-bit \"fingerprint\" or \"message digest\" of the input."
},
{
"code": null,
"e": 4374,
"s": 4109,
"text": "Digest-SHA − The Digest-SHA1 module allows you to use the NIST SHA-1 message digest algorithm from within the Perl programs. The algorithm takes as input a message of arbitrary length and produces as output a 160-bit \"fingerprint\" or \"message digest\" of the input."
},
{
"code": null,
"e": 4497,
"s": 4374,
"text": "TimeDate − TimeDate is a class for the representation of time/date combinations, and is part of the Perl TimeDate project."
},
{
"code": null,
"e": 4620,
"s": 4497,
"text": "TimeDate − TimeDate is a class for the representation of time/date combinations, and is part of the Perl TimeDate project."
},
{
"code": null,
"e": 4743,
"s": 4620,
"text": "DateTime − DateTime is a class for the representation of date/time combinations, and is part of the Perl DateTime project."
},
{
"code": null,
"e": 4866,
"s": 4743,
"text": "DateTime − DateTime is a class for the representation of date/time combinations, and is part of the Perl DateTime project."
},
{
"code": null,
"e": 5074,
"s": 4866,
"text": "DateTime-TimeZone − This class is the base class for all time zone objects. A time zone is represented internally as a set of observances, each of which describes the offset from GMT for a given time period."
},
{
"code": null,
"e": 5282,
"s": 5074,
"text": "DateTime-TimeZone − This class is the base class for all time zone objects. A time zone is represented internally as a set of observances, each of which describes the offset from GMT for a given time period."
},
{
"code": null,
"e": 5490,
"s": 5282,
"text": "DBI − It is the standard database interface module for Perl. It defines a set of methods, variables and conventions that provide a consistent database interface independent of the actual database being used."
},
{
"code": null,
"e": 5698,
"s": 5490,
"text": "DBI − It is the standard database interface module for Perl. It defines a set of methods, variables and conventions that provide a consistent database interface independent of the actual database being used."
},
{
"code": null,
"e": 5937,
"s": 5698,
"text": "Template-Toolkit − The Template Toolkit is a collection of Perl modules, which implement a fast, flexible, powerful and extensible template processing system. It can be used for processing any kind of text documents and is input-agnostic."
},
{
"code": null,
"e": 6176,
"s": 5937,
"text": "Template-Toolkit − The Template Toolkit is a collection of Perl modules, which implement a fast, flexible, powerful and extensible template processing system. It can be used for processing any kind of text documents and is input-agnostic."
},
{
"code": null,
"e": 6391,
"s": 6176,
"text": "Email-Sender − The Email-Sender replaces the old and problematic email send library, which did a decent job at handling the simple email sending tasks, but it was not suitable for serious use for a several reasons."
},
{
"code": null,
"e": 6606,
"s": 6391,
"text": "Email-Sender − The Email-Sender replaces the old and problematic email send library, which did a decent job at handling the simple email sending tasks, but it was not suitable for serious use for a several reasons."
},
{
"code": null,
"e": 6850,
"s": 6606,
"text": "Email-MIME − This is an extension of the Email-Simple module. It is majorly used to handle MIME encoded messages. It takes a message as a string, splits it into its constituent parts and allows you to access the different parts of the message."
},
{
"code": null,
"e": 7094,
"s": 6850,
"text": "Email-MIME − This is an extension of the Email-Simple module. It is majorly used to handle MIME encoded messages. It takes a message as a string, splits it into its constituent parts and allows you to access the different parts of the message."
},
{
"code": null,
"e": 7323,
"s": 7094,
"text": "URI − A Uniform Resource Identifier is a compact string of characters that identifies an abstract or physical resource. A URI can be further classified as either a Uniform Resource Locator (URL) or a Uniform Resource Name (URN)."
},
{
"code": null,
"e": 7552,
"s": 7323,
"text": "URI − A Uniform Resource Identifier is a compact string of characters that identifies an abstract or physical resource. A URI can be further classified as either a Uniform Resource Locator (URL) or a Uniform Resource Name (URN)."
},
{
"code": null,
"e": 7690,
"s": 7552,
"text": "List-MoreUtils − It provides some trivial but commonly needed functionality on lists, which is not going to go into the List-Util module."
},
{
"code": null,
"e": 7828,
"s": 7690,
"text": "List-MoreUtils − It provides some trivial but commonly needed functionality on lists, which is not going to go into the List-Util module."
},
{
"code": null,
"e": 8011,
"s": 7828,
"text": "Math-Random-ISAAC − The ISAAC (Indirection, Shift, Accumulate, Add, and Count) algorithm is designed to take some seed information and produce seemingly random results as the output."
},
{
"code": null,
"e": 8194,
"s": 8011,
"text": "Math-Random-ISAAC − The ISAAC (Indirection, Shift, Accumulate, Add, and Count) algorithm is designed to take some seed information and produce seemingly random results as the output."
},
{
"code": null,
"e": 8403,
"s": 8194,
"text": "File-Slurp − This module provides subs that allow you to read or write files with one simple call. They are designed to be simple, have flexible ways to pass in or get the file content and are very efficient."
},
{
"code": null,
"e": 8612,
"s": 8403,
"text": "File-Slurp − This module provides subs that allow you to read or write files with one simple call. They are designed to be simple, have flexible ways to pass in or get the file content and are very efficient."
},
{
"code": null,
"e": 8775,
"s": 8612,
"text": "JSON-XS − This module converts the Perl data structures to JSON and vice versa. The primary goal of JSON-XS is to be correct and its secondary goal is to be fast."
},
{
"code": null,
"e": 8938,
"s": 8775,
"text": "JSON-XS − This module converts the Perl data structures to JSON and vice versa. The primary goal of JSON-XS is to be correct and its secondary goal is to be fast."
},
{
"code": null,
"e": 9004,
"s": 8938,
"text": "Win32 − The Win32 module contains functions to access Win32 APIs."
},
{
"code": null,
"e": 9070,
"s": 9004,
"text": "Win32 − The Win32 module contains functions to access Win32 APIs."
},
{
"code": null,
"e": 9232,
"s": 9070,
"text": "Win32-API − With this module, you can import and call arbitrary functions from the Win32's Dynamic Link Libraries (DLL), without having to write an XS extension."
},
{
"code": null,
"e": 9394,
"s": 9232,
"text": "Win32-API − With this module, you can import and call arbitrary functions from the Win32's Dynamic Link Libraries (DLL), without having to write an XS extension."
},
{
"code": null,
"e": 9514,
"s": 9394,
"text": "DateTime-TimeZone-Local-Win32 − This module provides methods for determining the local time zone on a Windows platform."
},
{
"code": null,
"e": 9634,
"s": 9514,
"text": "DateTime-TimeZone-Local-Win32 − This module provides methods for determining the local time zone on a Windows platform."
},
{
"code": null,
"e": 9749,
"s": 9634,
"text": "The following modules enable various optional Bugzilla features; try to install these based on your requirements −"
},
{
"code": null,
"e": 9816,
"s": 9749,
"text": "GD − The GD module is only required if you want graphical reports."
},
{
"code": null,
"e": 9883,
"s": 9816,
"text": "GD − The GD module is only required if you want graphical reports."
},
{
"code": null,
"e": 9974,
"s": 9883,
"text": "Chart − This module is only required if you would want graphical reports as the GD module."
},
{
"code": null,
"e": 10065,
"s": 9974,
"text": "Chart − This module is only required if you would want graphical reports as the GD module."
},
{
"code": null,
"e": 10142,
"s": 10065,
"text": "Template-GD − This module has the template toolkit for the template plugins."
},
{
"code": null,
"e": 10219,
"s": 10142,
"text": "Template-GD − This module has the template toolkit for the template plugins."
},
{
"code": null,
"e": 10288,
"s": 10219,
"text": "GDTextUtil − This module has the text utilities for use with the GD."
},
{
"code": null,
"e": 10357,
"s": 10288,
"text": "GDTextUtil − This module has the text utilities for use with the GD."
},
{
"code": null,
"e": 10426,
"s": 10357,
"text": "GDGraph − It is a Perl5 module to create charts using the GD module."
},
{
"code": null,
"e": 10495,
"s": 10426,
"text": "GDGraph − It is a Perl5 module to create charts using the GD module."
},
{
"code": null,
"e": 10653,
"s": 10495,
"text": "MIME-tools − MIME-tools is a collection of Perl5 MIME modules for parsing, decoding and generating single or multipart (even nested multipart) MIME messages."
},
{
"code": null,
"e": 10811,
"s": 10653,
"text": "MIME-tools − MIME-tools is a collection of Perl5 MIME modules for parsing, decoding and generating single or multipart (even nested multipart) MIME messages."
},
{
"code": null,
"e": 11008,
"s": 10811,
"text": "libwww-perl − The World Wide Web library for Perl is also called as the libwww-perl. It is a set of Perl modules, which give Perl programming an easy access to send requests to the World Wide Web."
},
{
"code": null,
"e": 11205,
"s": 11008,
"text": "libwww-perl − The World Wide Web library for Perl is also called as the libwww-perl. It is a set of Perl modules, which give Perl programming an easy access to send requests to the World Wide Web."
},
{
"code": null,
"e": 11400,
"s": 11205,
"text": "XML-Twig − It is a Perl module used to process XML documents efficiently. This module offers a tree-oriented interface to a document while still allowing the processing of documents of any size."
},
{
"code": null,
"e": 11595,
"s": 11400,
"text": "XML-Twig − It is a Perl module used to process XML documents efficiently. This module offers a tree-oriented interface to a document while still allowing the processing of documents of any size."
},
{
"code": null,
"e": 11683,
"s": 11595,
"text": "PatchReader − This module has various utilities to read and manipulate patches and CVS."
},
{
"code": null,
"e": 11771,
"s": 11683,
"text": "PatchReader − This module has various utilities to read and manipulate patches and CVS."
},
{
"code": null,
"e": 11992,
"s": 11771,
"text": "perl-ldap − It is a collection of modules that implements LDAP services API for Perl programs. This module may be used to search directories or perform maintenance functions such as adding, deleting or modifying entries."
},
{
"code": null,
"e": 12213,
"s": 11992,
"text": "perl-ldap − It is a collection of modules that implements LDAP services API for Perl programs. This module may be used to search directories or perform maintenance functions such as adding, deleting or modifying entries."
},
{
"code": null,
"e": 12320,
"s": 12213,
"text": "Authen-SASL − This module provides an implementation framework that all protocols should be able to share."
},
{
"code": null,
"e": 12427,
"s": 12320,
"text": "Authen-SASL − This module provides an implementation framework that all protocols should be able to share."
},
{
"code": null,
"e": 12497,
"s": 12427,
"text": "Net-SMTP-SSL − This module provides the SSL support for Net-SMTP 1.04"
},
{
"code": null,
"e": 12567,
"s": 12497,
"text": "Net-SMTP-SSL − This module provides the SSL support for Net-SMTP 1.04"
},
{
"code": null,
"e": 12634,
"s": 12567,
"text": "RadiusPerl − This module provides simple Radius client facilities."
},
{
"code": null,
"e": 12701,
"s": 12634,
"text": "RadiusPerl − This module provides simple Radius client facilities."
},
{
"code": null,
"e": 12891,
"s": 12701,
"text": "SOAP-Lite − This module is a collection of Perl modules, which provide a simple and lightweight interface to the Simple Object Access Protocol (SOAP) on both the client and the server side."
},
{
"code": null,
"e": 13081,
"s": 12891,
"text": "SOAP-Lite − This module is a collection of Perl modules, which provide a simple and lightweight interface to the Simple Object Access Protocol (SOAP) on both the client and the server side."
},
{
"code": null,
"e": 13196,
"s": 13081,
"text": "XMLRPC-Lite − This Perl module provides a simple interface to the XML-RPC protocol both on client and server side."
},
{
"code": null,
"e": 13311,
"s": 13196,
"text": "XMLRPC-Lite − This Perl module provides a simple interface to the XML-RPC protocol both on client and server side."
},
{
"code": null,
"e": 13382,
"s": 13311,
"text": "JSON-RPC − A set of modules that implement the JSON RPC 2.0 protocols."
},
{
"code": null,
"e": 13453,
"s": 13382,
"text": "JSON-RPC − A set of modules that implement the JSON RPC 2.0 protocols."
},
{
"code": null,
"e": 13509,
"s": 13453,
"text": "Test-Taint − This module has Tools to test taintedness."
},
{
"code": null,
"e": 13565,
"s": 13509,
"text": "Test-Taint − This module has Tools to test taintedness."
},
{
"code": null,
"e": 13697,
"s": 13565,
"text": "HTML-Parser − This module defines a class HTMLParser, which serves as the basis for parsing text files formatted in HTML and XHTML."
},
{
"code": null,
"e": 13829,
"s": 13697,
"text": "HTML-Parser − This module defines a class HTMLParser, which serves as the basis for parsing text files formatted in HTML and XHTML."
},
{
"code": null,
"e": 13935,
"s": 13829,
"text": "HTML-Scrubber − This module helps to sanitize of scrub the html input in a reliable and flexible fashion."
},
{
"code": null,
"e": 14041,
"s": 13935,
"text": "HTML-Scrubber − This module helps to sanitize of scrub the html input in a reliable and flexible fashion."
},
{
"code": null,
"e": 14135,
"s": 14041,
"text": "Encode − This module provides an interface between Perl's strings and the rest of the system."
},
{
"code": null,
"e": 14229,
"s": 14135,
"text": "Encode − This module provides an interface between Perl's strings and the rest of the system."
},
{
"code": null,
"e": 14323,
"s": 14229,
"text": "Encode-Detect − This module is an Encode-Encoding subclass that detects the encoding of data."
},
{
"code": null,
"e": 14417,
"s": 14323,
"text": "Encode-Detect − This module is an Encode-Encoding subclass that detects the encoding of data."
},
{
"code": null,
"e": 14487,
"s": 14417,
"text": "Email-Reply − This module helps in replying to an email or a message."
},
{
"code": null,
"e": 14557,
"s": 14487,
"text": "Email-Reply − This module helps in replying to an email or a message."
},
{
"code": null,
"e": 14689,
"s": 14557,
"text": "HTML-FormatText-WithLinks − This module takes HTML and turns it into plain text, but prints all the links in the HTML as footnotes."
},
{
"code": null,
"e": 14821,
"s": 14689,
"text": "HTML-FormatText-WithLinks − This module takes HTML and turns it into plain text, but prints all the links in the HTML as footnotes."
},
{
"code": null,
"e": 14879,
"s": 14821,
"text": "TheSchwartz − This module is a reliable job queue system."
},
{
"code": null,
"e": 14937,
"s": 14879,
"text": "TheSchwartz − This module is a reliable job queue system."
},
{
"code": null,
"e": 15047,
"s": 14937,
"text": "Daemon-Generic − This module provides a framework for starting, stopping, reconfiguring daemon-like programs."
},
{
"code": null,
"e": 15157,
"s": 15047,
"text": "Daemon-Generic − This module provides a framework for starting, stopping, reconfiguring daemon-like programs."
},
{
"code": null,
"e": 15242,
"s": 15157,
"text": "mod_perl − This module helps in embedding a Perl interpreter into the Apache server."
},
{
"code": null,
"e": 15327,
"s": 15242,
"text": "mod_perl − This module helps in embedding a Perl interpreter into the Apache server."
},
{
"code": null,
"e": 15429,
"s": 15327,
"text": "Apache-SizeLimit − This module allows you to kill the Apache httpd processes, if they grow too large."
},
{
"code": null,
"e": 15531,
"s": 15429,
"text": "Apache-SizeLimit − This module allows you to kill the Apache httpd processes, if they grow too large."
},
{
"code": null,
"e": 15605,
"s": 15531,
"text": "File-MimeInfo − This module is used to determine the mime type of a file."
},
{
"code": null,
"e": 15679,
"s": 15605,
"text": "File-MimeInfo − This module is used to determine the mime type of a file."
},
{
"code": null,
"e": 15828,
"s": 15679,
"text": "IO-stringy − This toolkit mainly provides modules for performing both traditional and object-oriented (i/o) on things other than normal filehandles."
},
{
"code": null,
"e": 15977,
"s": 15828,
"text": "IO-stringy − This toolkit mainly provides modules for performing both traditional and object-oriented (i/o) on things other than normal filehandles."
},
{
"code": null,
"e": 16068,
"s": 15977,
"text": "Cache-Memcached − This module is a client library for the memory cache daemon (memcached)."
},
{
"code": null,
"e": 16159,
"s": 16068,
"text": "Cache-Memcached − This module is a client library for the memory cache daemon (memcached)."
},
{
"code": null,
"e": 16293,
"s": 16159,
"text": "Text-Markdown − This module is a text-to-HTML filter; it translates an easy-to-read / easy-to-write structured text format into HTML."
},
{
"code": null,
"e": 16427,
"s": 16293,
"text": "Text-Markdown − This module is a text-to-HTML filter; it translates an easy-to-read / easy-to-write structured text format into HTML."
},
{
"code": null,
"e": 16528,
"s": 16427,
"text": "File-Copy-Recursive − This module is a Perl extension for recursively copying files and directories."
},
{
"code": null,
"e": 16629,
"s": 16528,
"text": "File-Copy-Recursive − This module is a Perl extension for recursively copying files and directories."
},
{
"code": null,
"e": 16825,
"s": 16629,
"text": "In Strawberry Perl, use the cpanm script to install modules. Some of the most important modules are already installed by default. The remaining ones can be installed using the following command −"
},
{
"code": null,
"e": 16854,
"s": 16825,
"text": "cpanm -l local <modulename>\n"
},
{
"code": null,
"e": 16939,
"s": 16854,
"text": "The list of modules to install will be displayed by using the checksetup.pl command."
},
{
"code": null,
"e": 16946,
"s": 16939,
"text": " Print"
},
{
"code": null,
"e": 16957,
"s": 16946,
"text": " Add Notes"
}
] |
Deep Dive into Catboost Functionalities for Model Interpretation | by Alvira Swalin | Towards Data Science
|
In my previous blog, we saw a comparative study of XGBoost, LightGBM & Catboost. With that analysis, we were able to conclude that catboost outperformed the other two in terms of both speed and accuracy. In this part, we will dig further into the catboost, exploring the new features that catboost provides for efficient modeling and understanding the hyperparameters.
For new readers, catboost is an open-source gradient boosting algorithm developed by Yandex team in 2017. It is a machine learning algorithm which allows users to quickly handle categorical features for a large data set and this differentiates it from XGBoost & LightGBM. Catboost can be used to solve regression, classification and ranking problems.
As Data Scientists, we can easily train models and make predictions, but, we often fail to understand what’s happening inside those fancy algorithms. This is one of the reasons why we see a huge difference in model performance between offline evaluation and final production. It is high time we stop treating ML as a “black box” and give importance to model interpretation while improving model accuracy. This will also help us in identifying data biases. In this part, we will see how catboost helps us to analyze models and improve visibility with the following functionalities:
Why should you know it?- Remove unnecessary features to simplify the model and reduce training/prediction time- Get the most influential feature for your target value and manipulate them for business gains (eg: healthcare providers want to identify what factors are driving each patient’s risk of some disease so they can directly address those risk factors with targeted medicines)
Apart from choosing the type of feature importance, we should also know which data we want to use for finding feature importance — train or test or complete dataset. There are pros and cons of choosing one over the other but in the end, you need to decide whether you want to know how much the model relies on each feature for making predictions (use training data) or how much the feature contributes to the performance of the model on unseen data (use test data). We will see later in this blog that only some methods can be used to find feature importance on data not used for training model.
If you care for the second and assuming you have all the time and resources, the crudest and most reliable way to find feature importance is to train multiple models leaving one feature at a time and compare the performance on the test set. If the performance changes a lot with respect to the baseline (performance when we use all the features) that means that the feature was important. But since we live in a practical world where we need to optimize both accuracy and computation time, this method is unnecessary. Here are a few smart ways in which catboost lets you find the best feature for your model:
For each feature, PredictionValuesChange shows how much on average the prediction changes if the feature value changes. The bigger the value of the importance the bigger on average is the change to the prediction value if this feature is changed.
Pros: It is cheap to compute as you don’t have to do multiple training or testing and you will not be storing any extra information. You will get normalized values as the ouput (all the importances will add up to 100).Cons: It may give misleading results for ranking objectives, it might put groupwise features into the top, even though they have a little influence on the resulting loss value.
To get this feature importance, catboost simply takes the difference between the metric (Loss function) obtained using the model in normal scenario (when we include the feature) and model without this feature (model is built approximately using the original model with this feature removed from all the trees in the ensemble). Higher the difference, the more important the feature is. It is not clearly mentioned in catboost docs how we find the model without feature.
Pros & Cons: This works well for most type of problems unlike predictionvalueschange where you can get misleading results for ranking problems, at the same time, it is computationally heavy .
SHAP value breaks a prediction value into contributions from each feature. It measures the impact of a feature on a single prediction value in comparison to the baseline prediction (mean of the target value for the training dataset).
Two major use cases for shap values:
object-level contributions of features
object-level contributions of features
2. Summary for the whole dataset (overall feature importance)
shap.summary_plot(shap_values, X_test)
Though we can get accurate feature importances through shap, they are computationally more expensive than catboost inbuilt feature importance. For more details on SHAP values, please read this kernel .
BonusAnother feature importance based on the same concept but different implementation is— Permutation based feature importance. Though catboost does not use this, this is purely model-agnostic and easy to calculate.
Though bothPredictionValuesChange & LossFunctionChange can be used for all types of metrics, it is recommended to use LossFunctionChangefor ranking metrics. Except for PredictionValuesChange , all other methods can use test data to find feature importance using models trained on train data.
To understand the differences better, here are the results for all the methods we discussed:
From the above plots, we can see that most of the methods are agreeing on top features. it looks like LossFunctionChange is closest to shap(which is more reliable). However, it is not fair to compare these methods directly because predictionvalueschange is based on train data whereas all others are based on test data.
We should also see the time it takes to run all of them:
With this parameter, you can find the strength of a pair of features (importance of two features together).
In the output, you will get a list for each pair of features. The list will have 3 values, the first value is the index of the first feature in the pair, the second value is the index of the second feature in the pair and the third value is the feature importance score for that pair. For implementation details, please check the embedded notebook.
It is interesting to note that the top two features in the single feature importance don’t necessarily make the strongest pair.
Dataset used in the notebook
import pandas as pd, numpy as np
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
from catboost import *
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.model_selection import train_test_split
import shap
from time import time
# ! pip install plotly
header = ["age",
"workclass",
"fnlwgt",
"education",
"education-num",
"marital-status","occupation","relationship","race",
"sex","capital-gain","capital-loss","hours-per-week",
"native-country",
"income"]
train = pd.read_csv("adult_data", names = header, index_col=False)
print(train.shape)
(32561, 15)
train.head(3)
train.shape
(32561, 15)
train["income"] = train["income"].apply(lambda x: 0 if x == " <=50K" else 1)
def log_loss(m, X, y):
return metrics.log_loss(y,m.predict_proba(X)[:,1])
def permutation_importances(model, X, y, metric):
baseline = metric(model, X, y)
imp = []
for col in X.columns:
save = X[col].copy()
X[col] = np.random.permutation(X[col])
m = metric(model, X, y)
X[col] = save
imp.append(m-baseline)
return np.array(imp)
def baseline_importance(model, X, y, X_test, y_test, metric):
model = CatBoostClassifier(one_hot_max_size = 10, iterations = 500)
model.fit(X, y, cat_features = categorical_features_indices, verbose = False)
baseline = metric(model, X_test, y_test)
imp = []
for col in X.columns:
save = X[col].copy()
X[col] = np.random.permutation(X[col])
model.fit(X, y, cat_features = categorical_features_indices, verbose = False)
m = metric(model, X_test, y_test)
X[col] = save
imp.append(m-baseline)
return np.array(imp)
X_train, X_test, y_train, y_test = train_test_split(train.drop("income", axis = 1), train["income"], \
train_size=0.7, random_state=1)
categorical_features_indices = [1, 3, 5, 6, 7, 8, 9, 13]
for col in X_train.columns:
print(col, X_train[col].nunique())
age 73
workclass 9
fnlwgt 16640
education 16
education-num 16
marital-status 7
occupation 15
relationship 6
race 5
sex 2
capital-gain 116
capital-loss 88
hours-per-week 93
native-country 41
iteration = [50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800]
loss = []
for i in iteration:
model = CatBoostClassifier(one_hot_max_size = 10, iterations = i)
model.fit(
X_train, y_train,
cat_features = categorical_features_indices,
verbose = False
)
loss.append((i, log_loss(model, X_test, y_test), log_loss(model, X_train, y_train)))
print(i)
50
100
150
200
250
300
350
400
450
500
550
600
650
700
750
800
plt.plot([i[0] for i in loss],[i[1] for i in loss])
plt.plot([i[0] for i in loss],[i[2] for i in loss])
plt.show
<function matplotlib.pyplot.show>
model = CatBoostClassifier(one_hot_max_size = 10, iterations = 500)
model.fit(
X_train, y_train,
cat_features = categorical_features_indices,
verbose = False
)
<catboost.core.CatBoostClassifier at 0x1c283ca0b8>
# model.get_feature_importance??
shap_values = model.get_feature_importance(Pool(X_test, label=y_test,cat_features=categorical_features_indices),
type="ShapValues")
expected_value = shap_values[0,-1]
shap_values = shap_values[:,:-1]
shap.initjs()
shap.force_plot(expected_value, shap_values[3,:], X_test.iloc[3,:])
start_time = time.time()
shap_values = model.get_feature_importance(Pool(X_test, label=y_test,cat_features=categorical_features_indices),
type="ShapValues")
shap_values = shap_values[:,:-1]
shap.summary_plot(shap_values, X_test)
elapsed = time.time() - start_time
elapsed
2.246151924133301
timeit.default_timer()
770830.962590046
def get_feature_imp_plot(method):
if method == "Permutation":
fi = permutation_importances(model, X_test, y_test, log_loss)
elif method == "Baseline":
fi = baseline_importance(model, X_train, y_train, X_test, y_test, log_loss)
elif method == "ShapeValues":
shap_values = model.get_feature_importance(Pool(X_test, label=y_test,cat_features=categorical_features_indices),
type="ShapValues")
shap_values = shap_values[:,:-1]
shap.summary_plot(shap_values, X_test)
else:
fi = model.get_feature_importance(Pool(X_test, label=y_test,cat_features=categorical_features_indices),
type=method)
if method != "ShapeValues":
feature_score = pd.DataFrame(list(zip(X_test.dtypes.index, fi )),
columns=['Feature','Score'])
feature_score = feature_score.sort_values(by='Score', ascending=False, inplace=False, kind='quicksort', na_position='last')
plt.rcParams["figure.figsize"] = (12,7)
ax = feature_score.plot('Feature', 'Score', kind='bar', color='c')
ax.set_title("Feature Importance using {}".format(method), fontsize = 14)
ax.set_xlabel("features")
plt.show()
%time get_feature_imp_plot(method="PredictionValuesChange")
CPU times: user 281 ms, sys: 27.2 ms, total: 308 ms
Wall time: 313 ms
%time get_feature_imp_plot(method="LossFunctionChange")
CPU times: user 2.03 s, sys: 31.3 ms, total: 2.06 s
Wall time: 514 ms
%time get_feature_imp_plot(method="Permutation")
CPU times: user 1.27 s, sys: 137 ms, total: 1.4 s
Wall time: 1.08 s
%time get_feature_imp_plot(method="ShapeValues")
CPU times: user 3.86 s, sys: 50.1 ms, total: 3.91 s
Wall time: 2.29 s
%time get_feature_imp_plot(method="Baseline")
CPU times: user 25min 19s, sys: 6min 25s, total: 31min 45s
Wall time: 5min 32s
fi = model.get_feature_importance(Pool(X_test, label=y_test,cat_features=categorical_features_indices),
type="Interaction")
Dataset is provided, but Interaction feature importance don't use it.
fi[:5]
[[5, 10, 4.879359239300689],
[7, 11, 4.211308589799566],
[1, 7, 3.596972913690984],
[6, 10, 3.56524055924632],
[5, 6, 3.4918909052689524]]
fi_new = []
for k,item in enumerate(fi):
first = X_test.dtypes.index[fi[k][0]]
second = X_test.dtypes.index[fi[k][1]]
if first != second:
fi_new.append([first + "_" + second, fi[k][2]])
fi_new[:5]
[['marital-status_capital-gain', 4.879359239300689],
['relationship_capital-loss', 4.211308589799566],
['workclass_relationship', 3.596972913690984],
['occupation_capital-gain', 3.56524055924632],
['marital-status_occupation', 3.4918909052689524]]
feature_score = pd.DataFrame(fi_new,columns=['Feature-Pair','Score'])
feature_score = feature_score.sort_values(by='Score', ascending=False, inplace=False, kind='quicksort', na_position='last')
plt.rcParams["figure.figsize"] = (16,7)
ax = feature_score.plot('Feature-Pair', 'Score', kind='bar', color='c')
ax.set_title("Pairwise Feature Importance", fontsize = 14)
ax.set_xlabel("features Pair")
plt.show()
feature = 'hours-per-week'
res = model.get_feature_statistics(X_train, y_train, feature, plot=True)
feature = 'workclass'
model.get_feature_statistics(X_train, y_train, feature, plot=True)
{'binarized_feature': array([8, 0, 1, ..., 0, 6, 0]),
'mean_target': array([0.22366841, 0.1033411 , 0.2920592 , 0. , 0.3948949 ,
0. , 0.29469123, 0.28923768, 0.57639754], dtype=float32),
'mean_prediction': array([0.22334838, 0.10167585, 0.3016555 , 0.05339337, 0.37704837,
0.01450176, 0.30424172, 0.2946237 , 0.56375426], dtype=float32),
'objects_per_bin': array([15827, 1287, 1486, 9, 666, 5, 923, 1784, 805],
dtype=uint32),
'predictions_on_varying_feature': array([0.25023816, 0.24915191, 0.23332911, 0.18895106, 0.28084712,
0.22534325, 0.24529697, 0.21784215, 0.2707088 , 0. ]),
'cat_values': array([' Private', ' ?', ' Local-gov', ' Without-pay', ' Federal-gov',
' Never-worked', ' State-gov', ' Self-emp-not-inc',
' Self-emp-inc'], dtype='<U17')}
feature = 'sex'
res = titanic_model.calc_feature_statistics(titanic_train, titanic_train_target, feature, plot=True)
model.get_feature_statistics?
Remove the most useless training objects from the training data
Prioritize a batch of new objects for labeling based on which ones are expected to be the most “helpful”, akin to active learning
With this functionality, you can calculate the impact of each object on the optimized metric for test data. Positive values reflect that the optimized metric increases and negative values reflect that the optimized metric decreases. This method is an implementation of the approach described in this paper. Details of these algorithms are beyond the scope of this blog.
github.com
There are three types of update_method available in cb.get_object_importance :
SinglePoint: The fastest and least accurate method
TopKLeaves: Specify the number of leaves. The higher the value, the more accurate and the slower the calculation
AllPoints: The slowest and most accurate method
For example, the following value sets the method to TopKLeaves and limits the number of leaves to 3:
TopKLeaves:top=3
Catboost has recently launched this functionality in its latest update. With this feature, we will be able to visualize how the algorithm is splitting the data for each feature and look at feature-specific statistics. More specifically we will be able to see:
Mean target value for each bin (bin is used for continuous feature) or category (currently only OHE features are supported)
Mean prediction value for each bin/category
Number of objects in each bin
Predictions for different feature values: For every object, feature value is varied so that it falls into some bin. The model then predicts the target according to the new values of that feature and takes the mean of predictions in a bin (given by red points).
This plot will give us information like how uniform our splitting is (we don’t want all the objects to go in one bin), whether our predictions are close to target (blue and orange line), the red line will tell us how sensitive our predictions are wrt a feature.
Thank you for reading this. Hopefully, next time you will be able to make use of these tools to understand your models better.
After the positive reception from the machine learning community to my previous blog on CatBoost vs. Light GBM vs. XGBoost, the CatBoost team reached out to see if I was interested in covering more in-depth topics on the library. Thanks to the CatBoost team for helping answer my questions for this post!
About Me: I am currently working as a Data Scientist in Maps team at Uber. If you are interested in solving challenging problems at Uber, please reach out to me at LinkedIn. You can read my other blogs here.
Catboost Documentation
SHAP Values
Catboost official website
CatBoost Paper
Notebook
Paper on Finding Influential Training Samples
|
[
{
"code": null,
"e": 541,
"s": 172,
"text": "In my previous blog, we saw a comparative study of XGBoost, LightGBM & Catboost. With that analysis, we were able to conclude that catboost outperformed the other two in terms of both speed and accuracy. In this part, we will dig further into the catboost, exploring the new features that catboost provides for efficient modeling and understanding the hyperparameters."
},
{
"code": null,
"e": 892,
"s": 541,
"text": "For new readers, catboost is an open-source gradient boosting algorithm developed by Yandex team in 2017. It is a machine learning algorithm which allows users to quickly handle categorical features for a large data set and this differentiates it from XGBoost & LightGBM. Catboost can be used to solve regression, classification and ranking problems."
},
{
"code": null,
"e": 1473,
"s": 892,
"text": "As Data Scientists, we can easily train models and make predictions, but, we often fail to understand what’s happening inside those fancy algorithms. This is one of the reasons why we see a huge difference in model performance between offline evaluation and final production. It is high time we stop treating ML as a “black box” and give importance to model interpretation while improving model accuracy. This will also help us in identifying data biases. In this part, we will see how catboost helps us to analyze models and improve visibility with the following functionalities:"
},
{
"code": null,
"e": 1856,
"s": 1473,
"text": "Why should you know it?- Remove unnecessary features to simplify the model and reduce training/prediction time- Get the most influential feature for your target value and manipulate them for business gains (eg: healthcare providers want to identify what factors are driving each patient’s risk of some disease so they can directly address those risk factors with targeted medicines)"
},
{
"code": null,
"e": 2452,
"s": 1856,
"text": "Apart from choosing the type of feature importance, we should also know which data we want to use for finding feature importance — train or test or complete dataset. There are pros and cons of choosing one over the other but in the end, you need to decide whether you want to know how much the model relies on each feature for making predictions (use training data) or how much the feature contributes to the performance of the model on unseen data (use test data). We will see later in this blog that only some methods can be used to find feature importance on data not used for training model."
},
{
"code": null,
"e": 3061,
"s": 2452,
"text": "If you care for the second and assuming you have all the time and resources, the crudest and most reliable way to find feature importance is to train multiple models leaving one feature at a time and compare the performance on the test set. If the performance changes a lot with respect to the baseline (performance when we use all the features) that means that the feature was important. But since we live in a practical world where we need to optimize both accuracy and computation time, this method is unnecessary. Here are a few smart ways in which catboost lets you find the best feature for your model:"
},
{
"code": null,
"e": 3308,
"s": 3061,
"text": "For each feature, PredictionValuesChange shows how much on average the prediction changes if the feature value changes. The bigger the value of the importance the bigger on average is the change to the prediction value if this feature is changed."
},
{
"code": null,
"e": 3703,
"s": 3308,
"text": "Pros: It is cheap to compute as you don’t have to do multiple training or testing and you will not be storing any extra information. You will get normalized values as the ouput (all the importances will add up to 100).Cons: It may give misleading results for ranking objectives, it might put groupwise features into the top, even though they have a little influence on the resulting loss value."
},
{
"code": null,
"e": 4172,
"s": 3703,
"text": "To get this feature importance, catboost simply takes the difference between the metric (Loss function) obtained using the model in normal scenario (when we include the feature) and model without this feature (model is built approximately using the original model with this feature removed from all the trees in the ensemble). Higher the difference, the more important the feature is. It is not clearly mentioned in catboost docs how we find the model without feature."
},
{
"code": null,
"e": 4364,
"s": 4172,
"text": "Pros & Cons: This works well for most type of problems unlike predictionvalueschange where you can get misleading results for ranking problems, at the same time, it is computationally heavy ."
},
{
"code": null,
"e": 4598,
"s": 4364,
"text": "SHAP value breaks a prediction value into contributions from each feature. It measures the impact of a feature on a single prediction value in comparison to the baseline prediction (mean of the target value for the training dataset)."
},
{
"code": null,
"e": 4635,
"s": 4598,
"text": "Two major use cases for shap values:"
},
{
"code": null,
"e": 4674,
"s": 4635,
"text": "object-level contributions of features"
},
{
"code": null,
"e": 4713,
"s": 4674,
"text": "object-level contributions of features"
},
{
"code": null,
"e": 4775,
"s": 4713,
"text": "2. Summary for the whole dataset (overall feature importance)"
},
{
"code": null,
"e": 4814,
"s": 4775,
"text": "shap.summary_plot(shap_values, X_test)"
},
{
"code": null,
"e": 5016,
"s": 4814,
"text": "Though we can get accurate feature importances through shap, they are computationally more expensive than catboost inbuilt feature importance. For more details on SHAP values, please read this kernel ."
},
{
"code": null,
"e": 5233,
"s": 5016,
"text": "BonusAnother feature importance based on the same concept but different implementation is— Permutation based feature importance. Though catboost does not use this, this is purely model-agnostic and easy to calculate."
},
{
"code": null,
"e": 5525,
"s": 5233,
"text": "Though bothPredictionValuesChange & LossFunctionChange can be used for all types of metrics, it is recommended to use LossFunctionChangefor ranking metrics. Except for PredictionValuesChange , all other methods can use test data to find feature importance using models trained on train data."
},
{
"code": null,
"e": 5618,
"s": 5525,
"text": "To understand the differences better, here are the results for all the methods we discussed:"
},
{
"code": null,
"e": 5938,
"s": 5618,
"text": "From the above plots, we can see that most of the methods are agreeing on top features. it looks like LossFunctionChange is closest to shap(which is more reliable). However, it is not fair to compare these methods directly because predictionvalueschange is based on train data whereas all others are based on test data."
},
{
"code": null,
"e": 5995,
"s": 5938,
"text": "We should also see the time it takes to run all of them:"
},
{
"code": null,
"e": 6103,
"s": 5995,
"text": "With this parameter, you can find the strength of a pair of features (importance of two features together)."
},
{
"code": null,
"e": 6452,
"s": 6103,
"text": "In the output, you will get a list for each pair of features. The list will have 3 values, the first value is the index of the first feature in the pair, the second value is the index of the second feature in the pair and the third value is the feature importance score for that pair. For implementation details, please check the embedded notebook."
},
{
"code": null,
"e": 6580,
"s": 6452,
"text": "It is interesting to note that the top two features in the single feature importance don’t necessarily make the strongest pair."
},
{
"code": null,
"e": 6609,
"s": 6580,
"text": "Dataset used in the notebook"
},
{
"code": null,
"e": 6883,
"s": 6609,
"text": "import pandas as pd, numpy as np\nimport warnings\nwarnings.filterwarnings('ignore')\n%matplotlib inline \nfrom catboost import *\nimport matplotlib.pyplot as plt\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\nimport shap\nfrom time import time\n"
},
{
"code": null,
"e": 6908,
"s": 6883,
"text": "# ! pip install plotly \n"
},
{
"code": null,
"e": 7202,
"s": 6908,
"text": "header = [\"age\",\n\"workclass\",\n\"fnlwgt\",\n\"education\",\n\"education-num\",\n\"marital-status\",\"occupation\",\"relationship\",\"race\",\n\"sex\",\"capital-gain\",\"capital-loss\",\"hours-per-week\",\n\"native-country\",\n\"income\"]\n\ntrain = pd.read_csv(\"adult_data\", names = header, index_col=False)\n\nprint(train.shape)\n"
},
{
"code": null,
"e": 7215,
"s": 7202,
"text": "(32561, 15)\n"
},
{
"code": null,
"e": 7230,
"s": 7215,
"text": "train.head(3)\n"
},
{
"code": null,
"e": 7243,
"s": 7230,
"text": "train.shape\n"
},
{
"code": null,
"e": 7255,
"s": 7243,
"text": "(32561, 15)"
},
{
"code": null,
"e": 7333,
"s": 7255,
"text": "train[\"income\"] = train[\"income\"].apply(lambda x: 0 if x == \" <=50K\" else 1)\n"
},
{
"code": null,
"e": 7728,
"s": 7333,
"text": "def log_loss(m, X, y): \n return metrics.log_loss(y,m.predict_proba(X)[:,1])\n \ndef permutation_importances(model, X, y, metric):\n baseline = metric(model, X, y)\n imp = []\n for col in X.columns:\n save = X[col].copy()\n X[col] = np.random.permutation(X[col])\n m = metric(model, X, y)\n X[col] = save\n imp.append(m-baseline)\n return np.array(imp)\n"
},
{
"code": null,
"e": 8344,
"s": 7728,
"text": "def baseline_importance(model, X, y, X_test, y_test, metric):\n \n model = CatBoostClassifier(one_hot_max_size = 10, iterations = 500)\n model.fit(X, y, cat_features = categorical_features_indices, verbose = False)\n baseline = metric(model, X_test, y_test)\n \n imp = []\n for col in X.columns:\n \n save = X[col].copy()\n X[col] = np.random.permutation(X[col])\n \n model.fit(X, y, cat_features = categorical_features_indices, verbose = False)\n m = metric(model, X_test, y_test)\n X[col] = save\n imp.append(m-baseline)\n return np.array(imp)\n \n"
},
{
"code": null,
"e": 8532,
"s": 8344,
"text": "X_train, X_test, y_train, y_test = train_test_split(train.drop(\"income\", axis = 1), train[\"income\"], \\\n train_size=0.7, random_state=1)\n"
},
{
"code": null,
"e": 8590,
"s": 8532,
"text": "categorical_features_indices = [1, 3, 5, 6, 7, 8, 9, 13]\n"
},
{
"code": null,
"e": 8658,
"s": 8590,
"text": "for col in X_train.columns:\n print(col, X_train[col].nunique())\n"
},
{
"code": null,
"e": 8849,
"s": 8658,
"text": "age 73\nworkclass 9\nfnlwgt 16640\neducation 16\neducation-num 16\nmarital-status 7\noccupation 15\nrelationship 6\nrace 5\nsex 2\ncapital-gain 116\ncapital-loss 88\nhours-per-week 93\nnative-country 41\n"
},
{
"code": null,
"e": 9256,
"s": 8849,
"text": "iteration = [50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800]\nloss = []\nfor i in iteration:\n model = CatBoostClassifier(one_hot_max_size = 10, iterations = i)\n model.fit(\n X_train, y_train,\n cat_features = categorical_features_indices,\n verbose = False\n )\n loss.append((i, log_loss(model, X_test, y_test), log_loss(model, X_train, y_train)))\n print(i)\n"
},
{
"code": null,
"e": 9320,
"s": 9256,
"text": "50\n100\n150\n200\n250\n300\n350\n400\n450\n500\n550\n600\n650\n700\n750\n800\n"
},
{
"code": null,
"e": 9436,
"s": 9320,
"text": "plt.plot([i[0] for i in loss],[i[1] for i in loss]) \nplt.plot([i[0] for i in loss],[i[2] for i in loss]) \nplt.show\n"
},
{
"code": null,
"e": 9470,
"s": 9436,
"text": "<function matplotlib.pyplot.show>"
},
{
"code": null,
"e": 9643,
"s": 9470,
"text": "model = CatBoostClassifier(one_hot_max_size = 10, iterations = 500)\nmodel.fit(\n X_train, y_train,\n cat_features = categorical_features_indices,\n verbose = False\n)\n"
},
{
"code": null,
"e": 9694,
"s": 9643,
"text": "<catboost.core.CatBoostClassifier at 0x1c283ca0b8>"
},
{
"code": null,
"e": 9728,
"s": 9694,
"text": "# model.get_feature_importance??\n"
},
{
"code": null,
"e": 10082,
"s": 9728,
"text": "shap_values = model.get_feature_importance(Pool(X_test, label=y_test,cat_features=categorical_features_indices), \n type=\"ShapValues\")\nexpected_value = shap_values[0,-1]\nshap_values = shap_values[:,:-1]\n\nshap.initjs()\nshap.force_plot(expected_value, shap_values[3,:], X_test.iloc[3,:])\n"
},
{
"code": null,
"e": 10419,
"s": 10082,
"text": "start_time = time.time()\nshap_values = model.get_feature_importance(Pool(X_test, label=y_test,cat_features=categorical_features_indices), \n type=\"ShapValues\")\nshap_values = shap_values[:,:-1]\n\nshap.summary_plot(shap_values, X_test) \nelapsed = time.time() - start_time\n"
},
{
"code": null,
"e": 10428,
"s": 10419,
"text": "elapsed\n"
},
{
"code": null,
"e": 10446,
"s": 10428,
"text": "2.246151924133301"
},
{
"code": null,
"e": 10470,
"s": 10446,
"text": "timeit.default_timer()\n"
},
{
"code": null,
"e": 10487,
"s": 10470,
"text": "770830.962590046"
},
{
"code": null,
"e": 11878,
"s": 10487,
"text": "def get_feature_imp_plot(method):\n \n if method == \"Permutation\":\n fi = permutation_importances(model, X_test, y_test, log_loss)\n \n elif method == \"Baseline\":\n fi = baseline_importance(model, X_train, y_train, X_test, y_test, log_loss)\n \n elif method == \"ShapeValues\":\n shap_values = model.get_feature_importance(Pool(X_test, label=y_test,cat_features=categorical_features_indices), \n type=\"ShapValues\")\n shap_values = shap_values[:,:-1]\n shap.summary_plot(shap_values, X_test) \n \n else:\n fi = model.get_feature_importance(Pool(X_test, label=y_test,cat_features=categorical_features_indices), \n type=method)\n \n if method != \"ShapeValues\":\n feature_score = pd.DataFrame(list(zip(X_test.dtypes.index, fi )),\n columns=['Feature','Score'])\n\n feature_score = feature_score.sort_values(by='Score', ascending=False, inplace=False, kind='quicksort', na_position='last')\n\n plt.rcParams[\"figure.figsize\"] = (12,7)\n ax = feature_score.plot('Feature', 'Score', kind='bar', color='c')\n ax.set_title(\"Feature Importance using {}\".format(method), fontsize = 14)\n ax.set_xlabel(\"features\")\n plt.show()\n"
},
{
"code": null,
"e": 11939,
"s": 11878,
"text": "%time get_feature_imp_plot(method=\"PredictionValuesChange\")\n"
},
{
"code": null,
"e": 12010,
"s": 11939,
"text": "CPU times: user 281 ms, sys: 27.2 ms, total: 308 ms\nWall time: 313 ms\n"
},
{
"code": null,
"e": 12067,
"s": 12010,
"text": "%time get_feature_imp_plot(method=\"LossFunctionChange\")\n"
},
{
"code": null,
"e": 12138,
"s": 12067,
"text": "CPU times: user 2.03 s, sys: 31.3 ms, total: 2.06 s\nWall time: 514 ms\n"
},
{
"code": null,
"e": 12188,
"s": 12138,
"text": "%time get_feature_imp_plot(method=\"Permutation\")\n"
},
{
"code": null,
"e": 12257,
"s": 12188,
"text": "CPU times: user 1.27 s, sys: 137 ms, total: 1.4 s\nWall time: 1.08 s\n"
},
{
"code": null,
"e": 12307,
"s": 12257,
"text": "%time get_feature_imp_plot(method=\"ShapeValues\")\n"
},
{
"code": null,
"e": 12378,
"s": 12307,
"text": "CPU times: user 3.86 s, sys: 50.1 ms, total: 3.91 s\nWall time: 2.29 s\n"
},
{
"code": null,
"e": 12425,
"s": 12378,
"text": "%time get_feature_imp_plot(method=\"Baseline\")\n"
},
{
"code": null,
"e": 12505,
"s": 12425,
"text": "CPU times: user 25min 19s, sys: 6min 25s, total: 31min 45s\nWall time: 5min 32s\n"
},
{
"code": null,
"e": 12700,
"s": 12505,
"text": "fi = model.get_feature_importance(Pool(X_test, label=y_test,cat_features=categorical_features_indices), \n type=\"Interaction\")\n"
},
{
"code": null,
"e": 12771,
"s": 12700,
"text": "Dataset is provided, but Interaction feature importance don't use it.\n"
},
{
"code": null,
"e": 12779,
"s": 12771,
"text": "fi[:5]\n"
},
{
"code": null,
"e": 12922,
"s": 12779,
"text": "[[5, 10, 4.879359239300689],\n [7, 11, 4.211308589799566],\n [1, 7, 3.596972913690984],\n [6, 10, 3.56524055924632],\n [5, 6, 3.4918909052689524]]"
},
{
"code": null,
"e": 13131,
"s": 12922,
"text": "fi_new = []\nfor k,item in enumerate(fi): \n first = X_test.dtypes.index[fi[k][0]]\n second = X_test.dtypes.index[fi[k][1]]\n if first != second:\n fi_new.append([first + \"_\" + second, fi[k][2]])\n"
},
{
"code": null,
"e": 13143,
"s": 13131,
"text": "fi_new[:5]\n"
},
{
"code": null,
"e": 13395,
"s": 13143,
"text": "[['marital-status_capital-gain', 4.879359239300689],\n ['relationship_capital-loss', 4.211308589799566],\n ['workclass_relationship', 3.596972913690984],\n ['occupation_capital-gain', 3.56524055924632],\n ['marital-status_occupation', 3.4918909052689524]]"
},
{
"code": null,
"e": 13466,
"s": 13395,
"text": "feature_score = pd.DataFrame(fi_new,columns=['Feature-Pair','Score'])\n"
},
{
"code": null,
"e": 13804,
"s": 13466,
"text": "feature_score = feature_score.sort_values(by='Score', ascending=False, inplace=False, kind='quicksort', na_position='last')\nplt.rcParams[\"figure.figsize\"] = (16,7)\nax = feature_score.plot('Feature-Pair', 'Score', kind='bar', color='c')\nax.set_title(\"Pairwise Feature Importance\", fontsize = 14)\nax.set_xlabel(\"features Pair\")\nplt.show()\n"
},
{
"code": null,
"e": 13905,
"s": 13804,
"text": "feature = 'hours-per-week'\nres = model.get_feature_statistics(X_train, y_train, feature, plot=True)\n"
},
{
"code": null,
"e": 13995,
"s": 13905,
"text": "feature = 'workclass'\nmodel.get_feature_statistics(X_train, y_train, feature, plot=True)\n"
},
{
"code": null,
"e": 14837,
"s": 13995,
"text": "{'binarized_feature': array([8, 0, 1, ..., 0, 6, 0]),\n 'mean_target': array([0.22366841, 0.1033411 , 0.2920592 , 0. , 0.3948949 ,\n 0. , 0.29469123, 0.28923768, 0.57639754], dtype=float32),\n 'mean_prediction': array([0.22334838, 0.10167585, 0.3016555 , 0.05339337, 0.37704837,\n 0.01450176, 0.30424172, 0.2946237 , 0.56375426], dtype=float32),\n 'objects_per_bin': array([15827, 1287, 1486, 9, 666, 5, 923, 1784, 805],\n dtype=uint32),\n 'predictions_on_varying_feature': array([0.25023816, 0.24915191, 0.23332911, 0.18895106, 0.28084712,\n 0.22534325, 0.24529697, 0.21784215, 0.2707088 , 0. ]),\n 'cat_values': array([' Private', ' ?', ' Local-gov', ' Without-pay', ' Federal-gov',\n ' Never-worked', ' State-gov', ' Self-emp-not-inc',\n ' Self-emp-inc'], dtype='<U17')}"
},
{
"code": null,
"e": 14955,
"s": 14837,
"text": "feature = 'sex'\nres = titanic_model.calc_feature_statistics(titanic_train, titanic_train_target, feature, plot=True)\n"
},
{
"code": null,
"e": 14986,
"s": 14955,
"text": "model.get_feature_statistics?\n"
},
{
"code": null,
"e": 15053,
"s": 14989,
"text": "Remove the most useless training objects from the training data"
},
{
"code": null,
"e": 15183,
"s": 15053,
"text": "Prioritize a batch of new objects for labeling based on which ones are expected to be the most “helpful”, akin to active learning"
},
{
"code": null,
"e": 15553,
"s": 15183,
"text": "With this functionality, you can calculate the impact of each object on the optimized metric for test data. Positive values reflect that the optimized metric increases and negative values reflect that the optimized metric decreases. This method is an implementation of the approach described in this paper. Details of these algorithms are beyond the scope of this blog."
},
{
"code": null,
"e": 15564,
"s": 15553,
"text": "github.com"
},
{
"code": null,
"e": 15643,
"s": 15564,
"text": "There are three types of update_method available in cb.get_object_importance :"
},
{
"code": null,
"e": 15694,
"s": 15643,
"text": "SinglePoint: The fastest and least accurate method"
},
{
"code": null,
"e": 15807,
"s": 15694,
"text": "TopKLeaves: Specify the number of leaves. The higher the value, the more accurate and the slower the calculation"
},
{
"code": null,
"e": 15855,
"s": 15807,
"text": "AllPoints: The slowest and most accurate method"
},
{
"code": null,
"e": 15956,
"s": 15855,
"text": "For example, the following value sets the method to TopKLeaves and limits the number of leaves to 3:"
},
{
"code": null,
"e": 15973,
"s": 15956,
"text": "TopKLeaves:top=3"
},
{
"code": null,
"e": 16233,
"s": 15973,
"text": "Catboost has recently launched this functionality in its latest update. With this feature, we will be able to visualize how the algorithm is splitting the data for each feature and look at feature-specific statistics. More specifically we will be able to see:"
},
{
"code": null,
"e": 16357,
"s": 16233,
"text": "Mean target value for each bin (bin is used for continuous feature) or category (currently only OHE features are supported)"
},
{
"code": null,
"e": 16401,
"s": 16357,
"text": "Mean prediction value for each bin/category"
},
{
"code": null,
"e": 16431,
"s": 16401,
"text": "Number of objects in each bin"
},
{
"code": null,
"e": 16692,
"s": 16431,
"text": "Predictions for different feature values: For every object, feature value is varied so that it falls into some bin. The model then predicts the target according to the new values of that feature and takes the mean of predictions in a bin (given by red points)."
},
{
"code": null,
"e": 16954,
"s": 16692,
"text": "This plot will give us information like how uniform our splitting is (we don’t want all the objects to go in one bin), whether our predictions are close to target (blue and orange line), the red line will tell us how sensitive our predictions are wrt a feature."
},
{
"code": null,
"e": 17081,
"s": 16954,
"text": "Thank you for reading this. Hopefully, next time you will be able to make use of these tools to understand your models better."
},
{
"code": null,
"e": 17386,
"s": 17081,
"text": "After the positive reception from the machine learning community to my previous blog on CatBoost vs. Light GBM vs. XGBoost, the CatBoost team reached out to see if I was interested in covering more in-depth topics on the library. Thanks to the CatBoost team for helping answer my questions for this post!"
},
{
"code": null,
"e": 17594,
"s": 17386,
"text": "About Me: I am currently working as a Data Scientist in Maps team at Uber. If you are interested in solving challenging problems at Uber, please reach out to me at LinkedIn. You can read my other blogs here."
},
{
"code": null,
"e": 17617,
"s": 17594,
"text": "Catboost Documentation"
},
{
"code": null,
"e": 17629,
"s": 17617,
"text": "SHAP Values"
},
{
"code": null,
"e": 17655,
"s": 17629,
"text": "Catboost official website"
},
{
"code": null,
"e": 17670,
"s": 17655,
"text": "CatBoost Paper"
},
{
"code": null,
"e": 17679,
"s": 17670,
"text": "Notebook"
}
] |
How to display Absolute value of a number in C#?
|
To find the absolute value of a number in C#, use the Math.Abs method.
Set numbers first −
int val1 = 77;
int val2 = -88;
Now take two new variables and get the Absolute value of the above two numbers −
int abs1 = Math.Abs(val1);
int abs2 = Math.Abs(val2);
Let us see the complete code to display Absolute value of a number −
Live Demo
using System;
class Program {
static void Main() {
int val1 = 77;
int val2 = -88;
Console.WriteLine("Before...");
Console.WriteLine(val1);
Console.WriteLine(val2);
int abs1 = Math.Abs(val1);
int abs2 = Math.Abs(val2);
Console.WriteLine("After...");
Console.WriteLine(abs1);
Console.WriteLine(abs2);
}
}
Before...
77
-88
After...
77
88
|
[
{
"code": null,
"e": 1133,
"s": 1062,
"text": "To find the absolute value of a number in C#, use the Math.Abs method."
},
{
"code": null,
"e": 1153,
"s": 1133,
"text": "Set numbers first −"
},
{
"code": null,
"e": 1184,
"s": 1153,
"text": "int val1 = 77;\nint val2 = -88;"
},
{
"code": null,
"e": 1265,
"s": 1184,
"text": "Now take two new variables and get the Absolute value of the above two numbers −"
},
{
"code": null,
"e": 1319,
"s": 1265,
"text": "int abs1 = Math.Abs(val1);\nint abs2 = Math.Abs(val2);"
},
{
"code": null,
"e": 1388,
"s": 1319,
"text": "Let us see the complete code to display Absolute value of a number −"
},
{
"code": null,
"e": 1399,
"s": 1388,
"text": " Live Demo"
},
{
"code": null,
"e": 1770,
"s": 1399,
"text": "using System;\n\nclass Program {\n static void Main() {\n int val1 = 77;\n int val2 = -88;\n\n Console.WriteLine(\"Before...\");\n Console.WriteLine(val1);\n Console.WriteLine(val2);\n int abs1 = Math.Abs(val1);\n int abs2 = Math.Abs(val2);\n Console.WriteLine(\"After...\");\n Console.WriteLine(abs1);\n Console.WriteLine(abs2);\n }\n}"
},
{
"code": null,
"e": 1802,
"s": 1770,
"text": "Before...\n77\n-88\nAfter...\n77\n88"
}
] |
Descriptive Statistics in Julia - GeeksforGeeks
|
12 Oct, 2020
Julia is an appropriate programming language to perform data analysis. It has various built-in statistical functions and packages to support descriptive statistics. Descriptive Statistics helps in understanding the characteristics of the given data and to obtain a quick summary of it.
Packages required for performing Descriptive Statistics in Julia:
Distributions.jl: It provides a large collection of probabilistic distributions and related functions such as sampling, moments, entropy, probability density, logarithm, maximum likelihood estimation, distribution composition, etc.
StatsBase.jl: It provides basic support for statistics. It consists of various statistics-related functions, such as scalar statistics, high-order moment computation, counting, ranking, covariances, sampling, and empirical density estimation.
CSV.jl: It is used reading and writing Comma Separated Values(CSV) files.
Dataframes.jl: It is used for the creation of different data structures.
StatsPlots.jl: It is used to represent various statistical plots.
Steps to perform Descriptive Statistics in Julia:
Step 1: Installing Required Packages
The following command can be used to install the required packages:
Using Pkg
Pkg.add(“Distributions”)
Pkg.add(“StatsBase”)
Pkg.add(“CSV”)
Pkg.add(“Dataframes”)
Pkg.add(“StatsPlots”)
Step 2: Importing the Required Packages
Julia
# Descriptive Statistics in Julia# Importing required packages # to perform descriptive statistics # For random variable creationusing Distributions # For basic statistical operationsusing StatsBase # For reading and writing CSV filesusing CSV # For creation of Data Structures using DataFrames # For representing various plotsusing StatsPlots
Step 3: Creating stimulated Data (Random Variables)
Let’s create various variables with random data values
Example:
Julia
# Descriptive Statistics in Julia# Importing required packages # to perform descriptive statistics # For random variable creationusing Distributions # For basic statistical operationsusing StatsBase # For reading and writing CSV filesusing CSV # For creation of Data Structures using DataFrames # For representing various plotsusing StatsPlots # Uniform DistributionAge = rand(10:95, 100); # Weighted Uniform DistributionBloodGrp = rand(["A", "B", "O", "AB"], 100);
Step 4: Performing Descriptive statistics
The common statistical functions in Julia include mean(), median(), var(), and std() for calculating mean, median, variance and standard deviation of the data respectively. The more convenient functions aredescribe(), summarystats() from StatsBase package to perform descriptive statistics.
Example:
Julia
# Descriptive Statistics in Julia# Importing required packages # to perform descriptive statistics # For random variable creationusing Distributions # For basic statistical operationsusing StatsBase # For reading and writing CSV filesusing CSV # For creation of Data Structures using DataFrames # For representing various plotsusing StatsPlots # Uniform DistributionAge = rand(10:95, 100); # Weighted Uniform DistributionBloodGrp = rand(["A", "B", "O", "AB"], 100); # mean of Age variablemean(Age) # median of Age variablemedian(Age) # Variance of Age variablevar(Age) # Standard deviation of Age variablestd(Age) # Descriptive statistics of Age variabledescribe(Age) # summarystats function excludes typesummarystats(Age)
Output:
Step 5: Creating data frames from the stimulated data
Stimulated data should be stored in data frame objects for performing manipulation operations easily.
Example:
Julia
# Descriptive Statistics in Julia# Importing required packages # to perform descriptive statistics # For random variable creationusing Distributions # For basic statistical operationsusing StatsBase # For reading and writing CSV filesusing CSV # For creation of Data Structures using DataFrames # For representing various plotsusing StatsPlots # Uniform DistributionAge = rand(10:95, 100); # Weighted Uniform DistributionBloodGrp = rand(["A", "B", "O", "AB"], 100); # Creation of data frameDF = DataFrame(AGE = Age, BGRP = BloodGrp); # number of rows and columnssize(DF) # First 5 rowshead(DF, 5) # Last 5 rowstail(DF, 5) # Selecting specific data only# Data in which BGRP=AB is printedDFAB = DF[DF[:BGRP] .=="AB", :] # Data in which AGE>50 is printedDF50 = DF[DF[:AGE] .>90, :]
Output:
Step 6: Descriptive Statistics using DataFrame Objects
describe() function can be used to perform descriptive statistics of the data objects.
Example:
Julia
# Descriptive Statistics in Julia# Importing required packages # to perform descriptive statistics # For random variable creationusing Distributions # For basic statistical operationsusing StatsBase # For reading and writing CSV filesusing CSV # For creation of Data Structures using DataFrames # For representing various plotsusing StatsPlots # Uniform DistributionAge = rand(10:95, 100); # Weighted Uniform DistributionBloodGrp = rand(["A", "B", "O", "AB"], 100); # Creation of data frameDF = DataFrame(AGE = Age, BGRP = BloodGrp); # Perform descriptive statistics of data framedescribe(DF)
Output:
by() function is used to calculate the number of elements in the sample space of a categorical variable.
Example:
Julia
# Descriptive Statistics in Julia# Importing required packages #to perform descriptive statistics # For random variable creationusing Distributions # For basic statistical operationsusing StatsBase # For reading and writing CSV filesusing CSV # For creation of Data Structures using DataFrames # For representing various plotsusing StatsPlots # Uniform DistributionAge = rand(10:95, 100); # Weighted Uniform DistributionBloodGrp = rand(["A", "B", "O", "AB"], 100); # Creation of data frameDF = DataFrame(AGE = Age, BGRP = BloodGrp); # Counting the number of rows # with blood groups A,B,O,ABby(DF, :BGRP, DF-> DataFrame(Total = size(DF, 1))) # Counting the number of rows# with blood groups A, B, O, AB # using size argumentby(DF, :BGRP, size)
Output:
The descriptive statistics of different numerical variables can be calculated after separating them by categorical variables.
Example:
Julia
# Descriptive Statistics in Julia# Importing required packages # to perform descriptive statistics # For random variable creationusing Distributions # For basic statistical operationsusing StatsBase # For reading and writing CSV filesusing CSV # For creation of Data Structures using DataFrames # For representing various plotsusing StatsPlots # Uniform DistributionAge = rand(10:95, 100); # Weighted Uniform DistributionBloodGrp = rand(["A", "B", "O", "AB"], 100); # Creation of data frameDF = DataFrame(AGE = Age, BGRP = BloodGrp); # Mean AGE of Blood groups A, B, AB, Oby(DF, :BGRP, DF->mean(DF.AGE)) # Using the describe function # we can get the complete descriptive statisticsby(DF, :BGRP, DF->describe(DF.AGE))
Output:
Step 7: Visualizing Data using Plots
DataFrames package works well with the Plots package using the macro functions. In the following code:
Let’s analyze the Age distribution of the Blood groups A, B, AB, O:
Example:
Julia
# Descriptive Statistics in Julia# Importing required packages # to perform descriptive statistics # For random variable creationusing Distributions # For basic statistical operationsusing StatsBase # For reading and writing CSV filesusing CSV # For creation of Data Structures using DataFrames # For representing various plotsusing StatsPlots # Uniform DistributionAge = rand(10:95, 100); # Weighted Uniform DistributionBloodGrp = rand(["A", "B", "O", "AB"], 100); # Creation of data frameDF = DataFrame(AGE = Age, BGRP = BloodGrp); # Plotting density plot@df DF density( :AGE, group = :BGRP, xlab = "Age", ylab = "Distribution" )
Output:
Let’s create a box-and-Whisker plot of Age :
Example:
Julia
# Descriptive Statistics in Julia# Importing required packages to perform descriptive statistics # For random variable creationusing Distributions # For basic statistical operationsusing StatsBase # For reading and writing CSV filesusing CSV # For creation of Data Structures using DataFrames # For representing various plotsusing StatsPlots # Uniform DistributionAge = rand(10:95, 100); # Weighted Uniform DistributionBloodGrp = rand(["A", "B", "O", "AB"], 100); # Creation of data frameDF = DataFrame(AGE = Age, BGRP = BloodGrp); # Plotting Box plot@df DF boxplot( :AGE, xlab = ”Age”, ylab = ”Distribution” )
Output:
julia-statistics
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Formatting of Strings in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Tuples in Julia
while loop in Julia
Manipulating matrices in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Storing Output on a File in Julia
Taking Input from Users in Julia
|
[
{
"code": null,
"e": 23843,
"s": 23815,
"text": "\n12 Oct, 2020"
},
{
"code": null,
"e": 24129,
"s": 23843,
"text": "Julia is an appropriate programming language to perform data analysis. It has various built-in statistical functions and packages to support descriptive statistics. Descriptive Statistics helps in understanding the characteristics of the given data and to obtain a quick summary of it."
},
{
"code": null,
"e": 24195,
"s": 24129,
"text": "Packages required for performing Descriptive Statistics in Julia:"
},
{
"code": null,
"e": 24427,
"s": 24195,
"text": "Distributions.jl: It provides a large collection of probabilistic distributions and related functions such as sampling, moments, entropy, probability density, logarithm, maximum likelihood estimation, distribution composition, etc."
},
{
"code": null,
"e": 24670,
"s": 24427,
"text": "StatsBase.jl: It provides basic support for statistics. It consists of various statistics-related functions, such as scalar statistics, high-order moment computation, counting, ranking, covariances, sampling, and empirical density estimation."
},
{
"code": null,
"e": 24744,
"s": 24670,
"text": "CSV.jl: It is used reading and writing Comma Separated Values(CSV) files."
},
{
"code": null,
"e": 24817,
"s": 24744,
"text": "Dataframes.jl: It is used for the creation of different data structures."
},
{
"code": null,
"e": 24883,
"s": 24817,
"text": "StatsPlots.jl: It is used to represent various statistical plots."
},
{
"code": null,
"e": 24933,
"s": 24883,
"text": "Steps to perform Descriptive Statistics in Julia:"
},
{
"code": null,
"e": 24970,
"s": 24933,
"text": "Step 1: Installing Required Packages"
},
{
"code": null,
"e": 25038,
"s": 24970,
"text": "The following command can be used to install the required packages:"
},
{
"code": null,
"e": 25155,
"s": 25038,
"text": "Using Pkg\nPkg.add(“Distributions”)\nPkg.add(“StatsBase”)\nPkg.add(“CSV”)\nPkg.add(“Dataframes”)\nPkg.add(“StatsPlots”)\n\n"
},
{
"code": null,
"e": 25195,
"s": 25155,
"text": "Step 2: Importing the Required Packages"
},
{
"code": null,
"e": 25201,
"s": 25195,
"text": "Julia"
},
{
"code": "# Descriptive Statistics in Julia# Importing required packages # to perform descriptive statistics # For random variable creationusing Distributions # For basic statistical operationsusing StatsBase # For reading and writing CSV filesusing CSV # For creation of Data Structures using DataFrames # For representing various plotsusing StatsPlots",
"e": 25554,
"s": 25201,
"text": null
},
{
"code": null,
"e": 25606,
"s": 25554,
"text": "Step 3: Creating stimulated Data (Random Variables)"
},
{
"code": null,
"e": 25661,
"s": 25606,
"text": "Let’s create various variables with random data values"
},
{
"code": null,
"e": 25670,
"s": 25661,
"text": "Example:"
},
{
"code": null,
"e": 25676,
"s": 25670,
"text": "Julia"
},
{
"code": "# Descriptive Statistics in Julia# Importing required packages # to perform descriptive statistics # For random variable creationusing Distributions # For basic statistical operationsusing StatsBase # For reading and writing CSV filesusing CSV # For creation of Data Structures using DataFrames # For representing various plotsusing StatsPlots # Uniform DistributionAge = rand(10:95, 100); # Weighted Uniform DistributionBloodGrp = rand([\"A\", \"B\", \"O\", \"AB\"], 100);",
"e": 26156,
"s": 25676,
"text": null
},
{
"code": null,
"e": 26198,
"s": 26156,
"text": "Step 4: Performing Descriptive statistics"
},
{
"code": null,
"e": 26489,
"s": 26198,
"text": "The common statistical functions in Julia include mean(), median(), var(), and std() for calculating mean, median, variance and standard deviation of the data respectively. The more convenient functions aredescribe(), summarystats() from StatsBase package to perform descriptive statistics."
},
{
"code": null,
"e": 26498,
"s": 26489,
"text": "Example:"
},
{
"code": null,
"e": 26504,
"s": 26498,
"text": "Julia"
},
{
"code": "# Descriptive Statistics in Julia# Importing required packages # to perform descriptive statistics # For random variable creationusing Distributions # For basic statistical operationsusing StatsBase # For reading and writing CSV filesusing CSV # For creation of Data Structures using DataFrames # For representing various plotsusing StatsPlots # Uniform DistributionAge = rand(10:95, 100); # Weighted Uniform DistributionBloodGrp = rand([\"A\", \"B\", \"O\", \"AB\"], 100); # mean of Age variablemean(Age) # median of Age variablemedian(Age) # Variance of Age variablevar(Age) # Standard deviation of Age variablestd(Age) # Descriptive statistics of Age variabledescribe(Age) # summarystats function excludes typesummarystats(Age)",
"e": 27252,
"s": 26504,
"text": null
},
{
"code": null,
"e": 27260,
"s": 27252,
"text": "Output:"
},
{
"code": null,
"e": 27314,
"s": 27260,
"text": "Step 5: Creating data frames from the stimulated data"
},
{
"code": null,
"e": 27416,
"s": 27314,
"text": "Stimulated data should be stored in data frame objects for performing manipulation operations easily."
},
{
"code": null,
"e": 27425,
"s": 27416,
"text": "Example:"
},
{
"code": null,
"e": 27431,
"s": 27425,
"text": "Julia"
},
{
"code": "# Descriptive Statistics in Julia# Importing required packages # to perform descriptive statistics # For random variable creationusing Distributions # For basic statistical operationsusing StatsBase # For reading and writing CSV filesusing CSV # For creation of Data Structures using DataFrames # For representing various plotsusing StatsPlots # Uniform DistributionAge = rand(10:95, 100); # Weighted Uniform DistributionBloodGrp = rand([\"A\", \"B\", \"O\", \"AB\"], 100); # Creation of data frameDF = DataFrame(AGE = Age, BGRP = BloodGrp); # number of rows and columnssize(DF) # First 5 rowshead(DF, 5) # Last 5 rowstail(DF, 5) # Selecting specific data only# Data in which BGRP=AB is printedDFAB = DF[DF[:BGRP] .==\"AB\", :] # Data in which AGE>50 is printedDF50 = DF[DF[:AGE] .>90, :]",
"e": 28237,
"s": 27431,
"text": null
},
{
"code": null,
"e": 28245,
"s": 28237,
"text": "Output:"
},
{
"code": null,
"e": 28300,
"s": 28245,
"text": "Step 6: Descriptive Statistics using DataFrame Objects"
},
{
"code": null,
"e": 28387,
"s": 28300,
"text": "describe() function can be used to perform descriptive statistics of the data objects."
},
{
"code": null,
"e": 28396,
"s": 28387,
"text": "Example:"
},
{
"code": null,
"e": 28402,
"s": 28396,
"text": "Julia"
},
{
"code": "# Descriptive Statistics in Julia# Importing required packages # to perform descriptive statistics # For random variable creationusing Distributions # For basic statistical operationsusing StatsBase # For reading and writing CSV filesusing CSV # For creation of Data Structures using DataFrames # For representing various plotsusing StatsPlots # Uniform DistributionAge = rand(10:95, 100); # Weighted Uniform DistributionBloodGrp = rand([\"A\", \"B\", \"O\", \"AB\"], 100); # Creation of data frameDF = DataFrame(AGE = Age, BGRP = BloodGrp); # Perform descriptive statistics of data framedescribe(DF)",
"e": 29017,
"s": 28402,
"text": null
},
{
"code": null,
"e": 29025,
"s": 29017,
"text": "Output:"
},
{
"code": null,
"e": 29130,
"s": 29025,
"text": "by() function is used to calculate the number of elements in the sample space of a categorical variable."
},
{
"code": null,
"e": 29139,
"s": 29130,
"text": "Example:"
},
{
"code": null,
"e": 29145,
"s": 29139,
"text": "Julia"
},
{
"code": "# Descriptive Statistics in Julia# Importing required packages #to perform descriptive statistics # For random variable creationusing Distributions # For basic statistical operationsusing StatsBase # For reading and writing CSV filesusing CSV # For creation of Data Structures using DataFrames # For representing various plotsusing StatsPlots # Uniform DistributionAge = rand(10:95, 100); # Weighted Uniform DistributionBloodGrp = rand([\"A\", \"B\", \"O\", \"AB\"], 100); # Creation of data frameDF = DataFrame(AGE = Age, BGRP = BloodGrp); # Counting the number of rows # with blood groups A,B,O,ABby(DF, :BGRP, DF-> DataFrame(Total = size(DF, 1))) # Counting the number of rows# with blood groups A, B, O, AB # using size argumentby(DF, :BGRP, size)",
"e": 29912,
"s": 29145,
"text": null
},
{
"code": null,
"e": 29920,
"s": 29912,
"text": "Output:"
},
{
"code": null,
"e": 30046,
"s": 29920,
"text": "The descriptive statistics of different numerical variables can be calculated after separating them by categorical variables."
},
{
"code": null,
"e": 30055,
"s": 30046,
"text": "Example:"
},
{
"code": null,
"e": 30061,
"s": 30055,
"text": "Julia"
},
{
"code": "# Descriptive Statistics in Julia# Importing required packages # to perform descriptive statistics # For random variable creationusing Distributions # For basic statistical operationsusing StatsBase # For reading and writing CSV filesusing CSV # For creation of Data Structures using DataFrames # For representing various plotsusing StatsPlots # Uniform DistributionAge = rand(10:95, 100); # Weighted Uniform DistributionBloodGrp = rand([\"A\", \"B\", \"O\", \"AB\"], 100); # Creation of data frameDF = DataFrame(AGE = Age, BGRP = BloodGrp); # Mean AGE of Blood groups A, B, AB, Oby(DF, :BGRP, DF->mean(DF.AGE)) # Using the describe function # we can get the complete descriptive statisticsby(DF, :BGRP, DF->describe(DF.AGE))",
"e": 30802,
"s": 30061,
"text": null
},
{
"code": null,
"e": 30810,
"s": 30802,
"text": "Output:"
},
{
"code": null,
"e": 30847,
"s": 30810,
"text": "Step 7: Visualizing Data using Plots"
},
{
"code": null,
"e": 30950,
"s": 30847,
"text": "DataFrames package works well with the Plots package using the macro functions. In the following code:"
},
{
"code": null,
"e": 31018,
"s": 30950,
"text": "Let’s analyze the Age distribution of the Blood groups A, B, AB, O:"
},
{
"code": null,
"e": 31027,
"s": 31018,
"text": "Example:"
},
{
"code": null,
"e": 31033,
"s": 31027,
"text": "Julia"
},
{
"code": "# Descriptive Statistics in Julia# Importing required packages # to perform descriptive statistics # For random variable creationusing Distributions # For basic statistical operationsusing StatsBase # For reading and writing CSV filesusing CSV # For creation of Data Structures using DataFrames # For representing various plotsusing StatsPlots # Uniform DistributionAge = rand(10:95, 100); # Weighted Uniform DistributionBloodGrp = rand([\"A\", \"B\", \"O\", \"AB\"], 100); # Creation of data frameDF = DataFrame(AGE = Age, BGRP = BloodGrp); # Plotting density plot@df DF density( :AGE, group = :BGRP, xlab = \"Age\", ylab = \"Distribution\" )",
"e": 31698,
"s": 31033,
"text": null
},
{
"code": null,
"e": 31706,
"s": 31698,
"text": "Output:"
},
{
"code": null,
"e": 31751,
"s": 31706,
"text": "Let’s create a box-and-Whisker plot of Age :"
},
{
"code": null,
"e": 31760,
"s": 31751,
"text": "Example:"
},
{
"code": null,
"e": 31766,
"s": 31760,
"text": "Julia"
},
{
"code": "# Descriptive Statistics in Julia# Importing required packages to perform descriptive statistics # For random variable creationusing Distributions # For basic statistical operationsusing StatsBase # For reading and writing CSV filesusing CSV # For creation of Data Structures using DataFrames # For representing various plotsusing StatsPlots # Uniform DistributionAge = rand(10:95, 100); # Weighted Uniform DistributionBloodGrp = rand([\"A\", \"B\", \"O\", \"AB\"], 100); # Creation of data frameDF = DataFrame(AGE = Age, BGRP = BloodGrp); # Plotting Box plot@df DF boxplot( :AGE, xlab = ”Age”, ylab = ”Distribution” )",
"e": 32405,
"s": 31766,
"text": null
},
{
"code": null,
"e": 32413,
"s": 32405,
"text": "Output:"
},
{
"code": null,
"e": 32430,
"s": 32413,
"text": "julia-statistics"
},
{
"code": null,
"e": 32436,
"s": 32430,
"text": "Julia"
},
{
"code": null,
"e": 32534,
"s": 32436,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32543,
"s": 32534,
"text": "Comments"
},
{
"code": null,
"e": 32556,
"s": 32543,
"text": "Old Comments"
},
{
"code": null,
"e": 32573,
"s": 32556,
"text": "Vectors in Julia"
},
{
"code": null,
"e": 32633,
"s": 32573,
"text": "Getting rounded value of a number in Julia - round() Method"
},
{
"code": null,
"e": 32664,
"s": 32633,
"text": "Formatting of Strings in Julia"
},
{
"code": null,
"e": 32725,
"s": 32664,
"text": "Reshaping array dimensions in Julia | Array reshape() Method"
},
{
"code": null,
"e": 32741,
"s": 32725,
"text": "Tuples in Julia"
},
{
"code": null,
"e": 32761,
"s": 32741,
"text": "while loop in Julia"
},
{
"code": null,
"e": 32792,
"s": 32761,
"text": "Manipulating matrices in Julia"
},
{
"code": null,
"e": 32862,
"s": 32792,
"text": "Get array dimensions and size of a dimension in Julia - size() Method"
},
{
"code": null,
"e": 32896,
"s": 32862,
"text": "Storing Output on a File in Julia"
}
] |
PDF Redaction using Python - GeeksforGeeks
|
22 Jun, 2021
So, let’s just start with what exactly does Redaction mean. So, Redaction is a form of editing in which multiple sources of texts are combined and altered slightly to make a single document. In simple words, whenever you see any part in any document which is blackened out to hide some information, it is known as Redaction. To perform the same task on a PDF is known as PDF Redaction.
If anyone has worked with any kind of data extraction on PDF, then they know how painful it can be to handle PDFs. Consider a scenario where you want to share a PDF with someone but there are certain parts in a PDF that you don’t want to get leaked. So, what you can do is, you can redact the texts. It is pretty easy to redact texts using something like Adobe Acrobat, but what if you want this to be an automated process. Suppose, you are working in a company that shares its user’s purchases on its site with the Income Tax Department but due to strict privacy policies, the safety of users’ Personal Identifiable Information (PII) they want to remove those from the transaction receipts. If the user base is large then it can not be done manually, so you need some kind of automation to do so. This is where Python comes in. There is this amazing library called PyMuPDF, which is a library for pdf handling and performing various operations on them. So, let’s just check out how we are going to do so.
First, you need to have Python3 installed and also PyMuPDF installed. To install PyMuPDF, simply open up your terminal and type the following in it
pip3 install PyMuPDF
For this demonstration, we will be only redacting Email IDs from a PDF. You can apply the same logic to any other PII
Approach:
Read the PDF fileIterate line by line through the pdf and look for each occurrence of any email id. Email IDs have a pattern, so we will be using Regex to identify an emailOnce we encounter an email, we add it to a list and then return the list at the end of the last lineNow, we need to simply search for the occurrence of the fetched email ids in the pdf. PyMuPDF makes it very easy to find any text in a PDF. It returns four coordinates of a rectangle inside which the text will be present.Once we have all the text boxes, we can simply iterate over those boxes and Redact each box from the PDF
Read the PDF file
Iterate line by line through the pdf and look for each occurrence of any email id. Email IDs have a pattern, so we will be using Regex to identify an email
Once we encounter an email, we add it to a list and then return the list at the end of the last line
Now, we need to simply search for the occurrence of the fetched email ids in the pdf. PyMuPDF makes it very easy to find any text in a PDF. It returns four coordinates of a rectangle inside which the text will be present.
Once we have all the text boxes, we can simply iterate over those boxes and Redact each box from the PDF
Below is the implementation of the above approach and I have added inline comments for a better understanding of the code.
PDF file used:
Before
Python3
# importsimport fitzimport re class Redactor: # static methods work independent of class object @staticmethod def get_sensitive_data(lines): """ Function to get all the lines """ # email regex EMAIL_REG = r"([\w\.\d]+\@[\w\d]+\.[\w\d]+)" for line in lines: # matching the regex to each line if re.search(EMAIL_REG, line, re.IGNORECASE): search = re.search(EMAIL_REG, line, re.IGNORECASE) # yields creates a generator # generator is used to return # values in between function iterations yield search.group(1) # constructor def __init__(self, path): self.path = path def redaction(self): """ main redactor code """ # opening the pdf doc = fitz.open(self.path) # iterating through pages for page in doc: # _wrapContents is needed for fixing # alignment issues with rect boxes in some # cases where there is alignment issue page._wrapContents() # getting the rect boxes which consists the matching email regex sensitive = self.get_sensitive_data(page.getText("text") .split('\n')) for data in sensitive: areas = page.searchFor(data) # drawing outline over sensitive datas [page.addRedactAnnot(area, fill = (0, 0, 0)) for area in areas] # applying the redaction page.apply_redactions() # saving it to a new pdf doc.save('redacted.pdf') print("Successfully redacted") # driver code for testingif __name__ == "__main__": # replace it with name of the pdf file path = 'testing.pdf' redactor = Redactor(path) redactor.redaction()
Output:
After
saurabh1990aror
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24824,
"s": 24796,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 25210,
"s": 24824,
"text": "So, let’s just start with what exactly does Redaction mean. So, Redaction is a form of editing in which multiple sources of texts are combined and altered slightly to make a single document. In simple words, whenever you see any part in any document which is blackened out to hide some information, it is known as Redaction. To perform the same task on a PDF is known as PDF Redaction."
},
{
"code": null,
"e": 26216,
"s": 25210,
"text": "If anyone has worked with any kind of data extraction on PDF, then they know how painful it can be to handle PDFs. Consider a scenario where you want to share a PDF with someone but there are certain parts in a PDF that you don’t want to get leaked. So, what you can do is, you can redact the texts. It is pretty easy to redact texts using something like Adobe Acrobat, but what if you want this to be an automated process. Suppose, you are working in a company that shares its user’s purchases on its site with the Income Tax Department but due to strict privacy policies, the safety of users’ Personal Identifiable Information (PII) they want to remove those from the transaction receipts. If the user base is large then it can not be done manually, so you need some kind of automation to do so. This is where Python comes in. There is this amazing library called PyMuPDF, which is a library for pdf handling and performing various operations on them. So, let’s just check out how we are going to do so."
},
{
"code": null,
"e": 26364,
"s": 26216,
"text": "First, you need to have Python3 installed and also PyMuPDF installed. To install PyMuPDF, simply open up your terminal and type the following in it"
},
{
"code": null,
"e": 26385,
"s": 26364,
"text": "pip3 install PyMuPDF"
},
{
"code": null,
"e": 26503,
"s": 26385,
"text": "For this demonstration, we will be only redacting Email IDs from a PDF. You can apply the same logic to any other PII"
},
{
"code": null,
"e": 26513,
"s": 26503,
"text": "Approach:"
},
{
"code": null,
"e": 27111,
"s": 26513,
"text": "Read the PDF fileIterate line by line through the pdf and look for each occurrence of any email id. Email IDs have a pattern, so we will be using Regex to identify an emailOnce we encounter an email, we add it to a list and then return the list at the end of the last lineNow, we need to simply search for the occurrence of the fetched email ids in the pdf. PyMuPDF makes it very easy to find any text in a PDF. It returns four coordinates of a rectangle inside which the text will be present.Once we have all the text boxes, we can simply iterate over those boxes and Redact each box from the PDF"
},
{
"code": null,
"e": 27129,
"s": 27111,
"text": "Read the PDF file"
},
{
"code": null,
"e": 27285,
"s": 27129,
"text": "Iterate line by line through the pdf and look for each occurrence of any email id. Email IDs have a pattern, so we will be using Regex to identify an email"
},
{
"code": null,
"e": 27386,
"s": 27285,
"text": "Once we encounter an email, we add it to a list and then return the list at the end of the last line"
},
{
"code": null,
"e": 27608,
"s": 27386,
"text": "Now, we need to simply search for the occurrence of the fetched email ids in the pdf. PyMuPDF makes it very easy to find any text in a PDF. It returns four coordinates of a rectangle inside which the text will be present."
},
{
"code": null,
"e": 27713,
"s": 27608,
"text": "Once we have all the text boxes, we can simply iterate over those boxes and Redact each box from the PDF"
},
{
"code": null,
"e": 27836,
"s": 27713,
"text": "Below is the implementation of the above approach and I have added inline comments for a better understanding of the code."
},
{
"code": null,
"e": 27851,
"s": 27836,
"text": "PDF file used:"
},
{
"code": null,
"e": 27858,
"s": 27851,
"text": "Before"
},
{
"code": null,
"e": 27866,
"s": 27858,
"text": "Python3"
},
{
"code": "# importsimport fitzimport re class Redactor: # static methods work independent of class object @staticmethod def get_sensitive_data(lines): \"\"\" Function to get all the lines \"\"\" # email regex EMAIL_REG = r\"([\\w\\.\\d]+\\@[\\w\\d]+\\.[\\w\\d]+)\" for line in lines: # matching the regex to each line if re.search(EMAIL_REG, line, re.IGNORECASE): search = re.search(EMAIL_REG, line, re.IGNORECASE) # yields creates a generator # generator is used to return # values in between function iterations yield search.group(1) # constructor def __init__(self, path): self.path = path def redaction(self): \"\"\" main redactor code \"\"\" # opening the pdf doc = fitz.open(self.path) # iterating through pages for page in doc: # _wrapContents is needed for fixing # alignment issues with rect boxes in some # cases where there is alignment issue page._wrapContents() # getting the rect boxes which consists the matching email regex sensitive = self.get_sensitive_data(page.getText(\"text\") .split('\\n')) for data in sensitive: areas = page.searchFor(data) # drawing outline over sensitive datas [page.addRedactAnnot(area, fill = (0, 0, 0)) for area in areas] # applying the redaction page.apply_redactions() # saving it to a new pdf doc.save('redacted.pdf') print(\"Successfully redacted\") # driver code for testingif __name__ == \"__main__\": # replace it with name of the pdf file path = 'testing.pdf' redactor = Redactor(path) redactor.redaction()",
"e": 29845,
"s": 27866,
"text": null
},
{
"code": null,
"e": 29857,
"s": 29849,
"text": "Output:"
},
{
"code": null,
"e": 29865,
"s": 29859,
"text": "After"
},
{
"code": null,
"e": 29883,
"s": 29867,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 29898,
"s": 29883,
"text": "python-utility"
},
{
"code": null,
"e": 29905,
"s": 29898,
"text": "Python"
},
{
"code": null,
"e": 30003,
"s": 29905,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30012,
"s": 30003,
"text": "Comments"
},
{
"code": null,
"e": 30025,
"s": 30012,
"text": "Old Comments"
},
{
"code": null,
"e": 30043,
"s": 30025,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30075,
"s": 30043,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30110,
"s": 30075,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 30132,
"s": 30110,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30162,
"s": 30132,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 30204,
"s": 30162,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30247,
"s": 30204,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 30284,
"s": 30247,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 30310,
"s": 30284,
"text": "Python String | replace()"
}
] |
In JavaScript Why do we use "use strict"?
|
Strict Mode is a feature introduced in ES5 that allows you to place a program, or a function, in a “strict” mode.
This strict context prevents certain actions from being taken and throws more exceptions (generally providing the user with more information). Some specific features of strict mode −
Variables not declared but being assigned directly will fail. An attempt to assign foo = "bar"; where ‘foo’ hasn’t been defined will fail.
Variables not declared but being assigned directly will fail. An attempt to assign foo = "bar"; where ‘foo’ hasn’t been defined will fail.
You cannot use eval in strict mode
You cannot use eval in strict mode
You cannot reassign arguments array inside a function
You cannot reassign arguments array inside a function
Use of with statements is not allowed
Use of with statements is not allowed
You can use your scripts in strict mode as follows −
Add the following at the top of a script to enable it for the whole script −
"use strict";
If you want to use it only within a function then add it only in that context.
function strictFunc() {
"use strict";
// rest of function
}
|
[
{
"code": null,
"e": 1176,
"s": 1062,
"text": "Strict Mode is a feature introduced in ES5 that allows you to place a program, or a function, in a “strict” mode."
},
{
"code": null,
"e": 1359,
"s": 1176,
"text": "This strict context prevents certain actions from being taken and throws more exceptions (generally providing the user with more information). Some specific features of strict mode −"
},
{
"code": null,
"e": 1498,
"s": 1359,
"text": "Variables not declared but being assigned directly will fail. An attempt to assign foo = \"bar\"; where ‘foo’ hasn’t been defined will fail."
},
{
"code": null,
"e": 1637,
"s": 1498,
"text": "Variables not declared but being assigned directly will fail. An attempt to assign foo = \"bar\"; where ‘foo’ hasn’t been defined will fail."
},
{
"code": null,
"e": 1672,
"s": 1637,
"text": "You cannot use eval in strict mode"
},
{
"code": null,
"e": 1707,
"s": 1672,
"text": "You cannot use eval in strict mode"
},
{
"code": null,
"e": 1761,
"s": 1707,
"text": "You cannot reassign arguments array inside a function"
},
{
"code": null,
"e": 1815,
"s": 1761,
"text": "You cannot reassign arguments array inside a function"
},
{
"code": null,
"e": 1853,
"s": 1815,
"text": "Use of with statements is not allowed"
},
{
"code": null,
"e": 1891,
"s": 1853,
"text": "Use of with statements is not allowed"
},
{
"code": null,
"e": 1944,
"s": 1891,
"text": "You can use your scripts in strict mode as follows −"
},
{
"code": null,
"e": 2021,
"s": 1944,
"text": "Add the following at the top of a script to enable it for the whole script −"
},
{
"code": null,
"e": 2035,
"s": 2021,
"text": "\"use strict\";"
},
{
"code": null,
"e": 2114,
"s": 2035,
"text": "If you want to use it only within a function then add it only in that context."
},
{
"code": null,
"e": 2180,
"s": 2114,
"text": "function strictFunc() {\n \"use strict\";\n // rest of function\n}"
}
] |
Data analysis using Python Pandas
|
In this tutorial, we are going to see the data analysis using Python pandas library. The library pandas are written in C. So, we don't get any problem with speed. It is famous for data analysis. We have two types of data storage structures in pandas. They are Series and DataFrame. Let's see one by one.
Series is a 1D array with customized index and values. We can create a Series object using the pandas.Series(data, index) class. Series will take integers, lists, dictionaries as data. Let's see some examples.
# importing the pandas library
import pandas as pd
# data
data = [1, 2, 3]
# creating Series object
# Series automatically takes the default index
series = pd.Series(data)
print(series)
If you run the above program, you will get the following result.
0 1
1 2
2 3
dtype: int64
How to have a customized index? See the example.
# importing the pandas library
import pandas as pd
# data
data = [1, 2, 3]
# index
index = ['a', 'b', 'c']
# creating Series object
series = pd.Series(data, index)
print(series)
If you run the above program, you will get the following result.
a 1
b 2
c 3
dtype: int64
When we give the data as a dictionary to the Series class, then it takes keys as index and values as actual data. Let's see one example.
# importing the pandas library
import pandas as pd
# data
data = {'a':97, 'b':98, 'c':99}
# creating Series object
series = pd.Series(data)
print(series)
If you run the above program, you will get the following results.
a 97
b 98
c 99
dtype: int64
We can access the data from the Series using an index. Let's see the examples.
# importing the pandas library
import pandas as pd
# data
data = {'a':97, 'b':98, 'c':99}
# creating Series object
series = pd.Series(data)
# accessing the data from the Series using indexes
print(series['a'], series['b'], series['c'])
If you run the above code, you will get the following results.
97 98 99
We have how to use Series class in pandas. Let's see how to use the DataFrame class. DataFrame data structure class in pandas that contains rows and columns.
We can create DataFrame objects using lists, dictionaries, Series, etc.., Let's create the DataFrame using lists.
# importing the pandas library
import pandas as pd
# lists
names = ['Tutorialspoint', 'Mohit', 'Sharma']
ages = [25, 32, 21]
# creating a DataFrame
data_frame = pd.DataFrame({'Name': names, 'Age': ages})
# printing the DataFrame
print(data_frame)
If you run the above program, you will get the following results.
Name Age
0 Tutorialspoint 25
1 Mohit 32
2 Sharma 21
Let's see how to create a data frame object using the Series.
# importing the pandas library
import pandas as pd
# Series
_1 = pd.Series([1, 2, 3])
_2 = pd.Series([1, 4, 9])
_3 = pd.Series([1, 8, 27])
# creating a DataFrame
data_frame = pd.DataFrame({"a":_1, "b":_2, "c":_3})
# printing the DataFrame
print(data_frame)
If you run the above code, you will get the following results.
a b c
0 1 1 1
1 2 4 8
2 3 9 27
We can access the data from the DataFrames using the column name. Let's see one example.
# importing the pandas library
import pandas as pd
# Series
_1 = pd.Series([1, 2, 3])
_2 = pd.Series([1, 4, 9])
_3 = pd.Series([1, 8, 27])
# creating a DataFrame
data_frame = pd.DataFrame({"a":_1, "b":_2, "c":_3})
# accessing the entire column with name 'a'
print(data_frame['a'])
If you run the above code, you will get the following results.
0 1
1 2
2 3
Name: a, dtype: int64
If you have any doubts in the tutorial, mention them in the comment section.
|
[
{
"code": null,
"e": 1366,
"s": 1062,
"text": "In this tutorial, we are going to see the data analysis using Python pandas library. The library pandas are written in C. So, we don't get any problem with speed. It is famous for data analysis. We have two types of data storage structures in pandas. They are Series and DataFrame. Let's see one by one."
},
{
"code": null,
"e": 1576,
"s": 1366,
"text": "Series is a 1D array with customized index and values. We can create a Series object using the pandas.Series(data, index) class. Series will take integers, lists, dictionaries as data. Let's see some examples."
},
{
"code": null,
"e": 1762,
"s": 1576,
"text": "# importing the pandas library\nimport pandas as pd\n# data\ndata = [1, 2, 3]\n# creating Series object\n# Series automatically takes the default index\nseries = pd.Series(data)\nprint(series)"
},
{
"code": null,
"e": 1827,
"s": 1762,
"text": "If you run the above program, you will get the following result."
},
{
"code": null,
"e": 1852,
"s": 1827,
"text": "0 1\n1 2\n2 3\ndtype: int64"
},
{
"code": null,
"e": 1901,
"s": 1852,
"text": "How to have a customized index? See the example."
},
{
"code": null,
"e": 2079,
"s": 1901,
"text": "# importing the pandas library\nimport pandas as pd\n# data\ndata = [1, 2, 3]\n# index\nindex = ['a', 'b', 'c']\n# creating Series object\nseries = pd.Series(data, index)\nprint(series)"
},
{
"code": null,
"e": 2144,
"s": 2079,
"text": "If you run the above program, you will get the following result."
},
{
"code": null,
"e": 2169,
"s": 2144,
"text": "a 1\nb 2\nc 3\ndtype: int64"
},
{
"code": null,
"e": 2306,
"s": 2169,
"text": "When we give the data as a dictionary to the Series class, then it takes keys as index and values as actual data. Let's see one example."
},
{
"code": null,
"e": 2460,
"s": 2306,
"text": "# importing the pandas library\nimport pandas as pd\n# data\ndata = {'a':97, 'b':98, 'c':99}\n# creating Series object\nseries = pd.Series(data)\nprint(series)"
},
{
"code": null,
"e": 2526,
"s": 2460,
"text": "If you run the above program, you will get the following results."
},
{
"code": null,
"e": 2554,
"s": 2526,
"text": "a 97\nb 98\nc 99\ndtype: int64"
},
{
"code": null,
"e": 2633,
"s": 2554,
"text": "We can access the data from the Series using an index. Let's see the examples."
},
{
"code": null,
"e": 2869,
"s": 2633,
"text": "# importing the pandas library\nimport pandas as pd\n# data\ndata = {'a':97, 'b':98, 'c':99}\n# creating Series object\nseries = pd.Series(data)\n# accessing the data from the Series using indexes\nprint(series['a'], series['b'], series['c'])"
},
{
"code": null,
"e": 2932,
"s": 2869,
"text": "If you run the above code, you will get the following results."
},
{
"code": null,
"e": 2941,
"s": 2932,
"text": "97 98 99"
},
{
"code": null,
"e": 3099,
"s": 2941,
"text": "We have how to use Series class in pandas. Let's see how to use the DataFrame class. DataFrame data structure class in pandas that contains rows and columns."
},
{
"code": null,
"e": 3213,
"s": 3099,
"text": "We can create DataFrame objects using lists, dictionaries, Series, etc.., Let's create the DataFrame using lists."
},
{
"code": null,
"e": 3460,
"s": 3213,
"text": "# importing the pandas library\nimport pandas as pd\n# lists\nnames = ['Tutorialspoint', 'Mohit', 'Sharma']\nages = [25, 32, 21]\n# creating a DataFrame\ndata_frame = pd.DataFrame({'Name': names, 'Age': ages})\n# printing the DataFrame\nprint(data_frame)"
},
{
"code": null,
"e": 3526,
"s": 3460,
"text": "If you run the above program, you will get the following results."
},
{
"code": null,
"e": 3631,
"s": 3526,
"text": " Name Age\n0 Tutorialspoint 25\n1 Mohit 32\n2 Sharma 21"
},
{
"code": null,
"e": 3693,
"s": 3631,
"text": "Let's see how to create a data frame object using the Series."
},
{
"code": null,
"e": 3950,
"s": 3693,
"text": "# importing the pandas library\nimport pandas as pd\n# Series\n_1 = pd.Series([1, 2, 3])\n_2 = pd.Series([1, 4, 9])\n_3 = pd.Series([1, 8, 27])\n# creating a DataFrame\ndata_frame = pd.DataFrame({\"a\":_1, \"b\":_2, \"c\":_3})\n# printing the DataFrame\nprint(data_frame)"
},
{
"code": null,
"e": 4013,
"s": 3950,
"text": "If you run the above code, you will get the following results."
},
{
"code": null,
"e": 4058,
"s": 4013,
"text": " a b c\n0 1 1 1\n1 2 4 8\n2 3 9 27"
},
{
"code": null,
"e": 4147,
"s": 4058,
"text": "We can access the data from the DataFrames using the column name. Let's see one example."
},
{
"code": null,
"e": 4428,
"s": 4147,
"text": "# importing the pandas library\nimport pandas as pd\n# Series\n_1 = pd.Series([1, 2, 3])\n_2 = pd.Series([1, 4, 9])\n_3 = pd.Series([1, 8, 27])\n# creating a DataFrame\ndata_frame = pd.DataFrame({\"a\":_1, \"b\":_2, \"c\":_3})\n# accessing the entire column with name 'a'\nprint(data_frame['a'])"
},
{
"code": null,
"e": 4491,
"s": 4428,
"text": "If you run the above code, you will get the following results."
},
{
"code": null,
"e": 4525,
"s": 4491,
"text": "0 1\n1 2\n2 3\nName: a, dtype: int64"
},
{
"code": null,
"e": 4602,
"s": 4525,
"text": "If you have any doubts in the tutorial, mention them in the comment section."
}
] |
Machine Learning Perceptron Implementation | by Tarun Gupta | Towards Data Science
|
In this post, we are going to have a look at a program written in Python3 using numpy. We will discuss the basics of what a perceptron is, what is the delta rule and how to use it to converge the learning of the perceptron.
The perceptron is an algorithm for supervised learning of binary classifiers (let’s assumer {1, 0}). We have a linear combination of weight vector and the input data vector that is passed through an activation function and then compared to a threshold value. If the linear combination is greater than the threshold, we predict the class as 1 otherwise 0. Mathematically,
Perceptrons only represent linearly separable problems. They fail to converge if the training examples are not linearly separable. This brings into picture the delta rule.
The delta rule converges towards a best-fit approximation of the target concept. The key idea is to use gradient descent to search the hypothesis space of all possible weight vectors.
Note: This provides the basis for “Backpropogation” algorithm.
Now, let’s discuss the problem at hand. The program will read a dataset(tab separated file) and treat the first column as the target concept. The values present in the target concept are A and B, we will consider A as +ve class or 1 and B as -ve class or 0. The program implements the perceptron training rule in batch mode with a constant learning rate and an annealing(decreasing as the number of iterations increase) learning rate, starting with learning rate as 1.
where Y(x, w) is the set of samples which are misclassified. We will use the count or the number of misclassified points as our error rate(i.e. | Y(x, w)|). The output will also be a tab separated(tsv) file containing the error for each iteration, i.e. it will have 100 columns. Also, it will have 2 rows, one for normal learning rate and one for annealing learning rate.
Now, the understanding of what perceptron is, what delta rule and how we are going to use it. Let’s get started with Python3 implementation.
In the program, we are providing two inputs from the command line. They are:
1. data — The location of the data file.
2. output — Where to write the tsv solution to
Therefore, the program should be able to start like this:
python3 perceptron.py --data data.tsv --output solution.tsv
The program consists of 8 parts and we are going to have a look at them one at a time.
import argparse # to read inputs from command lineimport csv # to read and process datasetimport numpy as np # to perform mathematical functions
# initialise argument parser and read arguments from command line with the respective flags and then call the main() functionif __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-d", "--data", help="Data File") parser.add_argument("-o", "--output", help="output") main()
The flow of the main() function is as follows:
Save respective command line inputs into variablesSet starting learningRate = 1Read the dataset using csv and delimiter='\t', store independent variables in X and dependent variable in Y. We are adding 1.0 as bias to our independent dataThe independent and dependent data is converted to floatThe weight vector is initialised with zeroes with same dimensions as XThe normalError and annealError are calculated by calling their respective methodsFinally, the output is saved into a tsv file
Save respective command line inputs into variables
Set starting learningRate = 1
Read the dataset using csv and delimiter='\t', store independent variables in X and dependent variable in Y. We are adding 1.0 as bias to our independent data
The independent and dependent data is converted to float
The weight vector is initialised with zeroes with same dimensions as X
The normalError and annealError are calculated by calling their respective methods
Finally, the output is saved into a tsv file
The flow of calculateNormalBatchLearning() is as follows:
Initialisation of a variable e to store the error countA loop is run for 100 iterationsPredicted value is computed based on the perceptron rule described earlier using calculatePredicatedValue() methodError count is calculated using the calculateError() methodWeights are updated based on the equation above using calculateGradient() method
Initialisation of a variable e to store the error count
A loop is run for 100 iterations
Predicted value is computed based on the perceptron rule described earlier using calculatePredicatedValue() method
Error count is calculated using the calculateError() method
Weights are updated based on the equation above using calculateGradient() method
The flow of calculateNormalBatchLearning() is as follows:
Initialisation of a variable e to store the error countA loop is run for 100 iterationsPredicted value is computed based on the perceptron rule described earlier using calculatePredicatedValue() methodError count is calculated using the calculateError() methodLearning rate is divided by the number of the iterationWeights are updated based on the equation above using calculateGradient() method
Initialisation of a variable e to store the error count
A loop is run for 100 iterations
Predicted value is computed based on the perceptron rule described earlier using calculatePredicatedValue() method
Error count is calculated using the calculateError() method
Learning rate is divided by the number of the iteration
Weights are updated based on the equation above using calculateGradient() method
As described in the perceptron image, if the linear combination of W and X is greater than 0, then we predict the class as 1 otherwise 0.
We count the number of instances where the predicted value and the true value do not match and this becomes our error count.
This method is translation of the weight update formula mentioned above.
I am giving away a free eBook on Consistency. Get your free eBook here.
Now, that the whole code is out there. Let’s have a look at the execution of the program.
Here is how the output looks like:
The final program
If you enjoy reading stories like these and want to support me as a writer, consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to stories on Medium. If you sign up using my link, I’ll earn a small commission at no extra cost to you.
tarun-gupta.medium.com
Here is an index of my stories:
|
[
{
"code": null,
"e": 396,
"s": 172,
"text": "In this post, we are going to have a look at a program written in Python3 using numpy. We will discuss the basics of what a perceptron is, what is the delta rule and how to use it to converge the learning of the perceptron."
},
{
"code": null,
"e": 767,
"s": 396,
"text": "The perceptron is an algorithm for supervised learning of binary classifiers (let’s assumer {1, 0}). We have a linear combination of weight vector and the input data vector that is passed through an activation function and then compared to a threshold value. If the linear combination is greater than the threshold, we predict the class as 1 otherwise 0. Mathematically,"
},
{
"code": null,
"e": 939,
"s": 767,
"text": "Perceptrons only represent linearly separable problems. They fail to converge if the training examples are not linearly separable. This brings into picture the delta rule."
},
{
"code": null,
"e": 1123,
"s": 939,
"text": "The delta rule converges towards a best-fit approximation of the target concept. The key idea is to use gradient descent to search the hypothesis space of all possible weight vectors."
},
{
"code": null,
"e": 1186,
"s": 1123,
"text": "Note: This provides the basis for “Backpropogation” algorithm."
},
{
"code": null,
"e": 1655,
"s": 1186,
"text": "Now, let’s discuss the problem at hand. The program will read a dataset(tab separated file) and treat the first column as the target concept. The values present in the target concept are A and B, we will consider A as +ve class or 1 and B as -ve class or 0. The program implements the perceptron training rule in batch mode with a constant learning rate and an annealing(decreasing as the number of iterations increase) learning rate, starting with learning rate as 1."
},
{
"code": null,
"e": 2027,
"s": 1655,
"text": "where Y(x, w) is the set of samples which are misclassified. We will use the count or the number of misclassified points as our error rate(i.e. | Y(x, w)|). The output will also be a tab separated(tsv) file containing the error for each iteration, i.e. it will have 100 columns. Also, it will have 2 rows, one for normal learning rate and one for annealing learning rate."
},
{
"code": null,
"e": 2168,
"s": 2027,
"text": "Now, the understanding of what perceptron is, what delta rule and how we are going to use it. Let’s get started with Python3 implementation."
},
{
"code": null,
"e": 2245,
"s": 2168,
"text": "In the program, we are providing two inputs from the command line. They are:"
},
{
"code": null,
"e": 2286,
"s": 2245,
"text": "1. data — The location of the data file."
},
{
"code": null,
"e": 2333,
"s": 2286,
"text": "2. output — Where to write the tsv solution to"
},
{
"code": null,
"e": 2391,
"s": 2333,
"text": "Therefore, the program should be able to start like this:"
},
{
"code": null,
"e": 2451,
"s": 2391,
"text": "python3 perceptron.py --data data.tsv --output solution.tsv"
},
{
"code": null,
"e": 2538,
"s": 2451,
"text": "The program consists of 8 parts and we are going to have a look at them one at a time."
},
{
"code": null,
"e": 2683,
"s": 2538,
"text": "import argparse # to read inputs from command lineimport csv # to read and process datasetimport numpy as np # to perform mathematical functions"
},
{
"code": null,
"e": 3016,
"s": 2683,
"text": "# initialise argument parser and read arguments from command line with the respective flags and then call the main() functionif __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument(\"-d\", \"--data\", help=\"Data File\") parser.add_argument(\"-o\", \"--output\", help=\"output\") main()"
},
{
"code": null,
"e": 3063,
"s": 3016,
"text": "The flow of the main() function is as follows:"
},
{
"code": null,
"e": 3553,
"s": 3063,
"text": "Save respective command line inputs into variablesSet starting learningRate = 1Read the dataset using csv and delimiter='\\t', store independent variables in X and dependent variable in Y. We are adding 1.0 as bias to our independent dataThe independent and dependent data is converted to floatThe weight vector is initialised with zeroes with same dimensions as XThe normalError and annealError are calculated by calling their respective methodsFinally, the output is saved into a tsv file"
},
{
"code": null,
"e": 3604,
"s": 3553,
"text": "Save respective command line inputs into variables"
},
{
"code": null,
"e": 3634,
"s": 3604,
"text": "Set starting learningRate = 1"
},
{
"code": null,
"e": 3793,
"s": 3634,
"text": "Read the dataset using csv and delimiter='\\t', store independent variables in X and dependent variable in Y. We are adding 1.0 as bias to our independent data"
},
{
"code": null,
"e": 3850,
"s": 3793,
"text": "The independent and dependent data is converted to float"
},
{
"code": null,
"e": 3921,
"s": 3850,
"text": "The weight vector is initialised with zeroes with same dimensions as X"
},
{
"code": null,
"e": 4004,
"s": 3921,
"text": "The normalError and annealError are calculated by calling their respective methods"
},
{
"code": null,
"e": 4049,
"s": 4004,
"text": "Finally, the output is saved into a tsv file"
},
{
"code": null,
"e": 4107,
"s": 4049,
"text": "The flow of calculateNormalBatchLearning() is as follows:"
},
{
"code": null,
"e": 4448,
"s": 4107,
"text": "Initialisation of a variable e to store the error countA loop is run for 100 iterationsPredicted value is computed based on the perceptron rule described earlier using calculatePredicatedValue() methodError count is calculated using the calculateError() methodWeights are updated based on the equation above using calculateGradient() method"
},
{
"code": null,
"e": 4504,
"s": 4448,
"text": "Initialisation of a variable e to store the error count"
},
{
"code": null,
"e": 4537,
"s": 4504,
"text": "A loop is run for 100 iterations"
},
{
"code": null,
"e": 4652,
"s": 4537,
"text": "Predicted value is computed based on the perceptron rule described earlier using calculatePredicatedValue() method"
},
{
"code": null,
"e": 4712,
"s": 4652,
"text": "Error count is calculated using the calculateError() method"
},
{
"code": null,
"e": 4793,
"s": 4712,
"text": "Weights are updated based on the equation above using calculateGradient() method"
},
{
"code": null,
"e": 4851,
"s": 4793,
"text": "The flow of calculateNormalBatchLearning() is as follows:"
},
{
"code": null,
"e": 5247,
"s": 4851,
"text": "Initialisation of a variable e to store the error countA loop is run for 100 iterationsPredicted value is computed based on the perceptron rule described earlier using calculatePredicatedValue() methodError count is calculated using the calculateError() methodLearning rate is divided by the number of the iterationWeights are updated based on the equation above using calculateGradient() method"
},
{
"code": null,
"e": 5303,
"s": 5247,
"text": "Initialisation of a variable e to store the error count"
},
{
"code": null,
"e": 5336,
"s": 5303,
"text": "A loop is run for 100 iterations"
},
{
"code": null,
"e": 5451,
"s": 5336,
"text": "Predicted value is computed based on the perceptron rule described earlier using calculatePredicatedValue() method"
},
{
"code": null,
"e": 5511,
"s": 5451,
"text": "Error count is calculated using the calculateError() method"
},
{
"code": null,
"e": 5567,
"s": 5511,
"text": "Learning rate is divided by the number of the iteration"
},
{
"code": null,
"e": 5648,
"s": 5567,
"text": "Weights are updated based on the equation above using calculateGradient() method"
},
{
"code": null,
"e": 5786,
"s": 5648,
"text": "As described in the perceptron image, if the linear combination of W and X is greater than 0, then we predict the class as 1 otherwise 0."
},
{
"code": null,
"e": 5911,
"s": 5786,
"text": "We count the number of instances where the predicted value and the true value do not match and this becomes our error count."
},
{
"code": null,
"e": 5984,
"s": 5911,
"text": "This method is translation of the weight update formula mentioned above."
},
{
"code": null,
"e": 6056,
"s": 5984,
"text": "I am giving away a free eBook on Consistency. Get your free eBook here."
},
{
"code": null,
"e": 6146,
"s": 6056,
"text": "Now, that the whole code is out there. Let’s have a look at the execution of the program."
},
{
"code": null,
"e": 6181,
"s": 6146,
"text": "Here is how the output looks like:"
},
{
"code": null,
"e": 6199,
"s": 6181,
"text": "The final program"
},
{
"code": null,
"e": 6473,
"s": 6199,
"text": "If you enjoy reading stories like these and want to support me as a writer, consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to stories on Medium. If you sign up using my link, I’ll earn a small commission at no extra cost to you."
},
{
"code": null,
"e": 6496,
"s": 6473,
"text": "tarun-gupta.medium.com"
}
] |
Converting numbers to Indian currency using JavaScript
|
Suppose we have any number and are required to write a JavaScript function that takes in a number and returns its Indian currency equivalent.
toCurrency(1000) --> ₹4,000.00
toCurrency(129943) --> ₹1,49,419.00
toCurrency(76768798) --> ₹9,23,41,894.00
The code for this will be −
const num1 = 1000;
const num2 = 129943;
const num3 = 76768798;
const toIndianCurrency = (num) => {
const curr = num.toLocaleString('en-IN', {
style: 'currency',
currency: 'INR'
});
return curr;
};
console.log(toIndianCurrency(num1));
console.log(toIndianCurrency(num2));
console.log(toIndianCurrency(num3));
And the output in the console will be −
₹1,000.00
₹1,29,943.00
₹7,67,68,798.00
|
[
{
"code": null,
"e": 1204,
"s": 1062,
"text": "Suppose we have any number and are required to write a JavaScript function that takes in a number and returns its Indian currency equivalent."
},
{
"code": null,
"e": 1312,
"s": 1204,
"text": "toCurrency(1000) --> ₹4,000.00\ntoCurrency(129943) --> ₹1,49,419.00\ntoCurrency(76768798) --> ₹9,23,41,894.00"
},
{
"code": null,
"e": 1340,
"s": 1312,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1666,
"s": 1340,
"text": "const num1 = 1000;\nconst num2 = 129943;\nconst num3 = 76768798;\nconst toIndianCurrency = (num) => {\n const curr = num.toLocaleString('en-IN', {\n style: 'currency',\n currency: 'INR'\n });\nreturn curr;\n};\nconsole.log(toIndianCurrency(num1));\nconsole.log(toIndianCurrency(num2));\nconsole.log(toIndianCurrency(num3));"
},
{
"code": null,
"e": 1706,
"s": 1666,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 1745,
"s": 1706,
"text": "₹1,000.00\n₹1,29,943.00\n₹7,67,68,798.00"
}
] |
Variable Scope in C++
|
A scope is a region of the program and broadly speaking there are three places, where variables can be declared −
Inside a function or a block which is called local variables,
Inside a function or a block which is called local variables,
In the definition of function parameters which is called formal parameters.
In the definition of function parameters which is called formal parameters.
Outside of all functions which is called global variables.
Outside of all functions which is called global variables.
We will learn what is a function and it's parameter in subsequent chapters. Here let us explain what are local and global variables.
Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. Following is the example using local variables −
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables −
#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int main () {
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
A program can have same name for local and global variables but value of local variable inside a function will take preference. For example −
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main () {
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
When the above code is compiled and executed, it produces the following result −
10
When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows −
It is a good programming practice to initialize variables properly, otherwise sometimes program would produce unexpected result.
154 Lectures
11.5 hours
Arnab Chakraborty
14 Lectures
57 mins
Kaushik Roy Chowdhury
30 Lectures
12.5 hours
Frahaan Hussain
54 Lectures
3.5 hours
Frahaan Hussain
77 Lectures
5.5 hours
Frahaan Hussain
12 Lectures
3.5 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2432,
"s": 2318,
"text": "A scope is a region of the program and broadly speaking there are three places, where variables can be declared −"
},
{
"code": null,
"e": 2494,
"s": 2432,
"text": "Inside a function or a block which is called local variables,"
},
{
"code": null,
"e": 2556,
"s": 2494,
"text": "Inside a function or a block which is called local variables,"
},
{
"code": null,
"e": 2632,
"s": 2556,
"text": "In the definition of function parameters which is called formal parameters."
},
{
"code": null,
"e": 2708,
"s": 2632,
"text": "In the definition of function parameters which is called formal parameters."
},
{
"code": null,
"e": 2767,
"s": 2708,
"text": "Outside of all functions which is called global variables."
},
{
"code": null,
"e": 2826,
"s": 2767,
"text": "Outside of all functions which is called global variables."
},
{
"code": null,
"e": 2959,
"s": 2826,
"text": "We will learn what is a function and it's parameter in subsequent chapters. Here let us explain what are local and global variables."
},
{
"code": null,
"e": 3230,
"s": 2959,
"text": "Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. Following is the example using local variables −"
},
{
"code": null,
"e": 3443,
"s": 3230,
"text": "#include <iostream>\nusing namespace std;\n \nint main () {\n // Local variable declaration:\n int a, b;\n int c;\n \n // actual initialization\n a = 10;\n b = 20;\n c = a + b;\n \n cout << c;\n \n return 0;\n}"
},
{
"code": null,
"e": 3618,
"s": 3443,
"text": "Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the life-time of your program."
},
{
"code": null,
"e": 3831,
"s": 3618,
"text": "A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables −"
},
{
"code": null,
"e": 4076,
"s": 3831,
"text": "#include <iostream>\nusing namespace std;\n \n// Global variable declaration:\nint g;\n \nint main () {\n // Local variable declaration:\n int a, b;\n \n // actual initialization\n a = 10;\n b = 20;\n g = a + b;\n \n cout << g;\n \n return 0;\n}"
},
{
"code": null,
"e": 4218,
"s": 4076,
"text": "A program can have same name for local and global variables but value of local variable inside a function will take preference. For example −"
},
{
"code": null,
"e": 4403,
"s": 4218,
"text": "#include <iostream>\nusing namespace std;\n \n// Global variable declaration:\nint g = 20;\n \nint main () {\n // Local variable declaration:\n int g = 10;\n \n cout << g;\n \n return 0;\n}"
},
{
"code": null,
"e": 4484,
"s": 4403,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4488,
"s": 4484,
"text": "10\n"
},
{
"code": null,
"e": 4687,
"s": 4488,
"text": "When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows −"
},
{
"code": null,
"e": 4816,
"s": 4687,
"text": "It is a good programming practice to initialize variables properly, otherwise sometimes program would produce unexpected result."
},
{
"code": null,
"e": 4853,
"s": 4816,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 4872,
"s": 4853,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4904,
"s": 4872,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 4927,
"s": 4904,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 4963,
"s": 4927,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 4980,
"s": 4963,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5015,
"s": 4980,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5032,
"s": 5015,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5067,
"s": 5032,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5084,
"s": 5067,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5119,
"s": 5084,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5136,
"s": 5119,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5143,
"s": 5136,
"text": " Print"
},
{
"code": null,
"e": 5154,
"s": 5143,
"text": " Add Notes"
}
] |
Citi Bike 2017 Analysis. The goal of this analysis is to create... | by Vinit Shah | Towards Data Science
|
The goal of this analysis is to create an operating report of Citi Bike for the year of 2017. The following work was completed in less than five working days. Under each visual, I’ve added my thoughts on what I would consider if there was no time constraint. The Citi Bike analysis is based on the mock case shown below:
Overview: Your client, The Mayor of New York City, needs a better understanding of Citi Bike ridership. He wants an Operating Report for the Year of 2017 on his desk by the end of the week. Based on previous engagements we know the mayor is a big fan of visualizing data in charts. Specifically, the Mayor wants to see a variety of data visualizations to understand
Top 5 stations with the most starts (showing # of starts)
Trip duration by user type
Most popular trips based on start station and stop station)
Rider performance by Gender and Age based on avg trip distance (station to station), median speed (trip duration / distance traveled)
What is the busiest bike in NYC in 2017? How many times was it used? How many minutes was it in use?
Additionally, the Mayor has an idea that he wants to pitch to Citi Bike and needs your help proving its feasibility. He would like Citi Bike to add a new feature to their kiosks: “Enter a destination and we’ll tell you how long the trip will take”. We need you to build a model that can predict how long a trip will take given a starting point and destination.
Client: Mayor of New York City, Bill de BlasioObjective: Help the mayor get a better understanding of Citi Bike ridership by creating an operating report for 2017 (NYC only).
Ask:
Top 5 stations with the most starts (showing # of starts)Trip duration by user typeMost popular trips (based on start station and stop station)Rider performance by Gender and Age based on avg. trip distance (station to station), median speed (trip duration /distance traveled)What is the busiest bike in NYC in 2017? How many times was it used? How many minutes was it in use?A model that can predict how long a trip will take given a starting point and destination (Do not use the Google Maps API).
Top 5 stations with the most starts (showing # of starts)
Trip duration by user type
Most popular trips (based on start station and stop station)
Rider performance by Gender and Age based on avg. trip distance (station to station), median speed (trip duration /distance traveled)
What is the busiest bike in NYC in 2017? How many times was it used? How many minutes was it in use?
A model that can predict how long a trip will take given a starting point and destination (Do not use the Google Maps API).
The data was sourced from the Citi Bike’s amazon server which can be accessed here. The code used for this article can be found here.*
First let’s minimize the work and load in the data set from the server. It’s clear that these files are massive, a few hundred MBs each.
!curl -O "https://s3.amazonaws.com/tripdata/2017[01-12]-citibike-tripdata.csv.zip"!unzip '*.zip'!rm *.zipfiles = !ls *.csv #For Ipython onlydf = concat([read_csv(f, header=None,low_memory=False) for f in files], keys=files)
The column names have spaces in them, would be great to remove them for working purposes. If I was working on a team or a long term project, I would configure column names a little bit differently to make them easier to work with. However, I’ve kept the names simple and easy to understand for the purposes of this article.
The dataset is massive, ~16mil rows. BigData tools would be helpful, however, most require you to pay or have an enterprise license or a limited trial. Additionally, the data is very dirty. Different files have different column names, need to account for this. Mayor de Blasio doesn’t have a technical background. The graphs here are as simple yet informative as possible. I could’ve made more complicated plots, however, they would not be as informative for the mayor. The graphs are designed with the user in mind.
Lastly, my analysis tries best to follow the crisp-dm methodology outlined below.
Let’s understand the data we’re working with and give a brief overview of what each feature represents or should represent.
1. Trip Duration (seconds) — How long a trip lasted2. Start Time and Date - Self explanatory3. Stop Time and Date - Self explanatory4. Start Station Name - Self explanatory5. End Station Name - Self explanatory6. Station ID - Unique identifier for each station7. Station Lat/Long - Coordinates8. Bike ID - unique identifier for each bike9. User Type (Customer = 24-hour pass or 3-day pass user; Subscriber = Annual Member) - Customers are usually tourists, subscribers are usually NYC residents10. Gender (Zero=unknown; 1=male; 2=female) - Usually unknown for customers since they often sign up at a kiosk11. Year of Birth - Self entered, not validated by an ID.
Let’s check if there’s any noise or cleanup which needs to be done before creating the chart.
Any missing values?
Any missing values?
Mostly for Birth year
Few for User Type.
Citi Bike customers (1-day pass or 3-day pass) are often tourists and may not put in their birth year in a rush or due to other reasons
Citi Bike subscribers tend to be NYC residents, by blindly dropping rows with missing values, we’ll be losing critical information and may introduce bias.
2. Let’s get a description of the data we’re working with:
3. Citi Bike riders often come across broken bikes. As a user, I am quite familiar with the dilemma. Let’s drop any trips where a trip lasted less than 90 seconds and the start station == end station. 90 seconds is an arbitrary choice based on how long it would take a rider to realize a bike isn’t working properly and coming back to the station to return it and take a new on. Another measure which can be used is 372 seconds (25% quartile). This is based on the assumption that if someone is making a round trip, it most likely is to perform some quick task which is not close enough to walk to, thus this trip should be at least a little bit longer than the shortest trip.In case it was a short trip, let’s add the extra and condition to make sure the start and end station names are the same.
4. Anomalies such as theft and broken docks shouldn’t matter for this metric and can be dealt with later.
Next Steps and Business Use Case: Would be interesting to visualize these stations on a map to see how close they are to each other. This could be used to determine which areas require additional stations or bikes.
This question is a bit unclear in terms of what to do with the anomalies, so I’ll be making two graphs. One with anomalies, one without.
There are NA values in the dataset for usertype as can be seen from missing table image above. Since it’s only 0.09% of the data, it can be considered safe to remove.
According to Citi Bikes’ website: The first 45 minutes of each ride is included for Annual Members, and the first 30 minutes of each ride is included for Day Pass users. If you want to keep a bike out for longer, it’s only an extra $4 for each additional 15 minutes.
It’s safe to assume, no one (or very few people) will be willing to rent a bike for more than 2 hours, especially a clunky citibike. If they did, it would cost them an additional $20 assuming they’re annual subscribers. It would be more economical for them to buy a bike if they want that workout or use one of the tour bikes in central park if they want to tour and explore the city on a bike. There may be a better way to choose an optimal cutoff, however, time is key in a client project. Or just docing and getting another bike. The real cost of a bike is accrued ~24 hours.
Anomalies: Any trip which lasts longer than 2 hours (7,200 seconds) probably indicates a stolen bike, an anomaly, or incorrect docking of the bike. As an avid Citi Bike user, I know first hand that it doesn’t make any sense for one to use a bike for more than one hour! However, I’ve added a one hour cushion just in case. No rider would plan to go over the maximum 45 minutes allowed. However, I plan to reduce this to one hour in the future for modeling purposes.
First Half- with anomalies in dataset
First Half- with anomalies in dataset
The bargraph of average trip duration for each user type. It’s helpful, but would be better to see a box-plot or violin plot. Would be easier to interpret in minutes.
Second graph is a basic violin plot based with anomalies included. As we can see, there is too much noise for this to be useful. It’ll be better to look at this without anomalies.
2. Second Half — without anomalies in dataset
A much more informative graph about trip duration based on user type with anomalies defined as mentioned above. “Fliers” have been removed from the graph below.
Bar-graph highlighting average duration of each trip based on user type
It’s safe to say that user type will be a strong predictor of trip duration. It’s a point to note for now and we can come back to this later on.
Next Steps & Business Use Case: Customers are allowed 30 min per bike while subscribers are allowed 45 minutes per bike. Data clearly indicates that customers tend to use bikes longer. If the main concern is to have bikes available at docks, then the current time limit makes sense. However, if Citi Bike would like to be user-centric, giving customers more time per bike is worth exploring.
To get most popular trips, the most convenient way to do this is by using the groupby function in pandas. It’s analogous to a Pivot table.
trips_df = df.groupby([‘Start Station Name’,’End Station Name’]).size().reset_index(name = ‘Number of Trips’)
The groupby function makes it extremely easy and convenient to identify the most popular trips.
Next Steps & Business Use Case: Would be interesting to see this on a map to see if riders are traveling from North to South, East to West, etc. Additionally, it would be good to see most popular trips based on the time of day. This can help Citi Bike determine where to keep bikes and where to have docks available based on the time of day. The assumption being riders travel in one direction to work in the morning and in the opposite direction to get home in the evening.
Ask: Rider performance by Gender and Age based on avg trip distance (station to station), median speed (trip duration/distance traveled)
Let’s make sure the data we’re working with here is clean.
Missing Gender and Birth Year values? — Check missing_table above
Missing Gender and Birth Year values? — Check missing_table above
No for Gender. Yes for Birth Year
~10% Missing Birth year. Not a big chunk of data. Can either impute missing values or drop it. Since it’s less than 10% of the data, it’s safe to assume the rest of the 90% is a representative sample of data and we can replace the birth year with the median, based on gender and Start Station ID. I chose this method because most people the same age live in similar neighborhoods (i.e: young people in east village, older people in Upper East Side, etc.). This will be done after anomalies are removed and speed is calculated. There may be better ways to impute this data, please share your thoughts in the comments section below.
df['Birth Year'] = df.groupby(['Gender','Start Station ID'])['Birth Year'].transform(lambda x: x.fillna(x.median()))
2. Are there anomalies?
For Birth Year, there are some people born prior to 1960. I can believe some 60 year olds can ride a bike and that’s a stretch, however, anyone “born” prior to that riding a Citi Bike is an anomaly and false data. There could be a few senior citizens riding a bike, but probably not likely.
My approach is to identify the age 2 standard deviations lower than the mean. After calculating this number, mean - 2stdev, I removed the tail end of the data, birth year prior to 1956.
df = df.drop(df.index[(df['Birth Year'] < df['Birth Year'].mean()-(2*df['Birth Year'].std()))])
3. Calculate an Age column to make visuals easier to interpret:
df['Age'] = 2018 - df['Birth Year'];df['Age'] = df['Age'].astype(int);
4. Calculate trip distance (Miles)
No reliable way to calculate bike route since we can’t know what route a rider took without GPS data from each bike.
Could use Google maps and use lat, long coordinates to find bike route distance. However, this would require more than the daily limit on API calls. Use the geopy.distance package which uses Vincenty distance uses more accurate ellipsoidal models. This is more accurate than Haversine formula, but doesn’t matter much for our purposes since the curvature of the earth has a negligible effect on the distance for bike trips in NYC.
In the future, for a dataset of this size, I would consider using the Haversine formula to calculate distance if it's faster. The code below takes too long to run on a dataset of this size.
dist = []for i in range(len(df)): dist.append(geopy.distance.vincenty(df.iloc[i]['Start Coordinates'],df.iloc[i]['End Coordinates']).miles) if (i%1000000==0): print(i)
5. Calculate Speed (min/mile) and (mile/hr)
(min/mile): Can be used like sprint time (how fast does this person run)
df['min_mile'] = round(df['Minutes']/df['Distance'], 2)
(mile/hr): Conventional approach. Miles/hour is an easy to understand unit of measure and one most people are used to seeing. So the visual will be created based on this understanding.
df['mile_hour'] = round(df['Distance']/(df['Minutes']/60),2)
6. Dealing with “circular” trips
Circular trips are trips which start and end at the same station. The distance for these trips will come out to 0, however, that is not the case. These points will skew the data and visuals. Will be removing them to account for this issue.
For the model, this data is also irrelevant. Because if someone is going on a circular trip, the only person who knows how long the trip is going to take is the rider, assuming s/he knows that. So it’s safe to drop this data for the model.
df = df.drop(df.index[(df['Distance'] == 0)])
7. We have some Start Coordinates as (0.0,0.0). These are trips which were taken away for repair or for other purposes. These should be dropped. If kept, the distance for these trips is 5,389 miles. For this reason I’ve dropped any points where the distance is outrageously large. Additionally, we have some missing values. Since it’s a tiny portion, let’s replace missing values based on Gender and start location.
On some trips, the speed of the biker is more than 200 mph. This could be due to the formula used for distance calculation or some other error. The fastest cyclist in the world on a flat surface ever recorded biked at 82mph. It’s safe to assume none of the Citi Bike riders can approach this speed. Due to this and the fact that an average cyclist speed is 10mph, I’ve decided to remove all data where the speed in mph is greater than 20 mph and less than 2 stdev from the mean, because that’s probably a roundtrip where the biker found the dock was full and used another dock instead.
8. Rider performance by age and gender in miles/hour, after data cleaning
9. Rider performance by age and gender in average distance in miles
Next Steps & Business Use Case: Worth exploring the number of trips based on gender and age. This could help create different customer baskets based on bike usage. If working folks use Citi Bike more often they could be charged a higher rate. If senior citizens are using Citi Bike, they should be rewarded for staying fit and active. This information could be communicated to their insurers to reward them for taking care of their health.
Ask:
What is the busiest bike in NYC in 2017?How many times was it used?How many minutes was it in use?
What is the busiest bike in NYC in 2017?
How many times was it used?
How many minutes was it in use?
Busiest bike and count can be identified by a groupby function. Function below will also identify the number of times the bike was used
bike_use_df = df.groupby(['Bike ID']).size().reset_index(name = 'Number of Times Used');bike_use_df = bike_use_df.sort_values('Number of Times Used', ascending = False);
A similar groupby function which calls for the sum on minutes can identify the number of minutes the bike was used.
bike_min_df['Minutes Used'] = df.groupby('Bike ID')['Minutes'].sum()bike_min_df = bike_min_df.sort_values('Minutes Used', ascending = False)
Next Steps & Business Use Case: If combined with Citi Bike maintenance data, this information can be used to identify when a bike will need maintenance and repairs. This can help decrease the problem of broken bikes taking up docks at stations, which is an issue lots of riders face. This information can also be used to build a brand and for marketing purposes. It would be neat to have a “Citi Bike of the Year”, the most used bike advertised publicly as a symbol to increase bike use in NYC.
Ask: Build a model that can predict how long a trip will take given a starting point and destination.
Assumptions on how the Kiosk will work: Let’s assume that when a user inputs the start and end station, they swipe their key fob (if they’re a subscriber) and enter their info on the kiosk (if they’re a “Customer”) prior to entering the start and end station. This means that we would know their gender and age. Thus these variables can be used in building the model.
Step 1.
This dataset is massive. Almost 14 million rows. Let’s work on a random subsample while we build and evaluate models. If I tried to build and evaluate a model on the entire dataset, each run would take me ~10+ minutes depending on the model. One good way to decide what portion of your data to work with is using a learning curve. However, my kernel keeps crashing while trying to create that learning curve. If we were working with data for multiple years, we would need to reconsider this approach. However, given the reasons above, let’s sample 10% of the data. It’s still ~1.3 million rows and should be a representative sample since it’s randomly selected. To ensure that it’s a representative sample, we should look at the description of the original dataset and the sample dataset. Lastly, we can make sure the data is representative by making the the visuals above are the similar for the random sample. 10% of the data passes the test above.
Additionally, Citi Bike trips are capped at 45 minutes for subscribers and 30 minutes for customers (refer to “According to Citi Bike’s website” above). After these respective time limits, the riders incur a fee. To model our data, it does not make sense to include trips which last longer than the prescribed 45 minutes. Rider’s don’t often plan to go over the allocated time and there’s no clear way of knowing who plans to go over the allocated time. It’s a question worth exploring, however, the data is noise for our model.
df = df.drop(df.index[(df['Trip Duration'] > 2700)])df_sample = df.sample(frac = 0.1, random_state = 0)
Step 2.
Let’s get a baseline. If I were to just run a simple multi-variate linear regression, what would my model look like and how accurate would it be? Need to prepare the data for a multivariate regression
Drop irrelevant columns
Drop irrelevant columns
Trip Duration: We have the minutes column, which is the target variable
Stop Time: In the real world, we won’t have this information when predicting the trip duration.
Start Station ID: Start Station Name captures this information
Start Station Latitude: Start Station Name captures this information
Start Station Longitude: Start Station Name captures this information
Start Coordinates: Start Station Name captures this information
End Station ID: End Station Name captures this information
End Station Latitude: End Station Name captures this information
End Station Longitude: End Station Name captures this information
End Coordinates: End Station Name captures this information
Bike Id: We won’t know what bike the user is going to end up using
Birth Year: Age captures this information
min_mile: Effectively the same information as end time when combined with distance. We won’t have this information in the real world.
mile_hour: Effectively the same information as end time when combined with distance. We won’t have this information in the real world.
(Speed * Distance = Trip Duration): Which is why speed is dropped
Start Station Name and End Station Name: The distance variable captures the same information. For the model, if a user is inputting start and end station, we can build a simple function to calculate the distance which would capture the same information. One may argue to keep this information since this is the information which will be provided at the kiosk. However, given that there are over 800 stations, if we keep this information, we are required to encode this for any regression algorithm. This would create 800 features (~15 million rows) leading to lots of data, without much, if any, information gain.
After the cleaning mentioned above, the final predictors used for the baseline model are Distance, User Type, and Gender. Age seems to have no impact as can be seen by the visuals in part 4. To confirm this, I ran the model with and without age. Age had little to no impact on the model.
I chose to run a linear regression. The size of the data and limitation of resources made running more complex models less attractive. Ensemble algorithms were tested, but took too long to run.
The model is pretty good for a baseline model with an R2 and Adjusted R2 of 0.774. Distance seems to be having a large impact on trip duration, which makes sense.
Steps to make improvements:
1. Add back time in the following format
Is the ride on a weekday or weekend. Weekday, is rush-hour commute for the most part and probably from home to work. Weekend could be a longer, more casual ride and have higher variability.
Is the ride in the morning, afternoon, evening, or night. The exact timing will be based on the difference in trip duration based on time of day. Will have visuals below.
2. What season is it?
December — Feb. = Winter
March — May = Spring
June — Aug. = Summer
Sept. — Nov. = Fall
def get_date_info(df): df['d_week'] = df['Start Time'].dt.dayofweek df['m_yr'] = df['Start Time'].dt.month df['ToD'] = df['Start Time'].dt.hour df['d_week'] = (df['d_week']<5).astype(int) df['m_yr'] = df['m_yr'].replace(to_replace=[12,1,2], value = 0) df['m_yr'] = df['m_yr'].replace(to_replace=[3,4,5], value = 1) df['m_yr'] = df['m_yr'].replace(to_replace=[6,7,8], value = 2) df['m_yr'] = df['m_yr'].replace(to_replace=[9,10,11], value = 3) df['ToD'] = pd.cut(df['ToD'], bins=[-1, 5, 9, 14, 20, 25], labels=['Night','Morning','Afternoon','Evening','Night1']) df['ToD'] = df['ToD'].replace(to_replace='Night1', value = 'Night') df['ToD'] = df['ToD'].cat.remove_unused_categories() df['m_yr'] = df['m_yr'].astype('category') df['d_week'] = df['d_week'].astype('category')return(df)
Model 1: Negligible improvement in R2: 77.7% (depending on random_state used)
Safe to assume that we can drop these variables as they don’t have a major impact.
It’s a bit surprising that the weekday variable has little to no impact since people most likely bike for leisure on weekends rather than for work. This could be explained by obtaining a breakdown of riders. Maybe a lot of Citi Bike users are college students.
Another possibility is that the effect of this feature is being skewed by the fact that there are both customers and subscribers in this dataset and the effect of this feature on both variables is different. However, there’s no clear explanation for now. It’s worth considering building a separate model for subscribers and customers since their behavior is so drastically different as seen in part 2.
Next steps will be to factor in speed and distance based on Gender and Trip. By not being able to encode start and end stations (due to the sheer number of points), we are losing crucial information on the trip itself. We need another proxy for those measures.
Another change I could make is to bin age into buckets. However, the data indicates that age has no correlation or effect on the trip duration. This is counter-intuitive, however, I don’t have a good reason to refute the data.
Include Average Speed based on: Trip (Start + End Station) and User Type.
Include Average Speed based on: Trip (Start + End Station) and User Type.
Reason for Trip: Some trips are up hill, others are down hill. Some routes, such as one through times square involve heavy traffic, based on intuition.
Reason for User Type: Tourists (Customers), will usually ride more slowly with frequent stops than a Subscriber, according to the data.
2. Include average duration for each trip based on: Trip and User Type for reasons mentioned above
def get_speed_distance(df): df['Start Station Name'] = df['Start Station Name'].astype(str) df['End Station Name'] = df['End Station Name'].astype(str) df['Trip'] = df['Start Station Name'] + ' to ' + df['End Station Name'] df['Trip'] = df['Trip'].astype('category') df['avg_speed'] = df.groupby(['Trip','User Type'])['mile_hour'].transform('mean') df['avg_duration'] = df.groupby(['Trip','User Type'])['Trip Duration'].transform('median') return df
The model is significantly better. But can it be even better?
One factor which would have a significant impact on trip duration is traffic. However, since we do not know what route the rider took it’s difficult to incorporate this information. Lastly, the Google Maps API caps usage, so we can’t use it to identify traffic patterns easily.
One factor which a lot of people think may be a good predictor of trip duration is weather. I personally disagree. Weather influences wether or not a user will bike, not how long they will bike. If it’s snowing, I won’t bike to work. If it’s nice, I will bike to work. Regardless of my opinion, I am going to test this hypothesis. If weather is not a strong indicator, I will remove it in the next model.
The weather data was acquired from the National Centers for Environmental Information. The data sourced from the website is a daily summary. The attributes include: high temperature (F), low temperature (F), and precipitation (inches).
def get_weather(df): df['DATE'] = to_datetime(df['Start Time'].dt.date) df = df.merge(df_weather, on = 'DATE', how = 'left') return df
Little to no improvement in the model. Weather has little to no impact.
The coefficient for avg_duration spiked up. Not sure why, but the higher coefficient makes sense since duration is our target variable, and avg_duration is a solid proxy (anchor) for how long a trip most likely takes.
Let’s confirm the effectiveness of the model with cross validation:
CV accuracy: 0.874 +/- 0.001
Based on some of the observations above I ran the same model above without weather and date information as predictors.
As we can see, there’s a very small decrease in R2. Another interesting observation is the effect of this data on the coefficient of user type, it’s almost halved.
The effect on the random sample is small, however, with 10 times the amount of data, the effect could be slightly larger, so for the final model, let’s keep the date information.
Lastly, I chose to test other regression algorithms such as random forests to see if another regressor performed better. I chose to keep the n_estimators low due to run-time concerns. With this parameter set to 80, the model took 10 minutes to run with an R2 the same as that of the linear regression. It could be worth pursuing random forests by optimizing other parameters such a min_samples_leaf. One approach may be to see the distribution of trip duration to identify the number of of trips which take 5–6 minutes, 6–7 minutes, etc. This could help identify the min_samples_leaf parameter. In the real world, we don’t need to be accurate to the exact second. As long as we can predict how long the trip will take within a minute, it’s a solid result in my opinion. Google maps doesn’t tell you how long your trip will take to the exact second, it gives you it’s prediction as an integer in minutes.
I could’ve used XGboost and other fancy algorithms, however, for a dataset of this size, it would take too long to run and the gains wouldn’t be worth it if there are any.
Final Model: Linear Regression (worth exploring Lasso)
Predictors: Distance, Gender, Average Duration and Average Speed based on Trip and Gender, User Type, and Date information
CV accuracy: 0.852 +/- 0.000
*The code is a work in progress and constantly undergoing changes and improvement with your feedback. Please leave your thoughts in the comments section below.
|
[
{
"code": null,
"e": 493,
"s": 172,
"text": "The goal of this analysis is to create an operating report of Citi Bike for the year of 2017. The following work was completed in less than five working days. Under each visual, I’ve added my thoughts on what I would consider if there was no time constraint. The Citi Bike analysis is based on the mock case shown below:"
},
{
"code": null,
"e": 859,
"s": 493,
"text": "Overview: Your client, The Mayor of New York City, needs a better understanding of Citi Bike ridership. He wants an Operating Report for the Year of 2017 on his desk by the end of the week. Based on previous engagements we know the mayor is a big fan of visualizing data in charts. Specifically, the Mayor wants to see a variety of data visualizations to understand"
},
{
"code": null,
"e": 917,
"s": 859,
"text": "Top 5 stations with the most starts (showing # of starts)"
},
{
"code": null,
"e": 944,
"s": 917,
"text": "Trip duration by user type"
},
{
"code": null,
"e": 1004,
"s": 944,
"text": "Most popular trips based on start station and stop station)"
},
{
"code": null,
"e": 1138,
"s": 1004,
"text": "Rider performance by Gender and Age based on avg trip distance (station to station), median speed (trip duration / distance traveled)"
},
{
"code": null,
"e": 1239,
"s": 1138,
"text": "What is the busiest bike in NYC in 2017? How many times was it used? How many minutes was it in use?"
},
{
"code": null,
"e": 1600,
"s": 1239,
"text": "Additionally, the Mayor has an idea that he wants to pitch to Citi Bike and needs your help proving its feasibility. He would like Citi Bike to add a new feature to their kiosks: “Enter a destination and we’ll tell you how long the trip will take”. We need you to build a model that can predict how long a trip will take given a starting point and destination."
},
{
"code": null,
"e": 1775,
"s": 1600,
"text": "Client: Mayor of New York City, Bill de BlasioObjective: Help the mayor get a better understanding of Citi Bike ridership by creating an operating report for 2017 (NYC only)."
},
{
"code": null,
"e": 1780,
"s": 1775,
"text": "Ask:"
},
{
"code": null,
"e": 2280,
"s": 1780,
"text": "Top 5 stations with the most starts (showing # of starts)Trip duration by user typeMost popular trips (based on start station and stop station)Rider performance by Gender and Age based on avg. trip distance (station to station), median speed (trip duration /distance traveled)What is the busiest bike in NYC in 2017? How many times was it used? How many minutes was it in use?A model that can predict how long a trip will take given a starting point and destination (Do not use the Google Maps API)."
},
{
"code": null,
"e": 2338,
"s": 2280,
"text": "Top 5 stations with the most starts (showing # of starts)"
},
{
"code": null,
"e": 2365,
"s": 2338,
"text": "Trip duration by user type"
},
{
"code": null,
"e": 2426,
"s": 2365,
"text": "Most popular trips (based on start station and stop station)"
},
{
"code": null,
"e": 2560,
"s": 2426,
"text": "Rider performance by Gender and Age based on avg. trip distance (station to station), median speed (trip duration /distance traveled)"
},
{
"code": null,
"e": 2661,
"s": 2560,
"text": "What is the busiest bike in NYC in 2017? How many times was it used? How many minutes was it in use?"
},
{
"code": null,
"e": 2785,
"s": 2661,
"text": "A model that can predict how long a trip will take given a starting point and destination (Do not use the Google Maps API)."
},
{
"code": null,
"e": 2920,
"s": 2785,
"text": "The data was sourced from the Citi Bike’s amazon server which can be accessed here. The code used for this article can be found here.*"
},
{
"code": null,
"e": 3057,
"s": 2920,
"text": "First let’s minimize the work and load in the data set from the server. It’s clear that these files are massive, a few hundred MBs each."
},
{
"code": null,
"e": 3282,
"s": 3057,
"text": "!curl -O \"https://s3.amazonaws.com/tripdata/2017[01-12]-citibike-tripdata.csv.zip\"!unzip '*.zip'!rm *.zipfiles = !ls *.csv #For Ipython onlydf = concat([read_csv(f, header=None,low_memory=False) for f in files], keys=files) "
},
{
"code": null,
"e": 3606,
"s": 3282,
"text": "The column names have spaces in them, would be great to remove them for working purposes. If I was working on a team or a long term project, I would configure column names a little bit differently to make them easier to work with. However, I’ve kept the names simple and easy to understand for the purposes of this article."
},
{
"code": null,
"e": 4123,
"s": 3606,
"text": "The dataset is massive, ~16mil rows. BigData tools would be helpful, however, most require you to pay or have an enterprise license or a limited trial. Additionally, the data is very dirty. Different files have different column names, need to account for this. Mayor de Blasio doesn’t have a technical background. The graphs here are as simple yet informative as possible. I could’ve made more complicated plots, however, they would not be as informative for the mayor. The graphs are designed with the user in mind."
},
{
"code": null,
"e": 4205,
"s": 4123,
"text": "Lastly, my analysis tries best to follow the crisp-dm methodology outlined below."
},
{
"code": null,
"e": 4329,
"s": 4205,
"text": "Let’s understand the data we’re working with and give a brief overview of what each feature represents or should represent."
},
{
"code": null,
"e": 4993,
"s": 4329,
"text": "1. Trip Duration (seconds) — How long a trip lasted2. Start Time and Date - Self explanatory3. Stop Time and Date - Self explanatory4. Start Station Name - Self explanatory5. End Station Name - Self explanatory6. Station ID - Unique identifier for each station7. Station Lat/Long - Coordinates8. Bike ID - unique identifier for each bike9. User Type (Customer = 24-hour pass or 3-day pass user; Subscriber = Annual Member) - Customers are usually tourists, subscribers are usually NYC residents10. Gender (Zero=unknown; 1=male; 2=female) - Usually unknown for customers since they often sign up at a kiosk11. Year of Birth - Self entered, not validated by an ID."
},
{
"code": null,
"e": 5087,
"s": 4993,
"text": "Let’s check if there’s any noise or cleanup which needs to be done before creating the chart."
},
{
"code": null,
"e": 5107,
"s": 5087,
"text": "Any missing values?"
},
{
"code": null,
"e": 5127,
"s": 5107,
"text": "Any missing values?"
},
{
"code": null,
"e": 5149,
"s": 5127,
"text": "Mostly for Birth year"
},
{
"code": null,
"e": 5168,
"s": 5149,
"text": "Few for User Type."
},
{
"code": null,
"e": 5304,
"s": 5168,
"text": "Citi Bike customers (1-day pass or 3-day pass) are often tourists and may not put in their birth year in a rush or due to other reasons"
},
{
"code": null,
"e": 5459,
"s": 5304,
"text": "Citi Bike subscribers tend to be NYC residents, by blindly dropping rows with missing values, we’ll be losing critical information and may introduce bias."
},
{
"code": null,
"e": 5518,
"s": 5459,
"text": "2. Let’s get a description of the data we’re working with:"
},
{
"code": null,
"e": 6316,
"s": 5518,
"text": "3. Citi Bike riders often come across broken bikes. As a user, I am quite familiar with the dilemma. Let’s drop any trips where a trip lasted less than 90 seconds and the start station == end station. 90 seconds is an arbitrary choice based on how long it would take a rider to realize a bike isn’t working properly and coming back to the station to return it and take a new on. Another measure which can be used is 372 seconds (25% quartile). This is based on the assumption that if someone is making a round trip, it most likely is to perform some quick task which is not close enough to walk to, thus this trip should be at least a little bit longer than the shortest trip.In case it was a short trip, let’s add the extra and condition to make sure the start and end station names are the same."
},
{
"code": null,
"e": 6422,
"s": 6316,
"text": "4. Anomalies such as theft and broken docks shouldn’t matter for this metric and can be dealt with later."
},
{
"code": null,
"e": 6637,
"s": 6422,
"text": "Next Steps and Business Use Case: Would be interesting to visualize these stations on a map to see how close they are to each other. This could be used to determine which areas require additional stations or bikes."
},
{
"code": null,
"e": 6774,
"s": 6637,
"text": "This question is a bit unclear in terms of what to do with the anomalies, so I’ll be making two graphs. One with anomalies, one without."
},
{
"code": null,
"e": 6941,
"s": 6774,
"text": "There are NA values in the dataset for usertype as can be seen from missing table image above. Since it’s only 0.09% of the data, it can be considered safe to remove."
},
{
"code": null,
"e": 7208,
"s": 6941,
"text": "According to Citi Bikes’ website: The first 45 minutes of each ride is included for Annual Members, and the first 30 minutes of each ride is included for Day Pass users. If you want to keep a bike out for longer, it’s only an extra $4 for each additional 15 minutes."
},
{
"code": null,
"e": 7787,
"s": 7208,
"text": "It’s safe to assume, no one (or very few people) will be willing to rent a bike for more than 2 hours, especially a clunky citibike. If they did, it would cost them an additional $20 assuming they’re annual subscribers. It would be more economical for them to buy a bike if they want that workout or use one of the tour bikes in central park if they want to tour and explore the city on a bike. There may be a better way to choose an optimal cutoff, however, time is key in a client project. Or just docing and getting another bike. The real cost of a bike is accrued ~24 hours."
},
{
"code": null,
"e": 8253,
"s": 7787,
"text": "Anomalies: Any trip which lasts longer than 2 hours (7,200 seconds) probably indicates a stolen bike, an anomaly, or incorrect docking of the bike. As an avid Citi Bike user, I know first hand that it doesn’t make any sense for one to use a bike for more than one hour! However, I’ve added a one hour cushion just in case. No rider would plan to go over the maximum 45 minutes allowed. However, I plan to reduce this to one hour in the future for modeling purposes."
},
{
"code": null,
"e": 8291,
"s": 8253,
"text": "First Half- with anomalies in dataset"
},
{
"code": null,
"e": 8329,
"s": 8291,
"text": "First Half- with anomalies in dataset"
},
{
"code": null,
"e": 8496,
"s": 8329,
"text": "The bargraph of average trip duration for each user type. It’s helpful, but would be better to see a box-plot or violin plot. Would be easier to interpret in minutes."
},
{
"code": null,
"e": 8676,
"s": 8496,
"text": "Second graph is a basic violin plot based with anomalies included. As we can see, there is too much noise for this to be useful. It’ll be better to look at this without anomalies."
},
{
"code": null,
"e": 8722,
"s": 8676,
"text": "2. Second Half — without anomalies in dataset"
},
{
"code": null,
"e": 8883,
"s": 8722,
"text": "A much more informative graph about trip duration based on user type with anomalies defined as mentioned above. “Fliers” have been removed from the graph below."
},
{
"code": null,
"e": 8955,
"s": 8883,
"text": "Bar-graph highlighting average duration of each trip based on user type"
},
{
"code": null,
"e": 9100,
"s": 8955,
"text": "It’s safe to say that user type will be a strong predictor of trip duration. It’s a point to note for now and we can come back to this later on."
},
{
"code": null,
"e": 9492,
"s": 9100,
"text": "Next Steps & Business Use Case: Customers are allowed 30 min per bike while subscribers are allowed 45 minutes per bike. Data clearly indicates that customers tend to use bikes longer. If the main concern is to have bikes available at docks, then the current time limit makes sense. However, if Citi Bike would like to be user-centric, giving customers more time per bike is worth exploring."
},
{
"code": null,
"e": 9631,
"s": 9492,
"text": "To get most popular trips, the most convenient way to do this is by using the groupby function in pandas. It’s analogous to a Pivot table."
},
{
"code": null,
"e": 9741,
"s": 9631,
"text": "trips_df = df.groupby([‘Start Station Name’,’End Station Name’]).size().reset_index(name = ‘Number of Trips’)"
},
{
"code": null,
"e": 9837,
"s": 9741,
"text": "The groupby function makes it extremely easy and convenient to identify the most popular trips."
},
{
"code": null,
"e": 10312,
"s": 9837,
"text": "Next Steps & Business Use Case: Would be interesting to see this on a map to see if riders are traveling from North to South, East to West, etc. Additionally, it would be good to see most popular trips based on the time of day. This can help Citi Bike determine where to keep bikes and where to have docks available based on the time of day. The assumption being riders travel in one direction to work in the morning and in the opposite direction to get home in the evening."
},
{
"code": null,
"e": 10449,
"s": 10312,
"text": "Ask: Rider performance by Gender and Age based on avg trip distance (station to station), median speed (trip duration/distance traveled)"
},
{
"code": null,
"e": 10508,
"s": 10449,
"text": "Let’s make sure the data we’re working with here is clean."
},
{
"code": null,
"e": 10574,
"s": 10508,
"text": "Missing Gender and Birth Year values? — Check missing_table above"
},
{
"code": null,
"e": 10640,
"s": 10574,
"text": "Missing Gender and Birth Year values? — Check missing_table above"
},
{
"code": null,
"e": 10674,
"s": 10640,
"text": "No for Gender. Yes for Birth Year"
},
{
"code": null,
"e": 11305,
"s": 10674,
"text": "~10% Missing Birth year. Not a big chunk of data. Can either impute missing values or drop it. Since it’s less than 10% of the data, it’s safe to assume the rest of the 90% is a representative sample of data and we can replace the birth year with the median, based on gender and Start Station ID. I chose this method because most people the same age live in similar neighborhoods (i.e: young people in east village, older people in Upper East Side, etc.). This will be done after anomalies are removed and speed is calculated. There may be better ways to impute this data, please share your thoughts in the comments section below."
},
{
"code": null,
"e": 11422,
"s": 11305,
"text": "df['Birth Year'] = df.groupby(['Gender','Start Station ID'])['Birth Year'].transform(lambda x: x.fillna(x.median()))"
},
{
"code": null,
"e": 11446,
"s": 11422,
"text": "2. Are there anomalies?"
},
{
"code": null,
"e": 11737,
"s": 11446,
"text": "For Birth Year, there are some people born prior to 1960. I can believe some 60 year olds can ride a bike and that’s a stretch, however, anyone “born” prior to that riding a Citi Bike is an anomaly and false data. There could be a few senior citizens riding a bike, but probably not likely."
},
{
"code": null,
"e": 11923,
"s": 11737,
"text": "My approach is to identify the age 2 standard deviations lower than the mean. After calculating this number, mean - 2stdev, I removed the tail end of the data, birth year prior to 1956."
},
{
"code": null,
"e": 12019,
"s": 11923,
"text": "df = df.drop(df.index[(df['Birth Year'] < df['Birth Year'].mean()-(2*df['Birth Year'].std()))])"
},
{
"code": null,
"e": 12083,
"s": 12019,
"text": "3. Calculate an Age column to make visuals easier to interpret:"
},
{
"code": null,
"e": 12154,
"s": 12083,
"text": "df['Age'] = 2018 - df['Birth Year'];df['Age'] = df['Age'].astype(int);"
},
{
"code": null,
"e": 12189,
"s": 12154,
"text": "4. Calculate trip distance (Miles)"
},
{
"code": null,
"e": 12306,
"s": 12189,
"text": "No reliable way to calculate bike route since we can’t know what route a rider took without GPS data from each bike."
},
{
"code": null,
"e": 12737,
"s": 12306,
"text": "Could use Google maps and use lat, long coordinates to find bike route distance. However, this would require more than the daily limit on API calls. Use the geopy.distance package which uses Vincenty distance uses more accurate ellipsoidal models. This is more accurate than Haversine formula, but doesn’t matter much for our purposes since the curvature of the earth has a negligible effect on the distance for bike trips in NYC."
},
{
"code": null,
"e": 12927,
"s": 12737,
"text": "In the future, for a dataset of this size, I would consider using the Haversine formula to calculate distance if it's faster. The code below takes too long to run on a dataset of this size."
},
{
"code": null,
"e": 13108,
"s": 12927,
"text": "dist = []for i in range(len(df)): dist.append(geopy.distance.vincenty(df.iloc[i]['Start Coordinates'],df.iloc[i]['End Coordinates']).miles) if (i%1000000==0): print(i)"
},
{
"code": null,
"e": 13152,
"s": 13108,
"text": "5. Calculate Speed (min/mile) and (mile/hr)"
},
{
"code": null,
"e": 13225,
"s": 13152,
"text": "(min/mile): Can be used like sprint time (how fast does this person run)"
},
{
"code": null,
"e": 13281,
"s": 13225,
"text": "df['min_mile'] = round(df['Minutes']/df['Distance'], 2)"
},
{
"code": null,
"e": 13466,
"s": 13281,
"text": "(mile/hr): Conventional approach. Miles/hour is an easy to understand unit of measure and one most people are used to seeing. So the visual will be created based on this understanding."
},
{
"code": null,
"e": 13527,
"s": 13466,
"text": "df['mile_hour'] = round(df['Distance']/(df['Minutes']/60),2)"
},
{
"code": null,
"e": 13560,
"s": 13527,
"text": "6. Dealing with “circular” trips"
},
{
"code": null,
"e": 13800,
"s": 13560,
"text": "Circular trips are trips which start and end at the same station. The distance for these trips will come out to 0, however, that is not the case. These points will skew the data and visuals. Will be removing them to account for this issue."
},
{
"code": null,
"e": 14040,
"s": 13800,
"text": "For the model, this data is also irrelevant. Because if someone is going on a circular trip, the only person who knows how long the trip is going to take is the rider, assuming s/he knows that. So it’s safe to drop this data for the model."
},
{
"code": null,
"e": 14086,
"s": 14040,
"text": "df = df.drop(df.index[(df['Distance'] == 0)])"
},
{
"code": null,
"e": 14502,
"s": 14086,
"text": "7. We have some Start Coordinates as (0.0,0.0). These are trips which were taken away for repair or for other purposes. These should be dropped. If kept, the distance for these trips is 5,389 miles. For this reason I’ve dropped any points where the distance is outrageously large. Additionally, we have some missing values. Since it’s a tiny portion, let’s replace missing values based on Gender and start location."
},
{
"code": null,
"e": 15088,
"s": 14502,
"text": "On some trips, the speed of the biker is more than 200 mph. This could be due to the formula used for distance calculation or some other error. The fastest cyclist in the world on a flat surface ever recorded biked at 82mph. It’s safe to assume none of the Citi Bike riders can approach this speed. Due to this and the fact that an average cyclist speed is 10mph, I’ve decided to remove all data where the speed in mph is greater than 20 mph and less than 2 stdev from the mean, because that’s probably a roundtrip where the biker found the dock was full and used another dock instead."
},
{
"code": null,
"e": 15162,
"s": 15088,
"text": "8. Rider performance by age and gender in miles/hour, after data cleaning"
},
{
"code": null,
"e": 15230,
"s": 15162,
"text": "9. Rider performance by age and gender in average distance in miles"
},
{
"code": null,
"e": 15670,
"s": 15230,
"text": "Next Steps & Business Use Case: Worth exploring the number of trips based on gender and age. This could help create different customer baskets based on bike usage. If working folks use Citi Bike more often they could be charged a higher rate. If senior citizens are using Citi Bike, they should be rewarded for staying fit and active. This information could be communicated to their insurers to reward them for taking care of their health."
},
{
"code": null,
"e": 15675,
"s": 15670,
"text": "Ask:"
},
{
"code": null,
"e": 15774,
"s": 15675,
"text": "What is the busiest bike in NYC in 2017?How many times was it used?How many minutes was it in use?"
},
{
"code": null,
"e": 15815,
"s": 15774,
"text": "What is the busiest bike in NYC in 2017?"
},
{
"code": null,
"e": 15843,
"s": 15815,
"text": "How many times was it used?"
},
{
"code": null,
"e": 15875,
"s": 15843,
"text": "How many minutes was it in use?"
},
{
"code": null,
"e": 16011,
"s": 15875,
"text": "Busiest bike and count can be identified by a groupby function. Function below will also identify the number of times the bike was used"
},
{
"code": null,
"e": 16181,
"s": 16011,
"text": "bike_use_df = df.groupby(['Bike ID']).size().reset_index(name = 'Number of Times Used');bike_use_df = bike_use_df.sort_values('Number of Times Used', ascending = False);"
},
{
"code": null,
"e": 16297,
"s": 16181,
"text": "A similar groupby function which calls for the sum on minutes can identify the number of minutes the bike was used."
},
{
"code": null,
"e": 16438,
"s": 16297,
"text": "bike_min_df['Minutes Used'] = df.groupby('Bike ID')['Minutes'].sum()bike_min_df = bike_min_df.sort_values('Minutes Used', ascending = False)"
},
{
"code": null,
"e": 16933,
"s": 16438,
"text": "Next Steps & Business Use Case: If combined with Citi Bike maintenance data, this information can be used to identify when a bike will need maintenance and repairs. This can help decrease the problem of broken bikes taking up docks at stations, which is an issue lots of riders face. This information can also be used to build a brand and for marketing purposes. It would be neat to have a “Citi Bike of the Year”, the most used bike advertised publicly as a symbol to increase bike use in NYC."
},
{
"code": null,
"e": 17035,
"s": 16933,
"text": "Ask: Build a model that can predict how long a trip will take given a starting point and destination."
},
{
"code": null,
"e": 17403,
"s": 17035,
"text": "Assumptions on how the Kiosk will work: Let’s assume that when a user inputs the start and end station, they swipe their key fob (if they’re a subscriber) and enter their info on the kiosk (if they’re a “Customer”) prior to entering the start and end station. This means that we would know their gender and age. Thus these variables can be used in building the model."
},
{
"code": null,
"e": 17411,
"s": 17403,
"text": "Step 1."
},
{
"code": null,
"e": 18362,
"s": 17411,
"text": "This dataset is massive. Almost 14 million rows. Let’s work on a random subsample while we build and evaluate models. If I tried to build and evaluate a model on the entire dataset, each run would take me ~10+ minutes depending on the model. One good way to decide what portion of your data to work with is using a learning curve. However, my kernel keeps crashing while trying to create that learning curve. If we were working with data for multiple years, we would need to reconsider this approach. However, given the reasons above, let’s sample 10% of the data. It’s still ~1.3 million rows and should be a representative sample since it’s randomly selected. To ensure that it’s a representative sample, we should look at the description of the original dataset and the sample dataset. Lastly, we can make sure the data is representative by making the the visuals above are the similar for the random sample. 10% of the data passes the test above."
},
{
"code": null,
"e": 18891,
"s": 18362,
"text": "Additionally, Citi Bike trips are capped at 45 minutes for subscribers and 30 minutes for customers (refer to “According to Citi Bike’s website” above). After these respective time limits, the riders incur a fee. To model our data, it does not make sense to include trips which last longer than the prescribed 45 minutes. Rider’s don’t often plan to go over the allocated time and there’s no clear way of knowing who plans to go over the allocated time. It’s a question worth exploring, however, the data is noise for our model."
},
{
"code": null,
"e": 18995,
"s": 18891,
"text": "df = df.drop(df.index[(df['Trip Duration'] > 2700)])df_sample = df.sample(frac = 0.1, random_state = 0)"
},
{
"code": null,
"e": 19003,
"s": 18995,
"text": "Step 2."
},
{
"code": null,
"e": 19204,
"s": 19003,
"text": "Let’s get a baseline. If I were to just run a simple multi-variate linear regression, what would my model look like and how accurate would it be? Need to prepare the data for a multivariate regression"
},
{
"code": null,
"e": 19228,
"s": 19204,
"text": "Drop irrelevant columns"
},
{
"code": null,
"e": 19252,
"s": 19228,
"text": "Drop irrelevant columns"
},
{
"code": null,
"e": 19324,
"s": 19252,
"text": "Trip Duration: We have the minutes column, which is the target variable"
},
{
"code": null,
"e": 19420,
"s": 19324,
"text": "Stop Time: In the real world, we won’t have this information when predicting the trip duration."
},
{
"code": null,
"e": 19483,
"s": 19420,
"text": "Start Station ID: Start Station Name captures this information"
},
{
"code": null,
"e": 19552,
"s": 19483,
"text": "Start Station Latitude: Start Station Name captures this information"
},
{
"code": null,
"e": 19622,
"s": 19552,
"text": "Start Station Longitude: Start Station Name captures this information"
},
{
"code": null,
"e": 19686,
"s": 19622,
"text": "Start Coordinates: Start Station Name captures this information"
},
{
"code": null,
"e": 19745,
"s": 19686,
"text": "End Station ID: End Station Name captures this information"
},
{
"code": null,
"e": 19810,
"s": 19745,
"text": "End Station Latitude: End Station Name captures this information"
},
{
"code": null,
"e": 19876,
"s": 19810,
"text": "End Station Longitude: End Station Name captures this information"
},
{
"code": null,
"e": 19936,
"s": 19876,
"text": "End Coordinates: End Station Name captures this information"
},
{
"code": null,
"e": 20003,
"s": 19936,
"text": "Bike Id: We won’t know what bike the user is going to end up using"
},
{
"code": null,
"e": 20045,
"s": 20003,
"text": "Birth Year: Age captures this information"
},
{
"code": null,
"e": 20179,
"s": 20045,
"text": "min_mile: Effectively the same information as end time when combined with distance. We won’t have this information in the real world."
},
{
"code": null,
"e": 20314,
"s": 20179,
"text": "mile_hour: Effectively the same information as end time when combined with distance. We won’t have this information in the real world."
},
{
"code": null,
"e": 20380,
"s": 20314,
"text": "(Speed * Distance = Trip Duration): Which is why speed is dropped"
},
{
"code": null,
"e": 20994,
"s": 20380,
"text": "Start Station Name and End Station Name: The distance variable captures the same information. For the model, if a user is inputting start and end station, we can build a simple function to calculate the distance which would capture the same information. One may argue to keep this information since this is the information which will be provided at the kiosk. However, given that there are over 800 stations, if we keep this information, we are required to encode this for any regression algorithm. This would create 800 features (~15 million rows) leading to lots of data, without much, if any, information gain."
},
{
"code": null,
"e": 21282,
"s": 20994,
"text": "After the cleaning mentioned above, the final predictors used for the baseline model are Distance, User Type, and Gender. Age seems to have no impact as can be seen by the visuals in part 4. To confirm this, I ran the model with and without age. Age had little to no impact on the model."
},
{
"code": null,
"e": 21476,
"s": 21282,
"text": "I chose to run a linear regression. The size of the data and limitation of resources made running more complex models less attractive. Ensemble algorithms were tested, but took too long to run."
},
{
"code": null,
"e": 21639,
"s": 21476,
"text": "The model is pretty good for a baseline model with an R2 and Adjusted R2 of 0.774. Distance seems to be having a large impact on trip duration, which makes sense."
},
{
"code": null,
"e": 21667,
"s": 21639,
"text": "Steps to make improvements:"
},
{
"code": null,
"e": 21708,
"s": 21667,
"text": "1. Add back time in the following format"
},
{
"code": null,
"e": 21898,
"s": 21708,
"text": "Is the ride on a weekday or weekend. Weekday, is rush-hour commute for the most part and probably from home to work. Weekend could be a longer, more casual ride and have higher variability."
},
{
"code": null,
"e": 22069,
"s": 21898,
"text": "Is the ride in the morning, afternoon, evening, or night. The exact timing will be based on the difference in trip duration based on time of day. Will have visuals below."
},
{
"code": null,
"e": 22091,
"s": 22069,
"text": "2. What season is it?"
},
{
"code": null,
"e": 22116,
"s": 22091,
"text": "December — Feb. = Winter"
},
{
"code": null,
"e": 22137,
"s": 22116,
"text": "March — May = Spring"
},
{
"code": null,
"e": 22158,
"s": 22137,
"text": "June — Aug. = Summer"
},
{
"code": null,
"e": 22178,
"s": 22158,
"text": "Sept. — Nov. = Fall"
},
{
"code": null,
"e": 23007,
"s": 22178,
"text": "def get_date_info(df): df['d_week'] = df['Start Time'].dt.dayofweek df['m_yr'] = df['Start Time'].dt.month df['ToD'] = df['Start Time'].dt.hour df['d_week'] = (df['d_week']<5).astype(int) df['m_yr'] = df['m_yr'].replace(to_replace=[12,1,2], value = 0) df['m_yr'] = df['m_yr'].replace(to_replace=[3,4,5], value = 1) df['m_yr'] = df['m_yr'].replace(to_replace=[6,7,8], value = 2) df['m_yr'] = df['m_yr'].replace(to_replace=[9,10,11], value = 3) df['ToD'] = pd.cut(df['ToD'], bins=[-1, 5, 9, 14, 20, 25], labels=['Night','Morning','Afternoon','Evening','Night1']) df['ToD'] = df['ToD'].replace(to_replace='Night1', value = 'Night') df['ToD'] = df['ToD'].cat.remove_unused_categories() df['m_yr'] = df['m_yr'].astype('category') df['d_week'] = df['d_week'].astype('category')return(df)"
},
{
"code": null,
"e": 23085,
"s": 23007,
"text": "Model 1: Negligible improvement in R2: 77.7% (depending on random_state used)"
},
{
"code": null,
"e": 23168,
"s": 23085,
"text": "Safe to assume that we can drop these variables as they don’t have a major impact."
},
{
"code": null,
"e": 23429,
"s": 23168,
"text": "It’s a bit surprising that the weekday variable has little to no impact since people most likely bike for leisure on weekends rather than for work. This could be explained by obtaining a breakdown of riders. Maybe a lot of Citi Bike users are college students."
},
{
"code": null,
"e": 23831,
"s": 23429,
"text": "Another possibility is that the effect of this feature is being skewed by the fact that there are both customers and subscribers in this dataset and the effect of this feature on both variables is different. However, there’s no clear explanation for now. It’s worth considering building a separate model for subscribers and customers since their behavior is so drastically different as seen in part 2."
},
{
"code": null,
"e": 24092,
"s": 23831,
"text": "Next steps will be to factor in speed and distance based on Gender and Trip. By not being able to encode start and end stations (due to the sheer number of points), we are losing crucial information on the trip itself. We need another proxy for those measures."
},
{
"code": null,
"e": 24319,
"s": 24092,
"text": "Another change I could make is to bin age into buckets. However, the data indicates that age has no correlation or effect on the trip duration. This is counter-intuitive, however, I don’t have a good reason to refute the data."
},
{
"code": null,
"e": 24393,
"s": 24319,
"text": "Include Average Speed based on: Trip (Start + End Station) and User Type."
},
{
"code": null,
"e": 24467,
"s": 24393,
"text": "Include Average Speed based on: Trip (Start + End Station) and User Type."
},
{
"code": null,
"e": 24619,
"s": 24467,
"text": "Reason for Trip: Some trips are up hill, others are down hill. Some routes, such as one through times square involve heavy traffic, based on intuition."
},
{
"code": null,
"e": 24755,
"s": 24619,
"text": "Reason for User Type: Tourists (Customers), will usually ride more slowly with frequent stops than a Subscriber, according to the data."
},
{
"code": null,
"e": 24854,
"s": 24755,
"text": "2. Include average duration for each trip based on: Trip and User Type for reasons mentioned above"
},
{
"code": null,
"e": 25333,
"s": 24854,
"text": "def get_speed_distance(df): df['Start Station Name'] = df['Start Station Name'].astype(str) df['End Station Name'] = df['End Station Name'].astype(str) df['Trip'] = df['Start Station Name'] + ' to ' + df['End Station Name'] df['Trip'] = df['Trip'].astype('category') df['avg_speed'] = df.groupby(['Trip','User Type'])['mile_hour'].transform('mean') df['avg_duration'] = df.groupby(['Trip','User Type'])['Trip Duration'].transform('median') return df"
},
{
"code": null,
"e": 25395,
"s": 25333,
"text": "The model is significantly better. But can it be even better?"
},
{
"code": null,
"e": 25673,
"s": 25395,
"text": "One factor which would have a significant impact on trip duration is traffic. However, since we do not know what route the rider took it’s difficult to incorporate this information. Lastly, the Google Maps API caps usage, so we can’t use it to identify traffic patterns easily."
},
{
"code": null,
"e": 26078,
"s": 25673,
"text": "One factor which a lot of people think may be a good predictor of trip duration is weather. I personally disagree. Weather influences wether or not a user will bike, not how long they will bike. If it’s snowing, I won’t bike to work. If it’s nice, I will bike to work. Regardless of my opinion, I am going to test this hypothesis. If weather is not a strong indicator, I will remove it in the next model."
},
{
"code": null,
"e": 26314,
"s": 26078,
"text": "The weather data was acquired from the National Centers for Environmental Information. The data sourced from the website is a daily summary. The attributes include: high temperature (F), low temperature (F), and precipitation (inches)."
},
{
"code": null,
"e": 26458,
"s": 26314,
"text": "def get_weather(df): df['DATE'] = to_datetime(df['Start Time'].dt.date) df = df.merge(df_weather, on = 'DATE', how = 'left') return df"
},
{
"code": null,
"e": 26530,
"s": 26458,
"text": "Little to no improvement in the model. Weather has little to no impact."
},
{
"code": null,
"e": 26748,
"s": 26530,
"text": "The coefficient for avg_duration spiked up. Not sure why, but the higher coefficient makes sense since duration is our target variable, and avg_duration is a solid proxy (anchor) for how long a trip most likely takes."
},
{
"code": null,
"e": 26816,
"s": 26748,
"text": "Let’s confirm the effectiveness of the model with cross validation:"
},
{
"code": null,
"e": 26845,
"s": 26816,
"text": "CV accuracy: 0.874 +/- 0.001"
},
{
"code": null,
"e": 26964,
"s": 26845,
"text": "Based on some of the observations above I ran the same model above without weather and date information as predictors."
},
{
"code": null,
"e": 27128,
"s": 26964,
"text": "As we can see, there’s a very small decrease in R2. Another interesting observation is the effect of this data on the coefficient of user type, it’s almost halved."
},
{
"code": null,
"e": 27307,
"s": 27128,
"text": "The effect on the random sample is small, however, with 10 times the amount of data, the effect could be slightly larger, so for the final model, let’s keep the date information."
},
{
"code": null,
"e": 28211,
"s": 27307,
"text": "Lastly, I chose to test other regression algorithms such as random forests to see if another regressor performed better. I chose to keep the n_estimators low due to run-time concerns. With this parameter set to 80, the model took 10 minutes to run with an R2 the same as that of the linear regression. It could be worth pursuing random forests by optimizing other parameters such a min_samples_leaf. One approach may be to see the distribution of trip duration to identify the number of of trips which take 5–6 minutes, 6–7 minutes, etc. This could help identify the min_samples_leaf parameter. In the real world, we don’t need to be accurate to the exact second. As long as we can predict how long the trip will take within a minute, it’s a solid result in my opinion. Google maps doesn’t tell you how long your trip will take to the exact second, it gives you it’s prediction as an integer in minutes."
},
{
"code": null,
"e": 28383,
"s": 28211,
"text": "I could’ve used XGboost and other fancy algorithms, however, for a dataset of this size, it would take too long to run and the gains wouldn’t be worth it if there are any."
},
{
"code": null,
"e": 28438,
"s": 28383,
"text": "Final Model: Linear Regression (worth exploring Lasso)"
},
{
"code": null,
"e": 28561,
"s": 28438,
"text": "Predictors: Distance, Gender, Average Duration and Average Speed based on Trip and Gender, User Type, and Date information"
},
{
"code": null,
"e": 28590,
"s": 28561,
"text": "CV accuracy: 0.852 +/- 0.000"
}
] |
Cascading Behavior in Social Networks - GeeksforGeeks
|
01 Oct, 2020
Prerequisite: Introduction to Social Networks, Python Basics
When people are connected in networks to each other then they can influence each other’s behavior and decisions. This is called Cascading Behavior in Networks.
Let’s consider an example, assume all the people in a society have adopted a trend X. Now there comes new trend Y and a small group accepts this new trend and after this, their neighbors also accept this trend Y and so on.
Example of Cascading Behavior( a=2,b=3 and p=2/5)
So, there are 4 main ideas in Cascading Behaviors:
Increasing the payoff.Key people.Impact of communities on the Cascades.Cascading and Clusters.
Increasing the payoff.
Key people.
Impact of communities on the Cascades.
Cascading and Clusters.
Below is the code for each idea.
1. Increase the payoff.
Python3
# cascade pay offimport networkx as nximport matplotlib.pyplot as plt def set_all_B(G): for i in G.nodes(): G.nodes[i]['action'] = 'B' return G def set_A(G, list1): for i in list1: G.nodes[i]['action'] = 'A' return G def get_colors(G): color = [] for i in G.nodes(): if (G.nodes[i]['action'] == 'B'): color.append('red') else: color.append('blue') return color def recalculate(G): dict1 = {} # payoff(A)=a=4 # payoff(B)=b=3 a = 15 b = 5 for i in G.nodes(): neigh = G.neighbors(i) count_A = 0 count_B = 0 for j in neigh: if (G.nodes[j]['action'] == 'A'): count_A += 1 else: count_B += 1 payoff_A = a * count_A payoff_B = b * count_B if (payoff_A >= payoff_B): dict1[i] = 'A' else: dict1[i] = 'B' return dict1 def reset_node_attributes(G, action_dict): for i in action_dict: G.nodes[i]['action'] = action_dict[i] return G def Calculate(G): terminate = True count = 0 c = 0 while (terminate and count < 10): count += 1 # action_dict will hold a dictionary action_dict = recalculate(G) G = reset_node_attributes(G, action_dict) colors = get_colors(G) if (colors.count('red') == len(colors) or colors.count('green') == len(colors)): terminate = False if (colors.count('green') == len(colors)): c = 1 nx.draw(G, with_labels=1, node_color=colors, node_size=800) plt.show() if (c == 1): print('cascade complete') else: print('cascade incomplete') G = nx.erdos_renyi_graph(10, 0.5)nx.write_gml(G, "erdos_graph.gml") G = nx.read_gml('erdos_graph.gml')print(G.nodes()) G = set_all_B(G) # initial adopterslist1 = ['2', '1', '3']G = set_A(G, list1)colors = get_colors(G) nx.draw(G, with_labels=1, node_color=colors, node_size=800)plt.show() Calculate(G)
Output:
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
cascade complete
2. Key people.
Python3
# cascade key peopleimport networkx as nximport matplotlib.pyplot as plt G = nx.erdos_renyi_graph(10, 0.5)nx.write_gml(G, "erdos_graph.gml") def set_all_B(G): for i in G.nodes(): G.nodes[i]['action'] = 'B' return G def set_A(G, list1): for i in list1: G.nodes[i]['action'] = 'A' return G def get_colors(G): color = [] for i in G.nodes(): if (G.nodes[i]['action'] == 'B'): color.append('red') else: color.append('green') return color def recalculate(G): dict1 = {} # payoff(A)=a=4 # payoff(B)=b=3 a = 10 b = 5 for i in G.nodes(): neigh = G.neighbors(i) count_A = 0 count_B = 0 for j in neigh: if (G.nodes[j]['action'] == 'A'): count_A += 1 else: count_B += 1 payoff_A = a * count_A payoff_B = b * count_B if (payoff_A >= payoff_B): dict1[i] = 'A' else: dict1[i] = 'B' return dict1 def reset_node_attributes(G, action_dict): for i in action_dict: G.nodes[i]['action'] = action_dict[i] return G def Calculate(G): continuee = True count = 0 c = 0 while (continuee and count < 100): count += 1 # action_dict will hold a dictionary action_dict = recalculate(G) G = reset_node_attributes(G, action_dict) colors = get_colors(G) if (colors.count('red') == len(colors) or colors.count('green') == len(colors)): continuee = False if (colors.count('green') == len(colors)): c = 1 if (c == 1): print('cascade complete') else: print('cascade incomplete') G = nx.read_gml('erdos_graph.gml') for i in G.nodes(): for j in G.nodes(): if (i < j): list1 = [] list1.append(i) list1.append(j) print(list1, ':', end="") G = set_all_B(G) G = set_A(G, list1) colors = get_colors(G) Calculate(G)
Output:
['0', '1'] :cascade complete
['0', '2'] :cascade incomplete
['0', '3'] :cascade complete
['0', '4'] :cascade complete
['0', '5'] :cascade incomplete
['0', '6'] :cascade complete
['0', '7'] :cascade complete
['0', '8'] :cascade complete
['0', '9'] :cascade complete
['1', '2'] :cascade complete
['1', '3'] :cascade complete
['1', '4'] :cascade complete
['1', '5'] :cascade complete
['1', '6'] :cascade complete
['1', '7'] :cascade complete
['1', '8'] :cascade complete
['1', '9'] :cascade complete
['2', '3'] :cascade incomplete
['2', '4'] :cascade incomplete
['2', '5'] :cascade incomplete
['2', '6'] :cascade incomplete
['2', '7'] :cascade incomplete
['2', '8'] :cascade incomplete
['2', '9'] :cascade complete
['3', '4'] :cascade complete
['3', '5'] :cascade incomplete
['3', '6'] :cascade complete
['3', '7'] :cascade complete
['3', '8'] :cascade complete
['3', '9'] :cascade complete
['4', '5'] :cascade incomplete
['4', '6'] :cascade complete
['4', '7'] :cascade complete
['4', '8'] :cascade complete
['4', '9'] :cascade incomplete
['5', '6'] :cascade incomplete
['5', '7'] :cascade incomplete
['5', '8'] :cascade incomplete
['5', '9'] :cascade complete
['6', '7'] :cascade complete
['6', '8'] :cascade complete
['6', '9'] :cascade complete
['7', '8'] :cascade complete
['7', '9'] :cascade complete
['8', '9'] :cascade complete
3. Impact of communities on the Cascades.
Python3
import networkx as nximport randomimport matplotlib.pyplot as plt def first_community(G): for i in range(1, 11): G.add_node(i) for i in range(1, 11): for j in range(1, 11): if (i < j): r = random.random() if (r < 0.5): G.add_edge(i, j) return G def second_community(G): for i in range(11, 21): G.add_node(i) for i in range(11, 21): for j in range(11, 21): if (i < j): r = random.random() if (r < 0.5): G.add_edge(i, j) return G G = nx.Graph()G = first_community(G)G = second_community(G)G.add_edge(5, 15) nx.draw(G, with_labels=1)plt.show() nx.write_gml(G, "community.gml")
Output:
Impact on clusters
4. Cascading on Clusters.
Python3
import networkx as nximport matplotlib.pyplot as plt def set_all_B(G): for i in G.nodes(): G.nodes[i]['action'] = 'B' return G def set_A(G, list1): for i in list1: G.nodes[i]['action'] = 'A' return G def get_colors(G): color = [] for i in G.nodes(): if (G.nodes[i]['action'] == 'B'): color.append('red') else: color.append('green') return color def recalculate(G): dict1 = {} a = 3 b = 2 for i in G.nodes(): neigh = G.neighbors(i) count_A = 0 count_B = 0 for j in neigh: if (G.nodes[j]['action'] == 'A'): count_A += 1 else: count_B += 1 payoff_A = a * count_A payoff_B = b * count_B if (payoff_A >= payoff_B): dict1[i] = 'A' else: dict1[i] = 'B' return dict1 def reset_node_attributes(G, action_dict): for i in action_dict: G.nodes[i]['action'] = action_dict[i] return G def Calculate(G): terminate = True count = 0 c = 0 while (terminate and count < 100): count += 1 # action_dict will hold a dictionary action_dict = recalculate(G) G = reset_node_attributes(G, action_dict) colors = get_colors(G) if (colors.count('red') == len(colors) or colors.count('green') == len(colors)): terminate = False if (colors.count('green') == len(colors)): c = 1 if (c == 1): print('cascade complete') else: print('cascade incomplete') nx.draw(G, with_labels=1, node_color=colors, node_size=800) plt.show() G = nx.Graph()G.add_nodes_from(range(13))G.add_edges_from( [(0, 1), (0, 6), (1, 2), (1, 8), (1, 12), (2, 9), (2, 12), (3, 4), (3, 9), (3, 12), (4, 5), (4, 12), (5, 6), (5, 10), (6, 8), (7, 8), (7, 9), (7, 10), (7, 11), (8, 9), (8, 10), (8, 11), (9, 10), (9, 11), (10, 11)]) list2 = [[0, 1, 2, 3], [0, 2, 3, 4], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 12], [2, 3, 4, 12], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5, 6, 12]] for list1 in list2: print(list1) G = set_all_B(G) G = set_A(G, list1) colors = get_colors(G) nx.draw(G, with_labels=1, node_color=colors, node_size=800) plt.show() Calculate(G)
Output:
[0, 1, 2, 3]
cascade incomplete
[0, 2, 3, 4]
cascade incomplete
[1, 2, 3, 4]
cascade incomplete
[2, 3, 4, 5]
cascade incomplete
[3, 4, 5, 6]
cascade incomplete
[4, 5, 6, 12]
cascade incomplete
[2, 3, 4, 12]
cascade incomplete
[0, 1, 2, 3, 4, 5]
cascade incomplete
[0, 1, 2, 3, 4, 5, 6, 12]
cascade complete
Python-Networking
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 24354,
"s": 24292,
"text": "Prerequisite: Introduction to Social Networks, Python Basics "
},
{
"code": null,
"e": 24514,
"s": 24354,
"text": "When people are connected in networks to each other then they can influence each other’s behavior and decisions. This is called Cascading Behavior in Networks."
},
{
"code": null,
"e": 24737,
"s": 24514,
"text": "Let’s consider an example, assume all the people in a society have adopted a trend X. Now there comes new trend Y and a small group accepts this new trend and after this, their neighbors also accept this trend Y and so on."
},
{
"code": null,
"e": 24789,
"s": 24739,
"text": "Example of Cascading Behavior( a=2,b=3 and p=2/5)"
},
{
"code": null,
"e": 24840,
"s": 24789,
"text": "So, there are 4 main ideas in Cascading Behaviors:"
},
{
"code": null,
"e": 24935,
"s": 24840,
"text": "Increasing the payoff.Key people.Impact of communities on the Cascades.Cascading and Clusters."
},
{
"code": null,
"e": 24958,
"s": 24935,
"text": "Increasing the payoff."
},
{
"code": null,
"e": 24970,
"s": 24958,
"text": "Key people."
},
{
"code": null,
"e": 25009,
"s": 24970,
"text": "Impact of communities on the Cascades."
},
{
"code": null,
"e": 25033,
"s": 25009,
"text": "Cascading and Clusters."
},
{
"code": null,
"e": 25066,
"s": 25033,
"text": "Below is the code for each idea."
},
{
"code": null,
"e": 25090,
"s": 25066,
"text": "1. Increase the payoff."
},
{
"code": null,
"e": 25098,
"s": 25090,
"text": "Python3"
},
{
"code": "# cascade pay offimport networkx as nximport matplotlib.pyplot as plt def set_all_B(G): for i in G.nodes(): G.nodes[i]['action'] = 'B' return G def set_A(G, list1): for i in list1: G.nodes[i]['action'] = 'A' return G def get_colors(G): color = [] for i in G.nodes(): if (G.nodes[i]['action'] == 'B'): color.append('red') else: color.append('blue') return color def recalculate(G): dict1 = {} # payoff(A)=a=4 # payoff(B)=b=3 a = 15 b = 5 for i in G.nodes(): neigh = G.neighbors(i) count_A = 0 count_B = 0 for j in neigh: if (G.nodes[j]['action'] == 'A'): count_A += 1 else: count_B += 1 payoff_A = a * count_A payoff_B = b * count_B if (payoff_A >= payoff_B): dict1[i] = 'A' else: dict1[i] = 'B' return dict1 def reset_node_attributes(G, action_dict): for i in action_dict: G.nodes[i]['action'] = action_dict[i] return G def Calculate(G): terminate = True count = 0 c = 0 while (terminate and count < 10): count += 1 # action_dict will hold a dictionary action_dict = recalculate(G) G = reset_node_attributes(G, action_dict) colors = get_colors(G) if (colors.count('red') == len(colors) or colors.count('green') == len(colors)): terminate = False if (colors.count('green') == len(colors)): c = 1 nx.draw(G, with_labels=1, node_color=colors, node_size=800) plt.show() if (c == 1): print('cascade complete') else: print('cascade incomplete') G = nx.erdos_renyi_graph(10, 0.5)nx.write_gml(G, \"erdos_graph.gml\") G = nx.read_gml('erdos_graph.gml')print(G.nodes()) G = set_all_B(G) # initial adopterslist1 = ['2', '1', '3']G = set_A(G, list1)colors = get_colors(G) nx.draw(G, with_labels=1, node_color=colors, node_size=800)plt.show() Calculate(G)",
"e": 27149,
"s": 25098,
"text": null
},
{
"code": null,
"e": 27157,
"s": 27149,
"text": "Output:"
},
{
"code": null,
"e": 27226,
"s": 27157,
"text": "['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\ncascade complete\n"
},
{
"code": null,
"e": 27241,
"s": 27226,
"text": "2. Key people."
},
{
"code": null,
"e": 27249,
"s": 27241,
"text": "Python3"
},
{
"code": "# cascade key peopleimport networkx as nximport matplotlib.pyplot as plt G = nx.erdos_renyi_graph(10, 0.5)nx.write_gml(G, \"erdos_graph.gml\") def set_all_B(G): for i in G.nodes(): G.nodes[i]['action'] = 'B' return G def set_A(G, list1): for i in list1: G.nodes[i]['action'] = 'A' return G def get_colors(G): color = [] for i in G.nodes(): if (G.nodes[i]['action'] == 'B'): color.append('red') else: color.append('green') return color def recalculate(G): dict1 = {} # payoff(A)=a=4 # payoff(B)=b=3 a = 10 b = 5 for i in G.nodes(): neigh = G.neighbors(i) count_A = 0 count_B = 0 for j in neigh: if (G.nodes[j]['action'] == 'A'): count_A += 1 else: count_B += 1 payoff_A = a * count_A payoff_B = b * count_B if (payoff_A >= payoff_B): dict1[i] = 'A' else: dict1[i] = 'B' return dict1 def reset_node_attributes(G, action_dict): for i in action_dict: G.nodes[i]['action'] = action_dict[i] return G def Calculate(G): continuee = True count = 0 c = 0 while (continuee and count < 100): count += 1 # action_dict will hold a dictionary action_dict = recalculate(G) G = reset_node_attributes(G, action_dict) colors = get_colors(G) if (colors.count('red') == len(colors) or colors.count('green') == len(colors)): continuee = False if (colors.count('green') == len(colors)): c = 1 if (c == 1): print('cascade complete') else: print('cascade incomplete') G = nx.read_gml('erdos_graph.gml') for i in G.nodes(): for j in G.nodes(): if (i < j): list1 = [] list1.append(i) list1.append(j) print(list1, ':', end=\"\") G = set_all_B(G) G = set_A(G, list1) colors = get_colors(G) Calculate(G)",
"e": 29326,
"s": 27249,
"text": null
},
{
"code": null,
"e": 29334,
"s": 29326,
"text": "Output:"
},
{
"code": null,
"e": 30668,
"s": 29334,
"text": "['0', '1'] :cascade complete\n['0', '2'] :cascade incomplete\n['0', '3'] :cascade complete\n['0', '4'] :cascade complete\n['0', '5'] :cascade incomplete\n['0', '6'] :cascade complete\n['0', '7'] :cascade complete\n['0', '8'] :cascade complete\n['0', '9'] :cascade complete\n['1', '2'] :cascade complete\n['1', '3'] :cascade complete\n['1', '4'] :cascade complete\n['1', '5'] :cascade complete\n['1', '6'] :cascade complete\n['1', '7'] :cascade complete\n['1', '8'] :cascade complete\n['1', '9'] :cascade complete\n['2', '3'] :cascade incomplete\n['2', '4'] :cascade incomplete\n['2', '5'] :cascade incomplete\n['2', '6'] :cascade incomplete\n['2', '7'] :cascade incomplete\n['2', '8'] :cascade incomplete\n['2', '9'] :cascade complete\n['3', '4'] :cascade complete\n['3', '5'] :cascade incomplete\n['3', '6'] :cascade complete\n['3', '7'] :cascade complete\n['3', '8'] :cascade complete\n['3', '9'] :cascade complete\n['4', '5'] :cascade incomplete\n['4', '6'] :cascade complete\n['4', '7'] :cascade complete\n['4', '8'] :cascade complete\n['4', '9'] :cascade incomplete\n['5', '6'] :cascade incomplete\n['5', '7'] :cascade incomplete\n['5', '8'] :cascade incomplete\n['5', '9'] :cascade complete\n['6', '7'] :cascade complete\n['6', '8'] :cascade complete\n['6', '9'] :cascade complete\n['7', '8'] :cascade complete\n['7', '9'] :cascade complete\n['8', '9'] :cascade complete\n"
},
{
"code": null,
"e": 30710,
"s": 30668,
"text": "3. Impact of communities on the Cascades."
},
{
"code": null,
"e": 30718,
"s": 30710,
"text": "Python3"
},
{
"code": "import networkx as nximport randomimport matplotlib.pyplot as plt def first_community(G): for i in range(1, 11): G.add_node(i) for i in range(1, 11): for j in range(1, 11): if (i < j): r = random.random() if (r < 0.5): G.add_edge(i, j) return G def second_community(G): for i in range(11, 21): G.add_node(i) for i in range(11, 21): for j in range(11, 21): if (i < j): r = random.random() if (r < 0.5): G.add_edge(i, j) return G G = nx.Graph()G = first_community(G)G = second_community(G)G.add_edge(5, 15) nx.draw(G, with_labels=1)plt.show() nx.write_gml(G, \"community.gml\")",
"e": 31467,
"s": 30718,
"text": null
},
{
"code": null,
"e": 31475,
"s": 31467,
"text": "Output:"
},
{
"code": null,
"e": 31494,
"s": 31475,
"text": "Impact on clusters"
},
{
"code": null,
"e": 31520,
"s": 31494,
"text": "4. Cascading on Clusters."
},
{
"code": null,
"e": 31528,
"s": 31520,
"text": "Python3"
},
{
"code": "import networkx as nximport matplotlib.pyplot as plt def set_all_B(G): for i in G.nodes(): G.nodes[i]['action'] = 'B' return G def set_A(G, list1): for i in list1: G.nodes[i]['action'] = 'A' return G def get_colors(G): color = [] for i in G.nodes(): if (G.nodes[i]['action'] == 'B'): color.append('red') else: color.append('green') return color def recalculate(G): dict1 = {} a = 3 b = 2 for i in G.nodes(): neigh = G.neighbors(i) count_A = 0 count_B = 0 for j in neigh: if (G.nodes[j]['action'] == 'A'): count_A += 1 else: count_B += 1 payoff_A = a * count_A payoff_B = b * count_B if (payoff_A >= payoff_B): dict1[i] = 'A' else: dict1[i] = 'B' return dict1 def reset_node_attributes(G, action_dict): for i in action_dict: G.nodes[i]['action'] = action_dict[i] return G def Calculate(G): terminate = True count = 0 c = 0 while (terminate and count < 100): count += 1 # action_dict will hold a dictionary action_dict = recalculate(G) G = reset_node_attributes(G, action_dict) colors = get_colors(G) if (colors.count('red') == len(colors) or colors.count('green') == len(colors)): terminate = False if (colors.count('green') == len(colors)): c = 1 if (c == 1): print('cascade complete') else: print('cascade incomplete') nx.draw(G, with_labels=1, node_color=colors, node_size=800) plt.show() G = nx.Graph()G.add_nodes_from(range(13))G.add_edges_from( [(0, 1), (0, 6), (1, 2), (1, 8), (1, 12), (2, 9), (2, 12), (3, 4), (3, 9), (3, 12), (4, 5), (4, 12), (5, 6), (5, 10), (6, 8), (7, 8), (7, 9), (7, 10), (7, 11), (8, 9), (8, 10), (8, 11), (9, 10), (9, 11), (10, 11)]) list2 = [[0, 1, 2, 3], [0, 2, 3, 4], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 12], [2, 3, 4, 12], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5, 6, 12]] for list1 in list2: print(list1) G = set_all_B(G) G = set_A(G, list1) colors = get_colors(G) nx.draw(G, with_labels=1, node_color=colors, node_size=800) plt.show() Calculate(G)",
"e": 33874,
"s": 31528,
"text": null
},
{
"code": null,
"e": 33882,
"s": 33874,
"text": "Output:"
},
{
"code": null,
"e": 34190,
"s": 33882,
"text": "[0, 1, 2, 3]\ncascade incomplete\n[0, 2, 3, 4]\ncascade incomplete\n[1, 2, 3, 4]\ncascade incomplete\n[2, 3, 4, 5]\ncascade incomplete\n[3, 4, 5, 6]\ncascade incomplete\n[4, 5, 6, 12]\ncascade incomplete\n[2, 3, 4, 12]\ncascade incomplete\n[0, 1, 2, 3, 4, 5]\ncascade incomplete\n[0, 1, 2, 3, 4, 5, 6, 12]\ncascade complete\n"
},
{
"code": null,
"e": 34208,
"s": 34190,
"text": "Python-Networking"
},
{
"code": null,
"e": 34223,
"s": 34208,
"text": "python-utility"
},
{
"code": null,
"e": 34230,
"s": 34223,
"text": "Python"
},
{
"code": null,
"e": 34328,
"s": 34230,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34360,
"s": 34328,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 34402,
"s": 34360,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 34458,
"s": 34402,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 34500,
"s": 34458,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 34555,
"s": 34500,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 34586,
"s": 34555,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 34608,
"s": 34586,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 34637,
"s": 34608,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 34676,
"s": 34637,
"text": "Python | Get unique values from a list"
}
] |
How to Update Data in Realm Database in Android? - GeeksforGeeks
|
19 Aug, 2021
In previous articles, we have seen adding and reading data from our realm database in Android. In that article, we were adding course details in our database and reading the data in the form of a list. In this article, we will take a look at updating this data in our android app.
We will be working on the existing application which we build in our previous articles. In that, we will be simply creating a new activity in that we will be creating a form for updating our course details. Below is the video in which we will get to see what we are going to build in this article.
Step 1: Creating a new activity for updating our course
As we want to update our course, so for this process we will be creating a new activity where we will be able to update our courses in the SQLite database. To create a new Activity we have to navigate to the app > java > your app’s package name > Right click on package name > New > Empty Activity and name your activity as UpdateCourseActivity and create new Activity. Make sure to select the empty activity.
Step 2: Add google repository in the build.gradle file of the application project.
buildscript {
repositories {
google()
mavenCentral()
}
All Jetpack components are available in the Google Maven repository, include them in the build.gradle file
allprojects {
repositories {
google()
mavenCentral()
}
}
Step 3: Updating our CourseRVAdapter.java class
As we will be opening a new activity to update our course. We have to add on click listener for the items of our RecycleView. For adding onClickListener() to our recycler view items navigate to the app > java > your app’s package name > CourseRVAdapter class and simply add an onClickListener() for our RecyclerView item. Add the below code to your adapter class.
Java
// adding on click listener for item of recycler view.holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are creating a new intent. Intent i = new Intent(context, UpdateCourseActivity.class); // on below line we are passing all the data to new activity. i.putExtra("courseName", modal.getCourseName()); i.putExtra("courseDescription", modal.getCourseDescription()); i.putExtra("courseDuration", modal.getCourseDuration()); i.putExtra("courseTracks", modal.getCourseTracks()); i.putExtra("id", modal.getId()); // on below line we are starting a new activity. context.startActivity(i); }});
Below is the updated code for the CourseRVAdapter.java file after adding the above code snippet.
Java
import android.content.Context;import android.content.Intent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> { // variable for our array list and context private List<DataModal> dataModalArrayList; private Context context; public CourseRVAdapter(List<DataModal> dataModalArrayList, Context context) { this.dataModalArrayList = dataModalArrayList; this.context = context; } @NonNull @Override public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // on below line we are inflating our layout // file for our recycler view items. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) { DataModal modal = dataModalArrayList.get(position); holder.courseNameTV.setText(modal.getCourseName()); holder.courseDescTV.setText(modal.getCourseDescription()); holder.courseDurationTV.setText(modal.getCourseDuration()); holder.courseTracksTV.setText(modal.getCourseTracks()); // adding on click listener for item of recycler view. holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are creating a new intent. Intent i = new Intent(context, UpdateCourseActivity.class); // on below line we are passing all the data to new activity. i.putExtra("courseName", modal.getCourseName()); i.putExtra("courseDescription", modal.getCourseDescription()); i.putExtra("courseDuration", modal.getCourseDuration()); i.putExtra("courseTracks", modal.getCourseTracks()); i.putExtra("id", modal.getId()); // on below line we are starting a new activity. context.startActivity(i); } }); } @Override public int getItemCount() { return dataModalArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { // creating variables for our text views. private TextView courseNameTV, courseDescTV, courseDurationTV, courseTracksTV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing our text views courseNameTV = itemView.findViewById(R.id.idTVCourseName); courseDescTV = itemView.findViewById(R.id.idTVCourseDescription); courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration); courseTracksTV = itemView.findViewById(R.id.idTVCourseTracks); } }}
Step 4: Working with the activity_update_course.xml file
Navigate to the app > res > Layout > activity_update_course.xml and add the below code to it.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".UpdateCourseActivity"> <!--Edit text to enter course name--> <EditText android:id="@+id/idEdtCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Enter Course Name" /> <!--edit text to enter course duration--> <EditText android:id="@+id/idEdtCourseDuration" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Enter Course Duration" /> <!--edit text to display course tracks--> <EditText android:id="@+id/idEdtCourseTracks" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Enter Course Tracks" /> <!--edit text for course description--> <EditText android:id="@+id/idEdtCourseDescription" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Enter Course Description" /> <!--button for updating course--> <Button android:id="@+id/idBtnUpdateCourse" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:text="Update Course" android:textAllCaps="false" /> </LinearLayout>
Step 5: Working with the UpdateCourseActivity.java file
Navigate to the app > java > your app’s package name > UpdateCourseActivity.java file and add the below code to it. Comments are added inside the code to understand the code in more detail.
Java
import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import io.realm.Realm; public class UpdateCourseActivity extends AppCompatActivity { // creating variables for our edit text private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt, courseTracksEdt; // creating a strings for storing // our values from edittext fields. private String courseName, courseDuration, courseDescription, courseTracks; private long id; private Button updateCourseBtn; private Realm realm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_course); // initializing our edittext and buttons realm = Realm.getDefaultInstance(); courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription); courseDurationEdt = findViewById(R.id.idEdtCourseDuration); courseTracksEdt = findViewById(R.id.idEdtCourseTracks); updateCourseBtn = findViewById(R.id.idBtnUpdateCourse); // on below line we are getting data which is passed from intent. courseName = getIntent().getStringExtra("courseName"); courseDuration = getIntent().getStringExtra("courseDuration"); courseDescription = getIntent().getStringExtra("courseDescription"); courseTracks = getIntent().getStringExtra("courseTracks"); id = getIntent().getLongExtra("id", 0); // on below line we are setting data in our edit test fields. courseNameEdt.setText(courseName); courseDurationEdt.setText(courseDuration); courseDescriptionEdt.setText(courseDescription); courseTracksEdt.setText(courseTracks); // adding on click listener for update button. updateCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // getting data from edittext fields. String courseName = courseNameEdt.getText().toString(); String courseDescription = courseDescriptionEdt.getText().toString(); String courseDuration = courseDurationEdt.getText().toString(); String courseTracks = courseTracksEdt.getText().toString(); // validating the text fields if empty or not. if (TextUtils.isEmpty(courseName)) { courseNameEdt.setError("Please enter Course Name"); } else if (TextUtils.isEmpty(courseDescription)) { courseDescriptionEdt.setError("Please enter Course Description"); } else if (TextUtils.isEmpty(courseDuration)) { courseDurationEdt.setError("Please enter Course Duration"); } else if (TextUtils.isEmpty(courseTracks)) { courseTracksEdt.setError("Please enter Course Tracks"); } else { // on below line we are getting data from our modal where // the id of the course equals to which we passed previously. final DataModal modal = realm.where(DataModal.class).equalTo("id", id).findFirst(); updateCourse(modal, courseName, courseDescription, courseDuration, courseTracks); } // on below line we are displaying a toast message when course is updated. Toast.makeText(UpdateCourseActivity.this, "Course Updated.", Toast.LENGTH_SHORT).show(); // on below line we are opening our activity for read course activity to view updated course. Intent i = new Intent(UpdateCourseActivity.this, ReadCoursesActivity.class); startActivity(i); finish(); } }); } private void updateCourse(DataModal modal, String courseName, String courseDescription, String courseDuration, String courseTracks) { // on below line we are calling // a method to execute a transaction. realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { // on below line we are setting data to our modal class // which we get from our edit text fields. modal.setCourseDescription(courseDescription); modal.setCourseName(courseName); modal.setCourseDuration(courseDuration); modal.setCourseTracks(courseTracks); // inside on execute method we are calling a method to copy // and update to real m database from our modal class. realm.copyToRealmOrUpdate(modal); } }); }}
Now run your app and see the output of the app:
Output:
Below is the complete project file structure after performing the update operation:
AmiyaRanjanRout
hemantjain99
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Android Listview in Java with Example
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
|
[
{
"code": null,
"e": 24725,
"s": 24697,
"text": "\n19 Aug, 2021"
},
{
"code": null,
"e": 25007,
"s": 24725,
"text": "In previous articles, we have seen adding and reading data from our realm database in Android. In that article, we were adding course details in our database and reading the data in the form of a list. In this article, we will take a look at updating this data in our android app. "
},
{
"code": null,
"e": 25306,
"s": 25007,
"text": "We will be working on the existing application which we build in our previous articles. In that, we will be simply creating a new activity in that we will be creating a form for updating our course details. Below is the video in which we will get to see what we are going to build in this article. "
},
{
"code": null,
"e": 25362,
"s": 25306,
"text": "Step 1: Creating a new activity for updating our course"
},
{
"code": null,
"e": 25773,
"s": 25362,
"text": "As we want to update our course, so for this process we will be creating a new activity where we will be able to update our courses in the SQLite database. To create a new Activity we have to navigate to the app > java > your app’s package name > Right click on package name > New > Empty Activity and name your activity as UpdateCourseActivity and create new Activity. Make sure to select the empty activity. "
},
{
"code": null,
"e": 25856,
"s": 25773,
"text": "Step 2: Add google repository in the build.gradle file of the application project."
},
{
"code": null,
"e": 25870,
"s": 25856,
"text": "buildscript {"
},
{
"code": null,
"e": 25887,
"s": 25870,
"text": " repositories {"
},
{
"code": null,
"e": 25902,
"s": 25887,
"text": " google()"
},
{
"code": null,
"e": 25923,
"s": 25902,
"text": " mavenCentral()"
},
{
"code": null,
"e": 25926,
"s": 25923,
"text": " }"
},
{
"code": null,
"e": 26033,
"s": 25926,
"text": "All Jetpack components are available in the Google Maven repository, include them in the build.gradle file"
},
{
"code": null,
"e": 26047,
"s": 26033,
"text": "allprojects {"
},
{
"code": null,
"e": 26064,
"s": 26047,
"text": " repositories {"
},
{
"code": null,
"e": 26079,
"s": 26064,
"text": " google()"
},
{
"code": null,
"e": 26099,
"s": 26079,
"text": " mavenCentral()"
},
{
"code": null,
"e": 26103,
"s": 26099,
"text": " }"
},
{
"code": null,
"e": 26105,
"s": 26103,
"text": "}"
},
{
"code": null,
"e": 26153,
"s": 26105,
"text": "Step 3: Updating our CourseRVAdapter.java class"
},
{
"code": null,
"e": 26518,
"s": 26153,
"text": "As we will be opening a new activity to update our course. We have to add on click listener for the items of our RecycleView. For adding onClickListener() to our recycler view items navigate to the app > java > your app’s package name > CourseRVAdapter class and simply add an onClickListener() for our RecyclerView item. Add the below code to your adapter class. "
},
{
"code": null,
"e": 26523,
"s": 26518,
"text": "Java"
},
{
"code": "// adding on click listener for item of recycler view.holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are creating a new intent. Intent i = new Intent(context, UpdateCourseActivity.class); // on below line we are passing all the data to new activity. i.putExtra(\"courseName\", modal.getCourseName()); i.putExtra(\"courseDescription\", modal.getCourseDescription()); i.putExtra(\"courseDuration\", modal.getCourseDuration()); i.putExtra(\"courseTracks\", modal.getCourseTracks()); i.putExtra(\"id\", modal.getId()); // on below line we are starting a new activity. context.startActivity(i); }});",
"e": 27363,
"s": 26523,
"text": null
},
{
"code": null,
"e": 27460,
"s": 27363,
"text": "Below is the updated code for the CourseRVAdapter.java file after adding the above code snippet."
},
{
"code": null,
"e": 27465,
"s": 27460,
"text": "Java"
},
{
"code": "import android.content.Context;import android.content.Intent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> { // variable for our array list and context private List<DataModal> dataModalArrayList; private Context context; public CourseRVAdapter(List<DataModal> dataModalArrayList, Context context) { this.dataModalArrayList = dataModalArrayList; this.context = context; } @NonNull @Override public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // on below line we are inflating our layout // file for our recycler view items. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) { DataModal modal = dataModalArrayList.get(position); holder.courseNameTV.setText(modal.getCourseName()); holder.courseDescTV.setText(modal.getCourseDescription()); holder.courseDurationTV.setText(modal.getCourseDuration()); holder.courseTracksTV.setText(modal.getCourseTracks()); // adding on click listener for item of recycler view. holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are creating a new intent. Intent i = new Intent(context, UpdateCourseActivity.class); // on below line we are passing all the data to new activity. i.putExtra(\"courseName\", modal.getCourseName()); i.putExtra(\"courseDescription\", modal.getCourseDescription()); i.putExtra(\"courseDuration\", modal.getCourseDuration()); i.putExtra(\"courseTracks\", modal.getCourseTracks()); i.putExtra(\"id\", modal.getId()); // on below line we are starting a new activity. context.startActivity(i); } }); } @Override public int getItemCount() { return dataModalArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { // creating variables for our text views. private TextView courseNameTV, courseDescTV, courseDurationTV, courseTracksTV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing our text views courseNameTV = itemView.findViewById(R.id.idTVCourseName); courseDescTV = itemView.findViewById(R.id.idTVCourseDescription); courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration); courseTracksTV = itemView.findViewById(R.id.idTVCourseTracks); } }}",
"e": 30526,
"s": 27465,
"text": null
},
{
"code": null,
"e": 30583,
"s": 30526,
"text": "Step 4: Working with the activity_update_course.xml file"
},
{
"code": null,
"e": 30678,
"s": 30583,
"text": "Navigate to the app > res > Layout > activity_update_course.xml and add the below code to it. "
},
{
"code": null,
"e": 30682,
"s": 30678,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".UpdateCourseActivity\"> <!--Edit text to enter course name--> <EditText android:id=\"@+id/idEdtCourseName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"Enter Course Name\" /> <!--edit text to enter course duration--> <EditText android:id=\"@+id/idEdtCourseDuration\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"Enter Course Duration\" /> <!--edit text to display course tracks--> <EditText android:id=\"@+id/idEdtCourseTracks\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"Enter Course Tracks\" /> <!--edit text for course description--> <EditText android:id=\"@+id/idEdtCourseDescription\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"Enter Course Description\" /> <!--button for updating course--> <Button android:id=\"@+id/idBtnUpdateCourse\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:text=\"Update Course\" android:textAllCaps=\"false\" /> </LinearLayout>",
"e": 32390,
"s": 30682,
"text": null
},
{
"code": null,
"e": 32447,
"s": 32390,
"text": "Step 5: Working with the UpdateCourseActivity.java file "
},
{
"code": null,
"e": 32637,
"s": 32447,
"text": "Navigate to the app > java > your app’s package name > UpdateCourseActivity.java file and add the below code to it. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 32642,
"s": 32637,
"text": "Java"
},
{
"code": "import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import io.realm.Realm; public class UpdateCourseActivity extends AppCompatActivity { // creating variables for our edit text private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt, courseTracksEdt; // creating a strings for storing // our values from edittext fields. private String courseName, courseDuration, courseDescription, courseTracks; private long id; private Button updateCourseBtn; private Realm realm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_course); // initializing our edittext and buttons realm = Realm.getDefaultInstance(); courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription); courseDurationEdt = findViewById(R.id.idEdtCourseDuration); courseTracksEdt = findViewById(R.id.idEdtCourseTracks); updateCourseBtn = findViewById(R.id.idBtnUpdateCourse); // on below line we are getting data which is passed from intent. courseName = getIntent().getStringExtra(\"courseName\"); courseDuration = getIntent().getStringExtra(\"courseDuration\"); courseDescription = getIntent().getStringExtra(\"courseDescription\"); courseTracks = getIntent().getStringExtra(\"courseTracks\"); id = getIntent().getLongExtra(\"id\", 0); // on below line we are setting data in our edit test fields. courseNameEdt.setText(courseName); courseDurationEdt.setText(courseDuration); courseDescriptionEdt.setText(courseDescription); courseTracksEdt.setText(courseTracks); // adding on click listener for update button. updateCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // getting data from edittext fields. String courseName = courseNameEdt.getText().toString(); String courseDescription = courseDescriptionEdt.getText().toString(); String courseDuration = courseDurationEdt.getText().toString(); String courseTracks = courseTracksEdt.getText().toString(); // validating the text fields if empty or not. if (TextUtils.isEmpty(courseName)) { courseNameEdt.setError(\"Please enter Course Name\"); } else if (TextUtils.isEmpty(courseDescription)) { courseDescriptionEdt.setError(\"Please enter Course Description\"); } else if (TextUtils.isEmpty(courseDuration)) { courseDurationEdt.setError(\"Please enter Course Duration\"); } else if (TextUtils.isEmpty(courseTracks)) { courseTracksEdt.setError(\"Please enter Course Tracks\"); } else { // on below line we are getting data from our modal where // the id of the course equals to which we passed previously. final DataModal modal = realm.where(DataModal.class).equalTo(\"id\", id).findFirst(); updateCourse(modal, courseName, courseDescription, courseDuration, courseTracks); } // on below line we are displaying a toast message when course is updated. Toast.makeText(UpdateCourseActivity.this, \"Course Updated.\", Toast.LENGTH_SHORT).show(); // on below line we are opening our activity for read course activity to view updated course. Intent i = new Intent(UpdateCourseActivity.this, ReadCoursesActivity.class); startActivity(i); finish(); } }); } private void updateCourse(DataModal modal, String courseName, String courseDescription, String courseDuration, String courseTracks) { // on below line we are calling // a method to execute a transaction. realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { // on below line we are setting data to our modal class // which we get from our edit text fields. modal.setCourseDescription(courseDescription); modal.setCourseName(courseName); modal.setCourseDuration(courseDuration); modal.setCourseTracks(courseTracks); // inside on execute method we are calling a method to copy // and update to real m database from our modal class. realm.copyToRealmOrUpdate(modal); } }); }}",
"e": 37703,
"s": 32642,
"text": null
},
{
"code": null,
"e": 37752,
"s": 37703,
"text": "Now run your app and see the output of the app: "
},
{
"code": null,
"e": 37760,
"s": 37752,
"text": "Output:"
},
{
"code": null,
"e": 37844,
"s": 37760,
"text": "Below is the complete project file structure after performing the update operation:"
},
{
"code": null,
"e": 37860,
"s": 37844,
"text": "AmiyaRanjanRout"
},
{
"code": null,
"e": 37873,
"s": 37860,
"text": "hemantjain99"
},
{
"code": null,
"e": 37881,
"s": 37873,
"text": "Android"
},
{
"code": null,
"e": 37886,
"s": 37881,
"text": "Java"
},
{
"code": null,
"e": 37891,
"s": 37886,
"text": "Java"
},
{
"code": null,
"e": 37899,
"s": 37891,
"text": "Android"
},
{
"code": null,
"e": 37997,
"s": 37899,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38006,
"s": 37997,
"text": "Comments"
},
{
"code": null,
"e": 38019,
"s": 38006,
"text": "Old Comments"
},
{
"code": null,
"e": 38058,
"s": 38019,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 38108,
"s": 38058,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 38146,
"s": 38108,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 38197,
"s": 38146,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 38239,
"s": 38197,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 38254,
"s": 38239,
"text": "Arrays in Java"
},
{
"code": null,
"e": 38298,
"s": 38254,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 38320,
"s": 38298,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 38345,
"s": 38320,
"text": "Reverse a string in Java"
}
] |
How to extract online data using Python | by Euge Inzaugarat | Towards Data Science
|
“I would be nice to have all the documents of the website” — One of her colleagues said
“Yeah, that could give us a lot of information” — Said another colleague
“Can you do the scraper?” — They both turn to look at her
“Ehhhh... I could....” — She started mumbling
“Perfect” — They both said
“....try” —She finished saying but it was too late
She had never done a scraper in her life. So she was pretty overwhelmed at the moment.
“I don’t know what to do” — She called me crying — “I think that it is too hard for me to do it”
“You don’t worry! We can do it together” — I said
I understood her completely. The first time I had to code a scraper I felt lost as well.
It was like I was watching a magic trick. I remember when I start reading about scraping.
“Web scrapers...mm... HTML tags...mm... spiders... What....?” — It sounded like a foreign language to me
But the more I read, the more I began to understand that like magic, you need to know what to look for to understand the trick.
What is a web scraper anyway? A web scraper is a program that automatically gathers data off of websites.
We can collect all the content of a website or just specific data about a topic or element. This will depend on the parameters we set in our script. This versatility is the beauty of web scrapers.
Let’s set a hypothetical example. We want to scrape data from a website which URL is https://www.mainwebsite.com. Particularly, this website contains different documents. We are interested in getting their text.
In the main page, we find three subsections as you can see in the drawing below.
Clicking topic1, for example, we’ll take us to another page (https://www.mainwebsite.com/topic1) where we can find a list of documents we are interested in.
If we click on document1, we’ll end up on another page (https://www.mainwebsite.com/topic1/document1/date) where we can obtain the content of that document.
If we were to do it manually, we would copy and paste the content in a file. Instead, we are going to automate this process.
We saw the path we need to follow to get our data. Now, we should find a way to tell the web scraper where to look for the information.
There is a lot of data on the website, such as images, links to other pages, and headers, we are not interested in. As a consequence, we need to be very specific.
Here is where we start to unravel the magic trick. Let’s dissect it then.
1HTML stands for Hypertext Markup Language. Along with Cascading Style Sheets (CSS) and Javascript, it is used for structuring and presenting content on interactive websites.
You don’t need to learn how to code using HTML to build a scraper. But you should know how to identify HTML tags and elements.
Why? Because the data will have a specific HTML tag. And we can extract this data by just showing the scraper the correct HTML element to look for.
An HTML tag consists of a tag name enclosed by angular brackets. Frequently, you need an opening and an ending tag that frame a particular piece of text.
The opening tag consists of a name, followed by optional attributes. The ending tag consists of the same name preceded by a forward slash (/).
Each tag name refers to a particular element. We would pay attention to the following tags: <p> for paragraphs; <a> or anchor tag for hyperlinks; <img> for images; <h1>, <h2>, etc. for text headers; <div> for dividers, <tr> for table rows, and <td> for table columns.
Most tags also take id or class attributes. The id specifies a unique id for that HTML tag within the HTML document. The class is used to define which style that tag would take.
Let’s observe an HTML element:
In this case, we want to extract “28th June 2019 Edition”, the content of the HTML element. We would tell the scraper: look for all <h6> elements and give me the one with class “text-primary”.
If there is more than one element with these characteristics, we would need to be more specific. Indicating the ID attribute can accomplish this.
OK. But where do I look for this information on a website?
This is an easy step: Right-click anywhere on the webpage. A small window will appear. Next, you click Inspect like in the image below.
You’ll have access to the website source code, the images, the CSS, the fonts and icons it uses, the Javascript code.
Moreover, you can use the cursor selector (see the images below) to select an item in the website.
As a consequence, the HTML element corresponding to the selected item will be highlighted.
In the above diagram, we can observe what a typical HTML structure looks like.
Normally, all the content is included inside the opening and closing body tags. Every element has its own tags.
Some HTML elements are nested inside others giving a hierarchy. This can be represented in a tree.
If we move from left to right in the tree, we move forwards generations. If we move top to bottom, we move between the same generation or between siblings when they come from the same parent element.
Pay attention to the two <div> elements. They are siblings because they share <body> as a parent. They are the second descendant of html element. Each of them has children. The first <div> has two children. Its first child is a paragraph containing “Web scraping is useful!” element. However, this element is not a descendant of the second <div>. This is due to the fact that you can not follow a path from this div element to the paragraph element.
These relationships will help us also when indicating the desired element to the web scraper.
2XPath stands for XML Path Language. What does it have to do with web scraping? We’ll learn how to identify HTML elements. But the question that arises now is how do I point out the element to the scraper? And the answer is XPath.
XPath is a special syntax that can be used to navigate through elements and attributes in an XML document. Also, it will help us get a path to a certain HTML element and extract its content.
Let’s see how this syntax works.
/ is used to move forward one generation, tag-names gives the direction to which element, [] tell us which of the siblings to choose, // looks for all future generations, @ selects attributes, * is a wildcard indicating we want to ignore tag types.
If we see the following XPath:
Xpath = '//div[@class="first"]/p[2]'
we would understand that from all (//) the div elements with class “first” (div[@class="first"]), we want the second ([2]) paragraph (p) element.
Fortunately, web browsers have an easy way to get the XPath of an element.
When you are inspecting the website, right-click in the highlighted element. A small window will be displayed. You can then copy the XPath.
3Scrapy is a Python framework designed for crawling web sites and extracting structured data. It was specially designed for web scraping but nowadays it can also be used to extract data using APIs.
In order to install Scrapy, you need to have Python installed. It is advisable to work only with Python 3. Python 2 is going to be deprecated in January 2020.
To install Scrapy, you can do it using pip:
pip install Scrapy
or using conda
conda install -c conda-forge scrapy
One important aspect of Scrapy is that it uses Twisted, a popular event-driven networking framework for Python. Twisted works asynchronously for concurrency.
What does this mean? Synchronous means that you have to wait for a job to be completed in order to start a new job. Asynchronous means you can move to another job before the previous job has finished.
4Spiders. Because of this characteristic, Scrapy can crawl a group of URLs in a very short time. Consequently, instead of scraping on a single website, Scrapy works with spiders.
Spiders are classes we define and Scrapy uses to crawl multiple pages following links and scrape information.
Spiders must meet certain requirements to work correctly. They must subclass scrapy.Spider, and define the initial requests to make. Also, they can determine how to follow in the pages and how to parse the downloaded page content.
Let’s see these requirements in detail:
Every spider must be a subclass of the scrapy.Spider class: This means that it must take it as an argument.The name of the Spider must be unique within a project.They must define the initial requests to make: There must be a method call start_requests(). Scrapy will always look for it to initiate the requests. It also must return an iterable of Requests which the Spider will begin to crawl from.They can determine how to parse the downloaded content: Normally, a parse() method is defined. We call it to handle the response downloaded for each of the requests made. The parse() method usually parses the response, extracting the scraped data and also finding new URLs to follow and creating new requests from them.We can also find the allowed_domains list. This tells the spider what are the domain names that it is allowed to scrape.Also, we can seta start_urls list. It is used to specify what website we want to scrape. By default, Scrapy uses the HTTP protocol. It has to be changed to https.
Every spider must be a subclass of the scrapy.Spider class: This means that it must take it as an argument.
The name of the Spider must be unique within a project.
They must define the initial requests to make: There must be a method call start_requests(). Scrapy will always look for it to initiate the requests. It also must return an iterable of Requests which the Spider will begin to crawl from.
They can determine how to parse the downloaded content: Normally, a parse() method is defined. We call it to handle the response downloaded for each of the requests made. The parse() method usually parses the response, extracting the scraped data and also finding new URLs to follow and creating new requests from them.
We can also find the allowed_domains list. This tells the spider what are the domain names that it is allowed to scrape.
Also, we can seta start_urls list. It is used to specify what website we want to scrape. By default, Scrapy uses the HTTP protocol. It has to be changed to https.
Now, we have dissected all the components of a web scraper.
→ It’s time to write it!! ←
We’ll bring our initial example of the website with URL https://www.mainwebsite.com.
Let’s review the facts:
We have a main website with three links to three different sections.
In each section, we have a list of links to documents. Each section has a specific URL, e.g.https://www.mainwebsite.com/topic1.
Every link takes us to the document content that we are interested in. We can find every link in the HTML structure of each section.
First, we’ll design our file architecture.
Let’s explore our folders.
We’ve created a master folder called scraper where we are going to store all the files related to our scraper.
Then, we’ll collect all the scraped data in JSON files. Each of those files will be saved in the JSON folder.
The common folder has another folder called spiders. There, we’ll save one file for each spider. And we’ll create one spider for each topic. So, in total three spiders.
Now, it’s time to understand the files we’ve created.
Let’s start with the settings.py. The Scrapy settings allow us to customize the behavior of all Scrapy components, including the core, extensions, pipelines, and spiders themselves.
There, we can specify The name of the bot implemented by the Scrapy project, a list of modules where Scrapy will look for spiders and whether the HTTP cache will be enabled, among others.
Now, we arrive at the main two files.
AWe’ll start by the topic1.py spider. We’ll examine only one example as they are all very similar.
The first thing that we need to do is import all the needed libraries.
Obviously, we need to import scrapy. The re module will allow us to extract information using regular expressions. The json module will help us when saving information. The os module is useful to handle directories.
We stated before that a spider has to inherit from the scrapy.Spider. So we'll create a class called FirstSpider that subclass it. We’ll assign the name topic1. Then, we’ll define the allowed_domains list.
We also need to create the start_request() method to initialize the requests. Inside the method, we define a list of URL for the requests. In our case, this list only contains the URL www.mainwebsite.com/topic1. Then, we are going to make a request with scrapy.Request.
We’ll use yield instead of return. We’ll tell scrapy to handle the downloaded content using the parse() method inside the callback argument.
Until now, you might think that the explanation about HTML and XPath was quite useless. Well, now it’s the moment we’ll need it.
After we define our method to start the initial request, we need to define the method that will handle our downloaded information.
So in other words, we need to decide what we want to do with all the data. What information is worth it to save.
For this, let’s suppose this is the HTML structure of our website.
As you can see in the picture, the highlighted element is the element we need to get to extract our links.
Let’s construct our path to get there. From all (//) thediv elements that have the class col-md-12 (div[@class='col-md-12']), we need the attribute href from the a children (a/@href).
So, we have then our XPath: //div[@class='col-md-12']/a/@href.
In our parse method, we'll use response.xpath() to indicate the path and extract() to extract the content of every element.
We are expecting to get a list of links. We want to extract what is shown in those links. The spider will need to follow each of them and parse their content using a second parse method that we’ll call parse_first.
Notice that this time we are sending the links using follow in the response variable instead of creating a Request.
Next, the parse_first method has to be defined to tell the spider how to follow the links.
We are going to extract the title and the body of the document.
After exploring the HTML structure of one document, we’ll get any element which id is titleDocument, and all paragraphs that are a child of any element which id is BodyDocument.
Because we don’t care about which tag they have we’ll use the *.
After getting each paragraph, we are going to append them to a list.
After that, we’ll join all the paragraphs in the text list together. We’ll extract the date. Finally, we’ll define a dictionary with the date, title and text.
Lastly, we’ll save the data into a JSON file.
Here it’s the definition of the function extractdate where we’ll use regular expressions to extract the date.
Now, our spider is complete.
BIt’s time to investigate the scraper.py file. Not only we need to create spiders, but also we need to launch them.
First, we’ll import the required modules from Scrapy. CrawlerProcess will initiate the crawling process and settings will allow us to arrange the settings.
We’ll also import the three spider class created for each topic.
After that, we initiate a crawling process
We tell the process which spiders to use and finally, we’ll start the crawling.
Perfect! We now have our scraper built!!!
But wait how do we actually start scraping our website?
In the terminal, we navigate with command line to our scraper folder (using cd). Once inside, we just launch the spiders with the python3 command you can see in the picture.
And voilà! The spiders are crawling the website!
Here, I listed a couple of very nice resources and courses to learn more about web scraping:
DataCamp Course.Web Scraping tutorialScrapy documentationHTML long and short explanation
DataCamp Course.
Web Scraping tutorial
Scrapy documentation
HTML long and short explanation
Some rights reserved
|
[
{
"code": null,
"e": 259,
"s": 171,
"text": "“I would be nice to have all the documents of the website” — One of her colleagues said"
},
{
"code": null,
"e": 332,
"s": 259,
"text": "“Yeah, that could give us a lot of information” — Said another colleague"
},
{
"code": null,
"e": 390,
"s": 332,
"text": "“Can you do the scraper?” — They both turn to look at her"
},
{
"code": null,
"e": 436,
"s": 390,
"text": "“Ehhhh... I could....” — She started mumbling"
},
{
"code": null,
"e": 463,
"s": 436,
"text": "“Perfect” — They both said"
},
{
"code": null,
"e": 514,
"s": 463,
"text": "“....try” —She finished saying but it was too late"
},
{
"code": null,
"e": 601,
"s": 514,
"text": "She had never done a scraper in her life. So she was pretty overwhelmed at the moment."
},
{
"code": null,
"e": 698,
"s": 601,
"text": "“I don’t know what to do” — She called me crying — “I think that it is too hard for me to do it”"
},
{
"code": null,
"e": 748,
"s": 698,
"text": "“You don’t worry! We can do it together” — I said"
},
{
"code": null,
"e": 837,
"s": 748,
"text": "I understood her completely. The first time I had to code a scraper I felt lost as well."
},
{
"code": null,
"e": 927,
"s": 837,
"text": "It was like I was watching a magic trick. I remember when I start reading about scraping."
},
{
"code": null,
"e": 1032,
"s": 927,
"text": "“Web scrapers...mm... HTML tags...mm... spiders... What....?” — It sounded like a foreign language to me"
},
{
"code": null,
"e": 1160,
"s": 1032,
"text": "But the more I read, the more I began to understand that like magic, you need to know what to look for to understand the trick."
},
{
"code": null,
"e": 1266,
"s": 1160,
"text": "What is a web scraper anyway? A web scraper is a program that automatically gathers data off of websites."
},
{
"code": null,
"e": 1463,
"s": 1266,
"text": "We can collect all the content of a website or just specific data about a topic or element. This will depend on the parameters we set in our script. This versatility is the beauty of web scrapers."
},
{
"code": null,
"e": 1675,
"s": 1463,
"text": "Let’s set a hypothetical example. We want to scrape data from a website which URL is https://www.mainwebsite.com. Particularly, this website contains different documents. We are interested in getting their text."
},
{
"code": null,
"e": 1756,
"s": 1675,
"text": "In the main page, we find three subsections as you can see in the drawing below."
},
{
"code": null,
"e": 1913,
"s": 1756,
"text": "Clicking topic1, for example, we’ll take us to another page (https://www.mainwebsite.com/topic1) where we can find a list of documents we are interested in."
},
{
"code": null,
"e": 2070,
"s": 1913,
"text": "If we click on document1, we’ll end up on another page (https://www.mainwebsite.com/topic1/document1/date) where we can obtain the content of that document."
},
{
"code": null,
"e": 2195,
"s": 2070,
"text": "If we were to do it manually, we would copy and paste the content in a file. Instead, we are going to automate this process."
},
{
"code": null,
"e": 2331,
"s": 2195,
"text": "We saw the path we need to follow to get our data. Now, we should find a way to tell the web scraper where to look for the information."
},
{
"code": null,
"e": 2494,
"s": 2331,
"text": "There is a lot of data on the website, such as images, links to other pages, and headers, we are not interested in. As a consequence, we need to be very specific."
},
{
"code": null,
"e": 2568,
"s": 2494,
"text": "Here is where we start to unravel the magic trick. Let’s dissect it then."
},
{
"code": null,
"e": 2743,
"s": 2568,
"text": "1HTML stands for Hypertext Markup Language. Along with Cascading Style Sheets (CSS) and Javascript, it is used for structuring and presenting content on interactive websites."
},
{
"code": null,
"e": 2870,
"s": 2743,
"text": "You don’t need to learn how to code using HTML to build a scraper. But you should know how to identify HTML tags and elements."
},
{
"code": null,
"e": 3018,
"s": 2870,
"text": "Why? Because the data will have a specific HTML tag. And we can extract this data by just showing the scraper the correct HTML element to look for."
},
{
"code": null,
"e": 3172,
"s": 3018,
"text": "An HTML tag consists of a tag name enclosed by angular brackets. Frequently, you need an opening and an ending tag that frame a particular piece of text."
},
{
"code": null,
"e": 3315,
"s": 3172,
"text": "The opening tag consists of a name, followed by optional attributes. The ending tag consists of the same name preceded by a forward slash (/)."
},
{
"code": null,
"e": 3583,
"s": 3315,
"text": "Each tag name refers to a particular element. We would pay attention to the following tags: <p> for paragraphs; <a> or anchor tag for hyperlinks; <img> for images; <h1>, <h2>, etc. for text headers; <div> for dividers, <tr> for table rows, and <td> for table columns."
},
{
"code": null,
"e": 3761,
"s": 3583,
"text": "Most tags also take id or class attributes. The id specifies a unique id for that HTML tag within the HTML document. The class is used to define which style that tag would take."
},
{
"code": null,
"e": 3792,
"s": 3761,
"text": "Let’s observe an HTML element:"
},
{
"code": null,
"e": 3985,
"s": 3792,
"text": "In this case, we want to extract “28th June 2019 Edition”, the content of the HTML element. We would tell the scraper: look for all <h6> elements and give me the one with class “text-primary”."
},
{
"code": null,
"e": 4131,
"s": 3985,
"text": "If there is more than one element with these characteristics, we would need to be more specific. Indicating the ID attribute can accomplish this."
},
{
"code": null,
"e": 4190,
"s": 4131,
"text": "OK. But where do I look for this information on a website?"
},
{
"code": null,
"e": 4326,
"s": 4190,
"text": "This is an easy step: Right-click anywhere on the webpage. A small window will appear. Next, you click Inspect like in the image below."
},
{
"code": null,
"e": 4444,
"s": 4326,
"text": "You’ll have access to the website source code, the images, the CSS, the fonts and icons it uses, the Javascript code."
},
{
"code": null,
"e": 4543,
"s": 4444,
"text": "Moreover, you can use the cursor selector (see the images below) to select an item in the website."
},
{
"code": null,
"e": 4634,
"s": 4543,
"text": "As a consequence, the HTML element corresponding to the selected item will be highlighted."
},
{
"code": null,
"e": 4713,
"s": 4634,
"text": "In the above diagram, we can observe what a typical HTML structure looks like."
},
{
"code": null,
"e": 4825,
"s": 4713,
"text": "Normally, all the content is included inside the opening and closing body tags. Every element has its own tags."
},
{
"code": null,
"e": 4924,
"s": 4825,
"text": "Some HTML elements are nested inside others giving a hierarchy. This can be represented in a tree."
},
{
"code": null,
"e": 5124,
"s": 4924,
"text": "If we move from left to right in the tree, we move forwards generations. If we move top to bottom, we move between the same generation or between siblings when they come from the same parent element."
},
{
"code": null,
"e": 5574,
"s": 5124,
"text": "Pay attention to the two <div> elements. They are siblings because they share <body> as a parent. They are the second descendant of html element. Each of them has children. The first <div> has two children. Its first child is a paragraph containing “Web scraping is useful!” element. However, this element is not a descendant of the second <div>. This is due to the fact that you can not follow a path from this div element to the paragraph element."
},
{
"code": null,
"e": 5668,
"s": 5574,
"text": "These relationships will help us also when indicating the desired element to the web scraper."
},
{
"code": null,
"e": 5899,
"s": 5668,
"text": "2XPath stands for XML Path Language. What does it have to do with web scraping? We’ll learn how to identify HTML elements. But the question that arises now is how do I point out the element to the scraper? And the answer is XPath."
},
{
"code": null,
"e": 6090,
"s": 5899,
"text": "XPath is a special syntax that can be used to navigate through elements and attributes in an XML document. Also, it will help us get a path to a certain HTML element and extract its content."
},
{
"code": null,
"e": 6123,
"s": 6090,
"text": "Let’s see how this syntax works."
},
{
"code": null,
"e": 6372,
"s": 6123,
"text": "/ is used to move forward one generation, tag-names gives the direction to which element, [] tell us which of the siblings to choose, // looks for all future generations, @ selects attributes, * is a wildcard indicating we want to ignore tag types."
},
{
"code": null,
"e": 6403,
"s": 6372,
"text": "If we see the following XPath:"
},
{
"code": null,
"e": 6440,
"s": 6403,
"text": "Xpath = '//div[@class=\"first\"]/p[2]'"
},
{
"code": null,
"e": 6586,
"s": 6440,
"text": "we would understand that from all (//) the div elements with class “first” (div[@class=\"first\"]), we want the second ([2]) paragraph (p) element."
},
{
"code": null,
"e": 6661,
"s": 6586,
"text": "Fortunately, web browsers have an easy way to get the XPath of an element."
},
{
"code": null,
"e": 6801,
"s": 6661,
"text": "When you are inspecting the website, right-click in the highlighted element. A small window will be displayed. You can then copy the XPath."
},
{
"code": null,
"e": 6999,
"s": 6801,
"text": "3Scrapy is a Python framework designed for crawling web sites and extracting structured data. It was specially designed for web scraping but nowadays it can also be used to extract data using APIs."
},
{
"code": null,
"e": 7158,
"s": 6999,
"text": "In order to install Scrapy, you need to have Python installed. It is advisable to work only with Python 3. Python 2 is going to be deprecated in January 2020."
},
{
"code": null,
"e": 7202,
"s": 7158,
"text": "To install Scrapy, you can do it using pip:"
},
{
"code": null,
"e": 7221,
"s": 7202,
"text": "pip install Scrapy"
},
{
"code": null,
"e": 7236,
"s": 7221,
"text": "or using conda"
},
{
"code": null,
"e": 7272,
"s": 7236,
"text": "conda install -c conda-forge scrapy"
},
{
"code": null,
"e": 7430,
"s": 7272,
"text": "One important aspect of Scrapy is that it uses Twisted, a popular event-driven networking framework for Python. Twisted works asynchronously for concurrency."
},
{
"code": null,
"e": 7631,
"s": 7430,
"text": "What does this mean? Synchronous means that you have to wait for a job to be completed in order to start a new job. Asynchronous means you can move to another job before the previous job has finished."
},
{
"code": null,
"e": 7810,
"s": 7631,
"text": "4Spiders. Because of this characteristic, Scrapy can crawl a group of URLs in a very short time. Consequently, instead of scraping on a single website, Scrapy works with spiders."
},
{
"code": null,
"e": 7920,
"s": 7810,
"text": "Spiders are classes we define and Scrapy uses to crawl multiple pages following links and scrape information."
},
{
"code": null,
"e": 8151,
"s": 7920,
"text": "Spiders must meet certain requirements to work correctly. They must subclass scrapy.Spider, and define the initial requests to make. Also, they can determine how to follow in the pages and how to parse the downloaded page content."
},
{
"code": null,
"e": 8191,
"s": 8151,
"text": "Let’s see these requirements in detail:"
},
{
"code": null,
"e": 9191,
"s": 8191,
"text": "Every spider must be a subclass of the scrapy.Spider class: This means that it must take it as an argument.The name of the Spider must be unique within a project.They must define the initial requests to make: There must be a method call start_requests(). Scrapy will always look for it to initiate the requests. It also must return an iterable of Requests which the Spider will begin to crawl from.They can determine how to parse the downloaded content: Normally, a parse() method is defined. We call it to handle the response downloaded for each of the requests made. The parse() method usually parses the response, extracting the scraped data and also finding new URLs to follow and creating new requests from them.We can also find the allowed_domains list. This tells the spider what are the domain names that it is allowed to scrape.Also, we can seta start_urls list. It is used to specify what website we want to scrape. By default, Scrapy uses the HTTP protocol. It has to be changed to https."
},
{
"code": null,
"e": 9299,
"s": 9191,
"text": "Every spider must be a subclass of the scrapy.Spider class: This means that it must take it as an argument."
},
{
"code": null,
"e": 9355,
"s": 9299,
"text": "The name of the Spider must be unique within a project."
},
{
"code": null,
"e": 9592,
"s": 9355,
"text": "They must define the initial requests to make: There must be a method call start_requests(). Scrapy will always look for it to initiate the requests. It also must return an iterable of Requests which the Spider will begin to crawl from."
},
{
"code": null,
"e": 9912,
"s": 9592,
"text": "They can determine how to parse the downloaded content: Normally, a parse() method is defined. We call it to handle the response downloaded for each of the requests made. The parse() method usually parses the response, extracting the scraped data and also finding new URLs to follow and creating new requests from them."
},
{
"code": null,
"e": 10033,
"s": 9912,
"text": "We can also find the allowed_domains list. This tells the spider what are the domain names that it is allowed to scrape."
},
{
"code": null,
"e": 10196,
"s": 10033,
"text": "Also, we can seta start_urls list. It is used to specify what website we want to scrape. By default, Scrapy uses the HTTP protocol. It has to be changed to https."
},
{
"code": null,
"e": 10256,
"s": 10196,
"text": "Now, we have dissected all the components of a web scraper."
},
{
"code": null,
"e": 10284,
"s": 10256,
"text": "→ It’s time to write it!! ←"
},
{
"code": null,
"e": 10369,
"s": 10284,
"text": "We’ll bring our initial example of the website with URL https://www.mainwebsite.com."
},
{
"code": null,
"e": 10393,
"s": 10369,
"text": "Let’s review the facts:"
},
{
"code": null,
"e": 10462,
"s": 10393,
"text": "We have a main website with three links to three different sections."
},
{
"code": null,
"e": 10590,
"s": 10462,
"text": "In each section, we have a list of links to documents. Each section has a specific URL, e.g.https://www.mainwebsite.com/topic1."
},
{
"code": null,
"e": 10723,
"s": 10590,
"text": "Every link takes us to the document content that we are interested in. We can find every link in the HTML structure of each section."
},
{
"code": null,
"e": 10766,
"s": 10723,
"text": "First, we’ll design our file architecture."
},
{
"code": null,
"e": 10793,
"s": 10766,
"text": "Let’s explore our folders."
},
{
"code": null,
"e": 10904,
"s": 10793,
"text": "We’ve created a master folder called scraper where we are going to store all the files related to our scraper."
},
{
"code": null,
"e": 11014,
"s": 10904,
"text": "Then, we’ll collect all the scraped data in JSON files. Each of those files will be saved in the JSON folder."
},
{
"code": null,
"e": 11183,
"s": 11014,
"text": "The common folder has another folder called spiders. There, we’ll save one file for each spider. And we’ll create one spider for each topic. So, in total three spiders."
},
{
"code": null,
"e": 11237,
"s": 11183,
"text": "Now, it’s time to understand the files we’ve created."
},
{
"code": null,
"e": 11419,
"s": 11237,
"text": "Let’s start with the settings.py. The Scrapy settings allow us to customize the behavior of all Scrapy components, including the core, extensions, pipelines, and spiders themselves."
},
{
"code": null,
"e": 11607,
"s": 11419,
"text": "There, we can specify The name of the bot implemented by the Scrapy project, a list of modules where Scrapy will look for spiders and whether the HTTP cache will be enabled, among others."
},
{
"code": null,
"e": 11645,
"s": 11607,
"text": "Now, we arrive at the main two files."
},
{
"code": null,
"e": 11744,
"s": 11645,
"text": "AWe’ll start by the topic1.py spider. We’ll examine only one example as they are all very similar."
},
{
"code": null,
"e": 11815,
"s": 11744,
"text": "The first thing that we need to do is import all the needed libraries."
},
{
"code": null,
"e": 12031,
"s": 11815,
"text": "Obviously, we need to import scrapy. The re module will allow us to extract information using regular expressions. The json module will help us when saving information. The os module is useful to handle directories."
},
{
"code": null,
"e": 12237,
"s": 12031,
"text": "We stated before that a spider has to inherit from the scrapy.Spider. So we'll create a class called FirstSpider that subclass it. We’ll assign the name topic1. Then, we’ll define the allowed_domains list."
},
{
"code": null,
"e": 12507,
"s": 12237,
"text": "We also need to create the start_request() method to initialize the requests. Inside the method, we define a list of URL for the requests. In our case, this list only contains the URL www.mainwebsite.com/topic1. Then, we are going to make a request with scrapy.Request."
},
{
"code": null,
"e": 12648,
"s": 12507,
"text": "We’ll use yield instead of return. We’ll tell scrapy to handle the downloaded content using the parse() method inside the callback argument."
},
{
"code": null,
"e": 12777,
"s": 12648,
"text": "Until now, you might think that the explanation about HTML and XPath was quite useless. Well, now it’s the moment we’ll need it."
},
{
"code": null,
"e": 12908,
"s": 12777,
"text": "After we define our method to start the initial request, we need to define the method that will handle our downloaded information."
},
{
"code": null,
"e": 13021,
"s": 12908,
"text": "So in other words, we need to decide what we want to do with all the data. What information is worth it to save."
},
{
"code": null,
"e": 13088,
"s": 13021,
"text": "For this, let’s suppose this is the HTML structure of our website."
},
{
"code": null,
"e": 13195,
"s": 13088,
"text": "As you can see in the picture, the highlighted element is the element we need to get to extract our links."
},
{
"code": null,
"e": 13379,
"s": 13195,
"text": "Let’s construct our path to get there. From all (//) thediv elements that have the class col-md-12 (div[@class='col-md-12']), we need the attribute href from the a children (a/@href)."
},
{
"code": null,
"e": 13442,
"s": 13379,
"text": "So, we have then our XPath: //div[@class='col-md-12']/a/@href."
},
{
"code": null,
"e": 13566,
"s": 13442,
"text": "In our parse method, we'll use response.xpath() to indicate the path and extract() to extract the content of every element."
},
{
"code": null,
"e": 13781,
"s": 13566,
"text": "We are expecting to get a list of links. We want to extract what is shown in those links. The spider will need to follow each of them and parse their content using a second parse method that we’ll call parse_first."
},
{
"code": null,
"e": 13897,
"s": 13781,
"text": "Notice that this time we are sending the links using follow in the response variable instead of creating a Request."
},
{
"code": null,
"e": 13988,
"s": 13897,
"text": "Next, the parse_first method has to be defined to tell the spider how to follow the links."
},
{
"code": null,
"e": 14052,
"s": 13988,
"text": "We are going to extract the title and the body of the document."
},
{
"code": null,
"e": 14230,
"s": 14052,
"text": "After exploring the HTML structure of one document, we’ll get any element which id is titleDocument, and all paragraphs that are a child of any element which id is BodyDocument."
},
{
"code": null,
"e": 14295,
"s": 14230,
"text": "Because we don’t care about which tag they have we’ll use the *."
},
{
"code": null,
"e": 14364,
"s": 14295,
"text": "After getting each paragraph, we are going to append them to a list."
},
{
"code": null,
"e": 14523,
"s": 14364,
"text": "After that, we’ll join all the paragraphs in the text list together. We’ll extract the date. Finally, we’ll define a dictionary with the date, title and text."
},
{
"code": null,
"e": 14569,
"s": 14523,
"text": "Lastly, we’ll save the data into a JSON file."
},
{
"code": null,
"e": 14679,
"s": 14569,
"text": "Here it’s the definition of the function extractdate where we’ll use regular expressions to extract the date."
},
{
"code": null,
"e": 14708,
"s": 14679,
"text": "Now, our spider is complete."
},
{
"code": null,
"e": 14824,
"s": 14708,
"text": "BIt’s time to investigate the scraper.py file. Not only we need to create spiders, but also we need to launch them."
},
{
"code": null,
"e": 14980,
"s": 14824,
"text": "First, we’ll import the required modules from Scrapy. CrawlerProcess will initiate the crawling process and settings will allow us to arrange the settings."
},
{
"code": null,
"e": 15045,
"s": 14980,
"text": "We’ll also import the three spider class created for each topic."
},
{
"code": null,
"e": 15088,
"s": 15045,
"text": "After that, we initiate a crawling process"
},
{
"code": null,
"e": 15168,
"s": 15088,
"text": "We tell the process which spiders to use and finally, we’ll start the crawling."
},
{
"code": null,
"e": 15210,
"s": 15168,
"text": "Perfect! We now have our scraper built!!!"
},
{
"code": null,
"e": 15266,
"s": 15210,
"text": "But wait how do we actually start scraping our website?"
},
{
"code": null,
"e": 15440,
"s": 15266,
"text": "In the terminal, we navigate with command line to our scraper folder (using cd). Once inside, we just launch the spiders with the python3 command you can see in the picture."
},
{
"code": null,
"e": 15490,
"s": 15440,
"text": "And voilà! The spiders are crawling the website!"
},
{
"code": null,
"e": 15583,
"s": 15490,
"text": "Here, I listed a couple of very nice resources and courses to learn more about web scraping:"
},
{
"code": null,
"e": 15672,
"s": 15583,
"text": "DataCamp Course.Web Scraping tutorialScrapy documentationHTML long and short explanation"
},
{
"code": null,
"e": 15689,
"s": 15672,
"text": "DataCamp Course."
},
{
"code": null,
"e": 15711,
"s": 15689,
"text": "Web Scraping tutorial"
},
{
"code": null,
"e": 15732,
"s": 15711,
"text": "Scrapy documentation"
},
{
"code": null,
"e": 15764,
"s": 15732,
"text": "HTML long and short explanation"
}
] |
XML - Schemas
|
XML Schema is commonly known as XML Schema Definition (XSD). It is used to describe and validate the structure and the content of XML data. XML schema defines the elements, attributes and data types. Schema element supports Namespaces. It is similar to a database schema that describes the data in a database.
You need to declare a schema in your XML document as follows −
The following example shows how to use schema −
<?xml version = "1.0" encoding = "UTF-8"?>
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema">
<xs:element name = "contact">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
<xs:element name = "phone" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The basic idea behind XML Schemas is that they describe the legitimate format that an XML document can take.
As we saw in the XML - Elements chapter, elements are the building blocks of XML document. An element can be defined within an XSD as follows −
<xs:element name = "x" type = "y"/>
You can define XML schema elements in the following ways −
Simple type element is used only in the context of the text. Some of the predefined simple types are: xs:integer, xs:boolean, xs:string, xs:date. For example −
<xs:element name = "phone_number" type = "xs:int" />
A complex type is a container for other element definitions. This allows you to specify which child elements an element can contain and to provide some structure within your XML documents. For example −
<xs:element name = "Address">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
<xs:element name = "phone" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
In the above example, Address element consists of child elements. This is a container for other <xs:element> definitions, that allows to build a simple hierarchy of elements in the XML document.
With the global type, you can define a single type in your document, which can be used by all other references. For example, suppose you want to generalize the person and company for different addresses of the company. In such case, you can define a general type as follows −
<xs:element name = "AddressType">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
Now let us use this type in our example as follows −
<xs:element name = "Address1">
<xs:complexType>
<xs:sequence>
<xs:element name = "address" type = "AddressType" />
<xs:element name = "phone1" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name = "Address2">
<xs:complexType>
<xs:sequence>
<xs:element name = "address" type = "AddressType" />
<xs:element name = "phone2" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
Instead of having to define the name and the company twice (once for Address1 and once for Address2), we now have a single definition. This makes maintenance simpler, i.e., if you decide to add "Postcode" elements to the address, you need to add them at just one place.
Attributes in XSD provide extra information within an element. Attributes have name and type property as shown below −
<xs:attribute name = "x" type = "y"/>
84 Lectures
6 hours
Frahaan Hussain
29 Lectures
2 hours
YouAccel
27 Lectures
1 hours
Jordan Stanchev
16 Lectures
2 hours
Simon Sez IT
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2271,
"s": 1961,
"text": "XML Schema is commonly known as XML Schema Definition (XSD). It is used to describe and validate the structure and the content of XML data. XML schema defines the elements, attributes and data types. Schema element supports Namespaces. It is similar to a database schema that describes the data in a database."
},
{
"code": null,
"e": 2334,
"s": 2271,
"text": "You need to declare a schema in your XML document as follows −"
},
{
"code": null,
"e": 2382,
"s": 2334,
"text": "The following example shows how to use schema −"
},
{
"code": null,
"e": 2821,
"s": 2382,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<xs:schema xmlns:xs = \"http://www.w3.org/2001/XMLSchema\">\n <xs:element name = \"contact\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name = \"name\" type = \"xs:string\" />\n <xs:element name = \"company\" type = \"xs:string\" />\n <xs:element name = \"phone\" type = \"xs:int\" />\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n</xs:schema>"
},
{
"code": null,
"e": 2930,
"s": 2821,
"text": "The basic idea behind XML Schemas is that they describe the legitimate format that an XML document can take."
},
{
"code": null,
"e": 3074,
"s": 2930,
"text": "As we saw in the XML - Elements chapter, elements are the building blocks of XML document. An element can be defined within an XSD as follows −"
},
{
"code": null,
"e": 3110,
"s": 3074,
"text": "<xs:element name = \"x\" type = \"y\"/>"
},
{
"code": null,
"e": 3169,
"s": 3110,
"text": "You can define XML schema elements in the following ways −"
},
{
"code": null,
"e": 3329,
"s": 3169,
"text": "Simple type element is used only in the context of the text. Some of the predefined simple types are: xs:integer, xs:boolean, xs:string, xs:date. For example −"
},
{
"code": null,
"e": 3382,
"s": 3329,
"text": "<xs:element name = \"phone_number\" type = \"xs:int\" />"
},
{
"code": null,
"e": 3585,
"s": 3382,
"text": "A complex type is a container for other element definitions. This allows you to specify which child elements an element can contain and to provide some structure within your XML documents. For example −"
},
{
"code": null,
"e": 3886,
"s": 3585,
"text": "<xs:element name = \"Address\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name = \"name\" type = \"xs:string\" />\n <xs:element name = \"company\" type = \"xs:string\" />\n <xs:element name = \"phone\" type = \"xs:int\" /> \n </xs:sequence> \n </xs:complexType>\n</xs:element> "
},
{
"code": null,
"e": 4081,
"s": 3886,
"text": "In the above example, Address element consists of child elements. This is a container for other <xs:element> definitions, that allows to build a simple hierarchy of elements in the XML document."
},
{
"code": null,
"e": 4357,
"s": 4081,
"text": "With the global type, you can define a single type in your document, which can be used by all other references. For example, suppose you want to generalize the person and company for different addresses of the company. In such case, you can define a general type as follows −"
},
{
"code": null,
"e": 4606,
"s": 4357,
"text": "<xs:element name = \"AddressType\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name = \"name\" type = \"xs:string\" />\n <xs:element name = \"company\" type = \"xs:string\" />\n </xs:sequence> \n </xs:complexType>\n</xs:element> "
},
{
"code": null,
"e": 4659,
"s": 4606,
"text": "Now let us use this type in our example as follows −"
},
{
"code": null,
"e": 5156,
"s": 4659,
"text": "<xs:element name = \"Address1\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name = \"address\" type = \"AddressType\" />\n <xs:element name = \"phone1\" type = \"xs:int\" /> \n </xs:sequence> \n </xs:complexType>\n</xs:element> \n\n<xs:element name = \"Address2\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name = \"address\" type = \"AddressType\" />\n <xs:element name = \"phone2\" type = \"xs:int\" /> \n </xs:sequence> \n </xs:complexType>\n</xs:element> "
},
{
"code": null,
"e": 5426,
"s": 5156,
"text": "Instead of having to define the name and the company twice (once for Address1 and once for Address2), we now have a single definition. This makes maintenance simpler, i.e., if you decide to add \"Postcode\" elements to the address, you need to add them at just one place."
},
{
"code": null,
"e": 5545,
"s": 5426,
"text": "Attributes in XSD provide extra information within an element. Attributes have name and type property as shown below −"
},
{
"code": null,
"e": 5583,
"s": 5545,
"text": "<xs:attribute name = \"x\" type = \"y\"/>"
},
{
"code": null,
"e": 5616,
"s": 5583,
"text": "\n 84 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5633,
"s": 5616,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5666,
"s": 5633,
"text": "\n 29 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5676,
"s": 5666,
"text": " YouAccel"
},
{
"code": null,
"e": 5709,
"s": 5676,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5726,
"s": 5709,
"text": " Jordan Stanchev"
},
{
"code": null,
"e": 5759,
"s": 5726,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5773,
"s": 5759,
"text": " Simon Sez IT"
},
{
"code": null,
"e": 5780,
"s": 5773,
"text": " Print"
},
{
"code": null,
"e": 5791,
"s": 5780,
"text": " Add Notes"
}
] |
Chic look in Power BI with Chiclet Slicer | by Nikola Ilic | Towards Data Science
|
Using custom visuals in Power BI report creation gives you a perfect opportunity to extend built-in visual capabilities above and beyond. There are literally hundreds of custom visuals in Appstore and I advise you to check them when you want to enrich your reports with non-standard visuals.
That’s one of the main strengths of Power BI — you can literally choose between hundreds of visuals to tell your data story in an appealing way.
Recently, I came across a specific request to enable slicing customers based on their last names. They were sorted in alphabetical order, but the request was to see only customers whose last name starts with, let’s say, R.
Step 1 was to import Chiclet Slicer visual from the marketplace. Click on three dots under the Visualizations pane and choose Import from AppSource.
In the search field enter Chiclet and, once you see it, click Add.
Now, you are ready to go and use Chiclet Slicer in your report. The next step is to extract only the first letter from the customer’s last name. I will use Adventure Works 2017 database for demo purposes.
Since I want to see customer’s full name, I will first create a new column within DimCustomer table and concatenate customers’ last name and first name:
Full Name = DimCustomer[LastName] & " " & DimCustomer[FirstName]
Next step is to extract the first letter from this column and the easiest way to do this is using the LEFT function:
Cust Lastname 1st = LEFT(DimCustomer[LastName],1)
Number 1 tells the function to leave only one character on the left side of the text and remove everything else.
As soon as I did this, I can drag Chiclet Slicer on the report and put my newly created column Cust Lastname 1st as a category for slicing:
Now, I can select only those customers whose last name starts with a specific letter(s) and all other visualizations will be also filtered accordingly.
You can use the “first letter trick” also for other categories, like the product, country, etc.
Chiclet slicer also offers you a nice feature of using images as slicers. To demonstrate this, I will use flags of specific countries that exist as regions in the Adventure Works 2017 database.
I’m using web URLs from Wikipedia, but you are free to choose whatever source you want. You can create an additional column in the DimGeography table and insert a web URL for every respective country. But, in that case, your data model will get larger, because you mustn’t forget that calculated columns are part of the data model and, therefore, takes memory space.
To avoid that, I normalized data into a separate table, using country region codes from DimGeography and web URL. Power BI is smart enough to recognize the relationship between these two tables:
Now, a very important step is to mark images’ URLs properly, so that Power BI can handle it as images. You achieve that by clicking on column Flag URL and categorizing this column as Image URL (Data Category dropdown menu under Column tools tab).
Now, it’s time to drag Chiclet Slicer again to our report. Put Country Region Code as a Category and Flag URL as Image.
Then, under the Format pane, you can play around and try different customizations of various attributes. I’ve set the Image split value to 80, so that both Category and image are visible, but you can also opt to see the image only if you like, by enlarging this value to 100.
As I said, experiment with different numbers until you get the look and feel that best suits your report.
Chiclet Slicer is another interesting tool under your belt, which gives you the possibility to enhance your reports, by extending standard visualizations. However, be careful and not overuse it. The most important thing is to find the right balance and use it in some specific scenarios where it makes sense.
Thanks for reading!
Subscribe here to get more insightful data articles!
|
[
{
"code": null,
"e": 464,
"s": 172,
"text": "Using custom visuals in Power BI report creation gives you a perfect opportunity to extend built-in visual capabilities above and beyond. There are literally hundreds of custom visuals in Appstore and I advise you to check them when you want to enrich your reports with non-standard visuals."
},
{
"code": null,
"e": 609,
"s": 464,
"text": "That’s one of the main strengths of Power BI — you can literally choose between hundreds of visuals to tell your data story in an appealing way."
},
{
"code": null,
"e": 832,
"s": 609,
"text": "Recently, I came across a specific request to enable slicing customers based on their last names. They were sorted in alphabetical order, but the request was to see only customers whose last name starts with, let’s say, R."
},
{
"code": null,
"e": 981,
"s": 832,
"text": "Step 1 was to import Chiclet Slicer visual from the marketplace. Click on three dots under the Visualizations pane and choose Import from AppSource."
},
{
"code": null,
"e": 1048,
"s": 981,
"text": "In the search field enter Chiclet and, once you see it, click Add."
},
{
"code": null,
"e": 1253,
"s": 1048,
"text": "Now, you are ready to go and use Chiclet Slicer in your report. The next step is to extract only the first letter from the customer’s last name. I will use Adventure Works 2017 database for demo purposes."
},
{
"code": null,
"e": 1406,
"s": 1253,
"text": "Since I want to see customer’s full name, I will first create a new column within DimCustomer table and concatenate customers’ last name and first name:"
},
{
"code": null,
"e": 1471,
"s": 1406,
"text": "Full Name = DimCustomer[LastName] & \" \" & DimCustomer[FirstName]"
},
{
"code": null,
"e": 1588,
"s": 1471,
"text": "Next step is to extract the first letter from this column and the easiest way to do this is using the LEFT function:"
},
{
"code": null,
"e": 1638,
"s": 1588,
"text": "Cust Lastname 1st = LEFT(DimCustomer[LastName],1)"
},
{
"code": null,
"e": 1751,
"s": 1638,
"text": "Number 1 tells the function to leave only one character on the left side of the text and remove everything else."
},
{
"code": null,
"e": 1891,
"s": 1751,
"text": "As soon as I did this, I can drag Chiclet Slicer on the report and put my newly created column Cust Lastname 1st as a category for slicing:"
},
{
"code": null,
"e": 2043,
"s": 1891,
"text": "Now, I can select only those customers whose last name starts with a specific letter(s) and all other visualizations will be also filtered accordingly."
},
{
"code": null,
"e": 2139,
"s": 2043,
"text": "You can use the “first letter trick” also for other categories, like the product, country, etc."
},
{
"code": null,
"e": 2333,
"s": 2139,
"text": "Chiclet slicer also offers you a nice feature of using images as slicers. To demonstrate this, I will use flags of specific countries that exist as regions in the Adventure Works 2017 database."
},
{
"code": null,
"e": 2700,
"s": 2333,
"text": "I’m using web URLs from Wikipedia, but you are free to choose whatever source you want. You can create an additional column in the DimGeography table and insert a web URL for every respective country. But, in that case, your data model will get larger, because you mustn’t forget that calculated columns are part of the data model and, therefore, takes memory space."
},
{
"code": null,
"e": 2895,
"s": 2700,
"text": "To avoid that, I normalized data into a separate table, using country region codes from DimGeography and web URL. Power BI is smart enough to recognize the relationship between these two tables:"
},
{
"code": null,
"e": 3142,
"s": 2895,
"text": "Now, a very important step is to mark images’ URLs properly, so that Power BI can handle it as images. You achieve that by clicking on column Flag URL and categorizing this column as Image URL (Data Category dropdown menu under Column tools tab)."
},
{
"code": null,
"e": 3262,
"s": 3142,
"text": "Now, it’s time to drag Chiclet Slicer again to our report. Put Country Region Code as a Category and Flag URL as Image."
},
{
"code": null,
"e": 3538,
"s": 3262,
"text": "Then, under the Format pane, you can play around and try different customizations of various attributes. I’ve set the Image split value to 80, so that both Category and image are visible, but you can also opt to see the image only if you like, by enlarging this value to 100."
},
{
"code": null,
"e": 3644,
"s": 3538,
"text": "As I said, experiment with different numbers until you get the look and feel that best suits your report."
},
{
"code": null,
"e": 3953,
"s": 3644,
"text": "Chiclet Slicer is another interesting tool under your belt, which gives you the possibility to enhance your reports, by extending standard visualizations. However, be careful and not overuse it. The most important thing is to find the right balance and use it in some specific scenarios where it makes sense."
},
{
"code": null,
"e": 3973,
"s": 3953,
"text": "Thanks for reading!"
}
] |
PyTorch Levels Up Its Serving Game with TorchServe | by Anthony Agnone | Towards Data Science
|
In recent years, PyTorch has largely overtaken Tensorflow as the machine learning model training framework that is preferred for research-leaning data scientists. There are a few reasons for this, but mainly that Pytorch is built for Python as its first-class language of use, whereas Tensorflow’s architecture stays much closer to its C/C++ core. Although both frameworks do have C/C++ cores, Pytorch does loads more to make its interface “ pythonic “. For those unfamiliar with the term, it basically means the code is easy to understand and doesn’t make you feel like an adversarial teacher wrote it for an exam question.
Pytorch’s cleaner interface has resulted in mass adoption for folks whose main priority is to quickly turn their planned analyses into actionable results. We don’t have time to play with a static computation graph API that makes me feel like a criminal for wanting to place a breakpoint to debug a tensor’s value. We need to prototype something and get moving onto the next experiment.
However, this advantage comes at a cost. With Pytorch, we can easily churn through experiment after experiment, tossing results over the fence to be put into production at a similar speed. Sadly, getting these models serving in production has been slower than the experimentation throughput due to a lack of production-ready frameworks that encapsulate away API complexity. At least, these frameworks have been missing for Pytorch.
Tensorflow has long had a truly impressive model serving framework, TFX. Truthfully, there’s not much missing in its framework, provided that you are knee-deep in the Tensorflow ecosystem. If you have a TF model and are using Google Cloud, use TFX until it breathes its last breath. If you are not in that camp, combining TFX and PyTorch has been anything but plug and play.
Fear no more! PyTorch’s 1.5 release brings the initial version of TorchServe as well as experimental support of TorchElastic with Kubernetes for large-scale model training. Software powerhouses Facebook and AWS continue to supercharge PyTorch’s capabilities and provide a competitive alternative to Google’s Tensorflow-based software pipelines.
TorchServe is a flexible and easy-to-use library for serving PyTorch models in production performantly at scale. It is cloud and environment agnostic and supports features such as multi-model serving, logging, metrics, and the creation of RESTful endpoints for application integration.
- PyTorch Docs
Let’s parse some of those qualities because they’re worth a focused repetition:
Serve PyTorch models in production performantly at scale
Cloud and environment agnostic
Multi-model serving
Logging
Metrics
RESTful endpoints
Any ML model in production that has these characteristics is bound to make your fellow engineers very happy.
TorchServe provides most things you’d expect from a serving API right out of the box. On top of that, it additionally offers default inference handlers for image-based and text-based models. Due to my audio background, I’d be remiss to not slip in my complaint that once again audio-based models are left out of first-class support. Audio remains the black sheep in the machine learning world for now! Alas, I digress...
The DenseNet architecture, which yields good results on image classification tasks, is provided as a default model in TorchServe. The PyTorch engineers provide a pre-built docker image, but I added a few things to it for the demonstration below. If you want to re-create for yourself, run the four commands here.
With a few passed command-line arguments to the torchserve command, we have a production-ready service ready to provide model predictions. Without bogging down the article with the nitty-gritty, you can use a quick driver script to pump an image through the server from either a URL or a local path.
Cliche time! Cats and dogs, here we go.
./query.sh images/puppy.jpg
Blenheim_spaniel: 97.00%Papillon: 1.40%Japanese_spaniel: 0.94%Brittany_spaniel: 0.41%
Spot on! Three of the top four as spaniel sub-breeds and around 1% of the not-so-different Papillon breed isn’t anything to clamor about.
How about a teeny tiny kitten, but with an extra fur hat on? I guess his natural fur and ears weren’t good enough for the photo? Regardless, surely this won’t change too much as far as the network’s predictions...
./query.sh images/kitten-2.jpg
Egyptian_cat: 24.90%Marmoset: 20.75%Tabby: 11.22%Patas: 10.17%
Well then...
There’s certainly a majority vote in the top 4 for cats, but the predictions barely edge out the Marmoset and Patas predictions, which are both classifications for...monkeys.
Cute, but not as much.
A for effort, I guess. For the curious, now’s a great chance to apply attention techniques to debug what parts of the image were used heavily in influencing the classification.
One step lower, here’s a demo of some raw cURL commands. Keep in mind, all of this API behavior came out of the box. All I provided was the choice of model and the input image.
I’ve barely touched the surface of TorchServe, and that’s a good thing. If I could demonstrate all of its functionality in a simple blog post, it would be nowhere near production-ready. Maybe allow a few more versions to turn over before putting it behind anything mission-critical. But Facebook and AWS have set an exciting foundation for greasing the skids between PyTorch-based research and production.
Things move quickly in academics and industry! Keep yourself updated with the general LifeWithData blog as well as the ML UTD newsletter.
If you’re not a fan of newsletters, but still want to stay in the loop, consider adding lifewithdata.org/blog and lifewithdata.org/tag/ml-utd to a Feedly aggregation setup.
Originally published at https://lifewithdata.org on May 24, 2020.
|
[
{
"code": null,
"e": 797,
"s": 172,
"text": "In recent years, PyTorch has largely overtaken Tensorflow as the machine learning model training framework that is preferred for research-leaning data scientists. There are a few reasons for this, but mainly that Pytorch is built for Python as its first-class language of use, whereas Tensorflow’s architecture stays much closer to its C/C++ core. Although both frameworks do have C/C++ cores, Pytorch does loads more to make its interface “ pythonic “. For those unfamiliar with the term, it basically means the code is easy to understand and doesn’t make you feel like an adversarial teacher wrote it for an exam question."
},
{
"code": null,
"e": 1183,
"s": 797,
"text": "Pytorch’s cleaner interface has resulted in mass adoption for folks whose main priority is to quickly turn their planned analyses into actionable results. We don’t have time to play with a static computation graph API that makes me feel like a criminal for wanting to place a breakpoint to debug a tensor’s value. We need to prototype something and get moving onto the next experiment."
},
{
"code": null,
"e": 1615,
"s": 1183,
"text": "However, this advantage comes at a cost. With Pytorch, we can easily churn through experiment after experiment, tossing results over the fence to be put into production at a similar speed. Sadly, getting these models serving in production has been slower than the experimentation throughput due to a lack of production-ready frameworks that encapsulate away API complexity. At least, these frameworks have been missing for Pytorch."
},
{
"code": null,
"e": 1990,
"s": 1615,
"text": "Tensorflow has long had a truly impressive model serving framework, TFX. Truthfully, there’s not much missing in its framework, provided that you are knee-deep in the Tensorflow ecosystem. If you have a TF model and are using Google Cloud, use TFX until it breathes its last breath. If you are not in that camp, combining TFX and PyTorch has been anything but plug and play."
},
{
"code": null,
"e": 2335,
"s": 1990,
"text": "Fear no more! PyTorch’s 1.5 release brings the initial version of TorchServe as well as experimental support of TorchElastic with Kubernetes for large-scale model training. Software powerhouses Facebook and AWS continue to supercharge PyTorch’s capabilities and provide a competitive alternative to Google’s Tensorflow-based software pipelines."
},
{
"code": null,
"e": 2621,
"s": 2335,
"text": "TorchServe is a flexible and easy-to-use library for serving PyTorch models in production performantly at scale. It is cloud and environment agnostic and supports features such as multi-model serving, logging, metrics, and the creation of RESTful endpoints for application integration."
},
{
"code": null,
"e": 2636,
"s": 2621,
"text": "- PyTorch Docs"
},
{
"code": null,
"e": 2716,
"s": 2636,
"text": "Let’s parse some of those qualities because they’re worth a focused repetition:"
},
{
"code": null,
"e": 2773,
"s": 2716,
"text": "Serve PyTorch models in production performantly at scale"
},
{
"code": null,
"e": 2804,
"s": 2773,
"text": "Cloud and environment agnostic"
},
{
"code": null,
"e": 2824,
"s": 2804,
"text": "Multi-model serving"
},
{
"code": null,
"e": 2832,
"s": 2824,
"text": "Logging"
},
{
"code": null,
"e": 2840,
"s": 2832,
"text": "Metrics"
},
{
"code": null,
"e": 2858,
"s": 2840,
"text": "RESTful endpoints"
},
{
"code": null,
"e": 2967,
"s": 2858,
"text": "Any ML model in production that has these characteristics is bound to make your fellow engineers very happy."
},
{
"code": null,
"e": 3388,
"s": 2967,
"text": "TorchServe provides most things you’d expect from a serving API right out of the box. On top of that, it additionally offers default inference handlers for image-based and text-based models. Due to my audio background, I’d be remiss to not slip in my complaint that once again audio-based models are left out of first-class support. Audio remains the black sheep in the machine learning world for now! Alas, I digress..."
},
{
"code": null,
"e": 3701,
"s": 3388,
"text": "The DenseNet architecture, which yields good results on image classification tasks, is provided as a default model in TorchServe. The PyTorch engineers provide a pre-built docker image, but I added a few things to it for the demonstration below. If you want to re-create for yourself, run the four commands here."
},
{
"code": null,
"e": 4001,
"s": 3701,
"text": "With a few passed command-line arguments to the torchserve command, we have a production-ready service ready to provide model predictions. Without bogging down the article with the nitty-gritty, you can use a quick driver script to pump an image through the server from either a URL or a local path."
},
{
"code": null,
"e": 4041,
"s": 4001,
"text": "Cliche time! Cats and dogs, here we go."
},
{
"code": null,
"e": 4069,
"s": 4041,
"text": "./query.sh images/puppy.jpg"
},
{
"code": null,
"e": 4155,
"s": 4069,
"text": "Blenheim_spaniel: 97.00%Papillon: 1.40%Japanese_spaniel: 0.94%Brittany_spaniel: 0.41%"
},
{
"code": null,
"e": 4293,
"s": 4155,
"text": "Spot on! Three of the top four as spaniel sub-breeds and around 1% of the not-so-different Papillon breed isn’t anything to clamor about."
},
{
"code": null,
"e": 4507,
"s": 4293,
"text": "How about a teeny tiny kitten, but with an extra fur hat on? I guess his natural fur and ears weren’t good enough for the photo? Regardless, surely this won’t change too much as far as the network’s predictions..."
},
{
"code": null,
"e": 4538,
"s": 4507,
"text": "./query.sh images/kitten-2.jpg"
},
{
"code": null,
"e": 4601,
"s": 4538,
"text": "Egyptian_cat: 24.90%Marmoset: 20.75%Tabby: 11.22%Patas: 10.17%"
},
{
"code": null,
"e": 4614,
"s": 4601,
"text": "Well then..."
},
{
"code": null,
"e": 4789,
"s": 4614,
"text": "There’s certainly a majority vote in the top 4 for cats, but the predictions barely edge out the Marmoset and Patas predictions, which are both classifications for...monkeys."
},
{
"code": null,
"e": 4812,
"s": 4789,
"text": "Cute, but not as much."
},
{
"code": null,
"e": 4989,
"s": 4812,
"text": "A for effort, I guess. For the curious, now’s a great chance to apply attention techniques to debug what parts of the image were used heavily in influencing the classification."
},
{
"code": null,
"e": 5166,
"s": 4989,
"text": "One step lower, here’s a demo of some raw cURL commands. Keep in mind, all of this API behavior came out of the box. All I provided was the choice of model and the input image."
},
{
"code": null,
"e": 5572,
"s": 5166,
"text": "I’ve barely touched the surface of TorchServe, and that’s a good thing. If I could demonstrate all of its functionality in a simple blog post, it would be nowhere near production-ready. Maybe allow a few more versions to turn over before putting it behind anything mission-critical. But Facebook and AWS have set an exciting foundation for greasing the skids between PyTorch-based research and production."
},
{
"code": null,
"e": 5710,
"s": 5572,
"text": "Things move quickly in academics and industry! Keep yourself updated with the general LifeWithData blog as well as the ML UTD newsletter."
},
{
"code": null,
"e": 5883,
"s": 5710,
"text": "If you’re not a fan of newsletters, but still want to stay in the loop, consider adding lifewithdata.org/blog and lifewithdata.org/tag/ml-utd to a Feedly aggregation setup."
}
] |
Foundations of Probability. Sigma Algebra, Measure Theory, and... | by Sadrach Pierre, Ph.D. | Towards Data Science
|
Sigma algebra is considered part of the axiomatic foundations of probability theory. The topic is briefly covered in Casella & Berger’s Statistical Inference. The need for sigma algebras arises out of the technical difficulties associated with defining probabilities. So what exactly are sigma algebras?
Simply put, sigma on X is a collection of subsets of X including the empty set and X itself. In other words, sigma is the power set of X. The sigma algebra is also referred to as the Borel field. It is formally defined as follows:
The first property states that the empty set is always in a sigma algebra. Additionally, since the complement of the empty set is also in the sample space S, the first and second statement implies that the sample space is always in the Borel field (or part of the sigma algebra). The last two statements are conditions of countable intersections and unions.
The Borel space is a basic object of measure theory. It consists of a set and it’s corresponding sigma algebra. Specifically:
Let’s walk through a small example. Consider the following set:
Given X, the Borel Field is is a collection of 23 = 8 sets, also called the power set:
The power set is closely related to the binomial theorem which describes the algebraic expansion of powers of a binomial like the following:
We can expand this using the binomial formula:
where the binomial coefficient is:
The number of subsets in the power set of X is given by the number of binomial coeffients C(n,k):
The power set of any set is the set containing the empty set and the combinations of elements within that set from 1 to the size of the original set:
Now we will discuss how to generate the power set using an implementation in python. To begin, let’s import combinations and chain from itertools:
from itertools import combinations, chain
Next, let’s initialize a tuple containing an empty tuple:
powerset = ((),)
Now, let’s define a function that takes a parameter input set and uses the chain and combinations method to generate out power set:
def powerset(input_set):size = len(input_set) combs = (combinations(input_set, k) for k in range(1, size+1)) return chain(empty_powerset, *combs)
If we call our function with the set we specified earlier:
print(tuple(powerset({10, 20, 30})))
It turns out, unlike the example we showed above, for uncountable sets sigma algebra is necessary. Sigma algebra is necessary in order for us to be able to consider subsets of the real numbers of actual events. In other words, the sets need to be well defined, under the conditions of countable unions and countable intersections, for it to have probabilities assigned to it.
Given our basic understanding of Borel spaces, let’s proceed by defining probability functions.
Given a sample space S and an associated sigma algebra B, a probability function is a function P with domain B that satisfies the following:
Any function P that satisfies the statements above is a candidate probability function. Since there can be many probability functions defined that satisfy the Axioms of Probability, probability theory is concerned with understanding which functions reflect what is likely to be observed in a particular experiment.
One last interesting thing to consider:
The Banach — Tarski Paradox illustrates the contradiction that arises in the absence of sigma algebra. It states the following:
Given two solid 3D balls, one small and one large, either ball can be reassembled into the other. This is also called the pea and sun Paradox, where it’s stated that a pea can be reassembled into the sun and vice versa. This means that if you are working with real numbers in 3 dimensions (ratio of volumes, for example), you will have difficulty defining probabilities of events because you can rearrange sets of your space to change volumes. If your probability depends on volume, by changing the volume of the set you will also change probabilities. This means that no event can have a single probability assigned to it. This necessitates sigma algebra, which allows us to define measurable sets and probabilities.
|
[
{
"code": null,
"e": 475,
"s": 171,
"text": "Sigma algebra is considered part of the axiomatic foundations of probability theory. The topic is briefly covered in Casella & Berger’s Statistical Inference. The need for sigma algebras arises out of the technical difficulties associated with defining probabilities. So what exactly are sigma algebras?"
},
{
"code": null,
"e": 706,
"s": 475,
"text": "Simply put, sigma on X is a collection of subsets of X including the empty set and X itself. In other words, sigma is the power set of X. The sigma algebra is also referred to as the Borel field. It is formally defined as follows:"
},
{
"code": null,
"e": 1064,
"s": 706,
"text": "The first property states that the empty set is always in a sigma algebra. Additionally, since the complement of the empty set is also in the sample space S, the first and second statement implies that the sample space is always in the Borel field (or part of the sigma algebra). The last two statements are conditions of countable intersections and unions."
},
{
"code": null,
"e": 1190,
"s": 1064,
"text": "The Borel space is a basic object of measure theory. It consists of a set and it’s corresponding sigma algebra. Specifically:"
},
{
"code": null,
"e": 1254,
"s": 1190,
"text": "Let’s walk through a small example. Consider the following set:"
},
{
"code": null,
"e": 1341,
"s": 1254,
"text": "Given X, the Borel Field is is a collection of 23 = 8 sets, also called the power set:"
},
{
"code": null,
"e": 1482,
"s": 1341,
"text": "The power set is closely related to the binomial theorem which describes the algebraic expansion of powers of a binomial like the following:"
},
{
"code": null,
"e": 1529,
"s": 1482,
"text": "We can expand this using the binomial formula:"
},
{
"code": null,
"e": 1564,
"s": 1529,
"text": "where the binomial coefficient is:"
},
{
"code": null,
"e": 1662,
"s": 1564,
"text": "The number of subsets in the power set of X is given by the number of binomial coeffients C(n,k):"
},
{
"code": null,
"e": 1812,
"s": 1662,
"text": "The power set of any set is the set containing the empty set and the combinations of elements within that set from 1 to the size of the original set:"
},
{
"code": null,
"e": 1959,
"s": 1812,
"text": "Now we will discuss how to generate the power set using an implementation in python. To begin, let’s import combinations and chain from itertools:"
},
{
"code": null,
"e": 2001,
"s": 1959,
"text": "from itertools import combinations, chain"
},
{
"code": null,
"e": 2059,
"s": 2001,
"text": "Next, let’s initialize a tuple containing an empty tuple:"
},
{
"code": null,
"e": 2076,
"s": 2059,
"text": "powerset = ((),)"
},
{
"code": null,
"e": 2208,
"s": 2076,
"text": "Now, let’s define a function that takes a parameter input set and uses the chain and combinations method to generate out power set:"
},
{
"code": null,
"e": 2364,
"s": 2208,
"text": "def powerset(input_set):size = len(input_set) combs = (combinations(input_set, k) for k in range(1, size+1)) return chain(empty_powerset, *combs)"
},
{
"code": null,
"e": 2423,
"s": 2364,
"text": "If we call our function with the set we specified earlier:"
},
{
"code": null,
"e": 2460,
"s": 2423,
"text": "print(tuple(powerset({10, 20, 30})))"
},
{
"code": null,
"e": 2836,
"s": 2460,
"text": "It turns out, unlike the example we showed above, for uncountable sets sigma algebra is necessary. Sigma algebra is necessary in order for us to be able to consider subsets of the real numbers of actual events. In other words, the sets need to be well defined, under the conditions of countable unions and countable intersections, for it to have probabilities assigned to it."
},
{
"code": null,
"e": 2932,
"s": 2836,
"text": "Given our basic understanding of Borel spaces, let’s proceed by defining probability functions."
},
{
"code": null,
"e": 3073,
"s": 2932,
"text": "Given a sample space S and an associated sigma algebra B, a probability function is a function P with domain B that satisfies the following:"
},
{
"code": null,
"e": 3388,
"s": 3073,
"text": "Any function P that satisfies the statements above is a candidate probability function. Since there can be many probability functions defined that satisfy the Axioms of Probability, probability theory is concerned with understanding which functions reflect what is likely to be observed in a particular experiment."
},
{
"code": null,
"e": 3428,
"s": 3388,
"text": "One last interesting thing to consider:"
},
{
"code": null,
"e": 3556,
"s": 3428,
"text": "The Banach — Tarski Paradox illustrates the contradiction that arises in the absence of sigma algebra. It states the following:"
}
] |
Banking Transaction System using Java - GeeksforGeeks
|
29 Apr, 2022
In order to understand one must have a strong grasp over Java OOPs, Java Multithreading & Java Interrupted-Exception. If not go through them as the title in itself is a sheer implementation of multithreading.
Approaches:
Rookie approachMultithreading approachSynchronization invoking in multithreading approach
Rookie approach
Multithreading approach
Synchronization invoking in multithreading approach
In order to understand, let us consider an illustration in order to implement the approach.
Illustration:
We will discuss the architecture of the banking transaction system using java. Throughout this editorial, I will hold your hands and take you through the entire transaction procedure and make it Easy-Pease for you to understand so that you can even explain it to your friends. For the sake of simplicity, we have considered a joint bank account having 5 owners(Arnab, Monodwip, Mukta, Rinkel, and Shubham) and the initial balance is a hundred dollars ($100). The transactions of the account are listed as follows:
Arnab has withdrawn 20
Balance after withdrawal: 80
Monodwip withdrawn 40
Balance after withdrawal: 40
Mukta deposited 35
Balance after deposit: 75
Rinkel you can not withdraw 80
your balance is: 75
Shubham withdrawn 40
Balance after withdrawal: 35
Approach 1: Rookie approach
We have declared the “withdraw” and “deposit” method inside the class “Bank” and accessed them from the driver class “GFG” by creating an object “obj” of Bank class.
Example
Java
// Java Program to illustrate Rookie Approach// In Banking transaction system // Class 1// Bank class// Defining the banking transactionclass Bank { // Initial balance $100 int total = 100; // Money withdrawal method. Withdraw only if // total money greater than or equal to the money // requested for withdrawal // Method // To withdraw money void withdrawn(String name, int withdrawal) { if (total >= withdrawal) { System.out.println(name + " withdrawn " + withdrawal); total = total - withdrawal; System.out.println("Balance after withdrawal: " + total); // Making the thread sleep for 1 second after // each withdrawal // Try block to check for exceptions try { // Making thread t osleep for 1 second Thread.sleep(1000); } // Catch block to handle the exceptions catch (InterruptedException e) { // Display the exception along with line // number // using printStacktrace() method e.printStackTrace(); } } // If the money requested for withdrawal is greater // than the balance then deny transaction*/ else { // Print statements System.out.println(name + " you can not withdraw " + withdrawal); System.out.println("your balance is: " + total); // Making the thread sleep for 1 second after // each transaction failure // Try block to check for exceptions try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } // Method - to deposit money // Accept money whenever deposited void deposit(String name, int deposit) { System.out.println(name + " deposited " + deposit); total = total + deposit; System.out.println("Balance after deposit: " + total); // Making the thread sleep for 1 second after // each deposit try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }}// Class 2// main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring an object of Bank class and calling the // withdarwn and deposit methods with suitable // parameters // Creating object of class 1 inside main() Bank obj = new Bank(); // Custom input - Transactions obj.withdrawn("Arnab", 20); obj.withdrawn("Monodwip", 40); obj.deposit("Mukta", 35); obj.withdrawn("Rinkel", 80); obj.withdrawn("Shubham", 40); }}
Output:
C:\Users\USER\Desktop\LearnCoding\MultiThreading>javac GFG.java
C:\Users\USER\Desktop\LearnCoding\MultiThreading>java GFG
Arnab withdrawn 20
Balance after withdrawal: 80
//After 1 Second
Monodwip withdrawn 40
Balance after withdrawal: 40
//After 1 Second
Mukta deposited 35
Balance after deposit: 75
//After 1 Second
Rinkel you can not withdraw 80
your balance is: 75
//After 1 Second
Shubham withdrawn 40
Balance after withdrawal: 35
There are certain cons associated with the Rookie approach as depicted below:
No 2 people can make transactions at the same time, one needs to wait till the former finishes its transaction. If the number of people is large then we need to wait and wait until our turn comes. To demonstrate this problem, we made the thread sleep for 3 seconds during each transaction in the video provided below. In real life, it would take much time making this approach incapable of implementation in real transaction projects.
Method 2: Multithreading Approach
How multithreading can help?
Multithreading allows different threads to work at the same time without having any dependency on one-another. So large group of threads can perform an operation at the same time.
Example
Java
// Java Program to illustrate Multithreading Approach// In Banking transaction system // Class 1// Helper classclass Bank { // Initial custom balance int total = 100; // Money withdrawal method. Withdraw only if total money // greater than or equal to the money requested for // withdrawal void withdrawn(String name, int withdrawal) { if (total >= withdrawal) { System.out.println(name + " withdrawn " + withdrawal); total = total - withdrawal; System.out.println(total); // Making the thread sleep for 1 second after // each withdrawal // Try block to check for exceptions try { // Making thread to sleep for 1 second Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } // Else if the money requested for withdrawal is // greater than the balance then deny transaction else { System.out.println(name + " you can not withdraw " + withdrawal); System.out.println("your balance is: " + total); // Making the thread sleep for 1 second after // each transaction failure try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } // Method - To deposit money // Accepting money whenever deposited void deposit(String name, int deposit) { System.out.println(name + " deposited " + deposit); total = total + deposit; System.out.println("Balance after deposit: " + total); // Making the thread sleep for 1 second after // each deposit try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }} // Method - Withdraw method// Called from ThreadWithdrawal class// using the object of Bank class passed// from the main() methodclass ThreadWithdrawal extends Thread { Bank object; String name; int dollar; // Constructor of this method ThreadWithdrawal(Bank ob, String name, int money) { this.object = ob; this.name = name; this.dollar = money; } // run() method for thread public void run() { object.withdrawn(name, dollar); }}// Deposit method is called from ThreadDeposit class// using the object of Bank class passed// from the main methodclass ThreadDeposit extends Thread { Bank object; String name; int dollar; ThreadDeposit(Bank ob, String name, int money) { // This keyword refers t ocurrent instance itself this.object = ob; this.name = name; this.dollar = money; } public void run() { object.deposit(name, dollar); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring an object of Bank class and passing the // object along with other parameters to the // ThreadWithdrawal and ThreadDeposit class. This // will be required to call withdrawn and deposit // methods from those class // Creating an object of class1 Bank obj = new Bank(); ThreadWithdrawal t1 = new ThreadWithdrawal(obj, "Arnab", 20); ThreadWithdrawal t2 = new ThreadWithdrawal(obj, "Monodwip", 40); ThreadDeposit t3 = new ThreadDeposit(obj, "Mukta", 35); ThreadWithdrawal t4 = new ThreadWithdrawal(obj, "Rinkel", 80); ThreadWithdrawal t5 = new ThreadWithdrawal(obj, "Shubham", 40); // When a program calls the start() method, a new // thread is created and then the run() method is // executed. // Starting threads created above t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); }}
Output:
Now there are certain problems with the multithreading approach as listed below:
When multiple threads try to do a particular operation at the same time then there exists a possibility of bad output, this is because all the threads are updating the same resource at a time. In the above output, we got balance in negative figures due to the same reason.
How to handle those cases where multiple people try to access the same operation at a time?
If multiple threads access a single resource at a time then there exists a possibility of bad output. This unwanted phenomenon is defined as data racing.
Suppose we have $100 in our joint bank account. To trick the banker, both of us can request $100 simultaneously at a time. The system will create an object, assign 2 threads and pass them to the withdrawal method. At the end of the process, both of us will have $100!
To handle this problem engineers came up with the synchronization concept.
YouTubeGeeksforGeeks502K subscribersSynchronization | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 18:31•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=IIgHG_YHXPE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Method 3: Incorporating synchronization with multithreading
Synchronization provides a lock to the object and declares a sensitive area (withdraw & deposit methods). An object can have multiple threads but the sensitive area can only be accessed by 1 thread at a time. The thread scheduler chooses the order of execution of the threads. As it is a random process the output is different for each interpretation.
Why should we use static synchronization?
Say we have 5 thread classes with 1 object each. Each object have multiple threads. Now the sensitive area will be accessed by 5 threads at a time! To handle this problem engineers came up with the idea of static synchronization. We provide a lock to the class. The class will select 1 object at a time. The object in turn will choose 1 thread and pass it through the sensitive area.
Does synchronized multithreaded execution slower than the normal execution without multithreading?
No. The amount of time one task spends waiting for another is considered as overhead. In synchronized multithreading, this overhead time can be used to do other productive work until the waiting thread gets the key from the thread scheduler to get inside the synchronized area. Thus the overhead would be minimal in the case of synchronized multithreaded execution, so we can expect it to be faster.
Example
Java
// Java Program to illustrate Multithreading Approach// With Synchronization In Banking transaction system // Class 1// Helper classclass Bank { // Initial balance $100 static int total = 100; // Money withdrawal method. Withdraw only if total money // greater than or equal to the money requested for // withdrawal static synchronized void withdrawn(String name, int withdrawal) { if (total >= withdrawal) { System.out.println(name + " withdrawn " + withdrawal); total = total - withdrawal; System.out.println("Balance after withdrawal: " + total); /* Making the thread sleep for 1 second after each withdrawal.*/ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } // If the money requested for withdrawal is greater // than the balance then deny transaction else { System.out.println(name + " you can not withdraw " + withdrawal); System.out.println("your balance is: " + total); // Making the thread sleep for 1 second after // each transaction failure // Try block to check for exceptions try { // Making thread to sleep for 1 second Thread.sleep(1000); } // Catch bloc kto handle exceptions catch (InterruptedException e) { // Displa ythe line number where exception // occurred // Using printStackTrace() method e.printStackTrace(); } } } // Method - Deposit method // Accepting money whenever deposited static synchronized void deposit(String name, int deposit) { System.out.println(name + " deposited " + deposit); total = total + deposit; System.out.println("Balance after deposit: " + total); // Making the thread sleep for 1 second // after each deposit // Try block to check for exceptions try { // Making thread to sleep for 1 second Thread.sleep(1000); } // Catch block to handle InterruptedException // exception catch (InterruptedException e) { e.printStackTrace(); } }} // Method - Withdraw// It is called from ThreadWithdrawal class using// the object of Bank class passed from the main methodclass ThreadWithdrawal extends Thread { // Attributes of this class Bank object; String name; int dollar; // Constructor of this class ThreadWithdrawal(Bank ob, String name, int money) { // This keyword refers to parent class this.object = ob; this.name = name; this.dollar = money; } // run() method for the thread public void run() { object.withdrawn(name, dollar); }} // Deposit method is called from ThreadDeposit class using// the object of Bank class passed from the main method*/ // Class 2// Helper class extending Thread classclass ThreadDeposit extends Thread { Bank object; String name; int dollar; ThreadDeposit(Bank ob, String name, int money) { this.object = ob; this.name = name; this.dollar = money; } public void run() { object.deposit(name, dollar); }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring an object of Bank class and passing the // object along with other parameters to the // ThreadWithdrawal and ThreadDeposit class. This // will be required to call withdrawn and deposit // methods from those class // Creating object of above class inside main() Bank obj = new Bank(); // Creating threads ThreadWithdrawal t1 = new ThreadWithdrawal(obj, "Arnab", 20); ThreadWithdrawal t2 = new ThreadWithdrawal(obj, "Monodwip", 40); ThreadDeposit t3 = new ThreadDeposit(obj, "Mukta", 35); ThreadWithdrawal t4 = new ThreadWithdrawal(obj, "Rinkel", 80); ThreadWithdrawal t5 = new ThreadWithdrawal(obj, "Shubham", 40); // When a program calls the start() method, a new // thread is created and then the run() method is // executed t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); }}
Output(Compiled & Interpreted):
Output(Interpreted): Shubham & Monodwip failed to withdraw money
C:\Users\USER\Desktop\Network Java>java GFG
Arnab withdrawn 20
Balance after withdrawal: 80
Rinkel withdrawn 80
Balance after withdrawal: 0
Shubham you can not withdraw 40
your balance is: 0
Mukta deposited 35
Balance after deposit: 35
Monodwip you can not withdraw 40
your balance is: 35
Output(Interpreted): Rinkel failed to withdraw money.
C:\Users\USER\Desktop\Network Java>java GFG
Arnab withdrawn 20
Balance after withdrawal: 80
Shubham withdrawn 40
Balance after withdrawal: 40
Monodwip withdrawn 40
Balance after withdrawal: 0
Mukta deposited 35
Balance after deposit: 35
Rinkel you can not withdraw 80
your balance is: 35
Output(Interpreted): Monodwip failed to withdraw money.
C:\Users\USER\Desktop\Network Java>java GFG
Arnab withdrawn 20
Balance after withdrawal: 80
Rinkel withdrawn 80
Balance after withdrawal: 0
Shubham you can not withdraw 40
your balance is: 0
Monodwip you can not withdraw 40
your balance is: 0
Mukta deposited 35
Balance after deposit: 35
Note: The thread scheduler chooses the order of execution of the threads. As it is a random process the output is different for each interpretation.
dattabikash505
gulshankumarar231
anikakapoor
sweetyty
Blogathon-2021
Blogathon
Java
Project
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python NOT EQUAL operator
Difference Between Local Storage, Session Storage And Cookies
Changing CSS styling with React onClick() Event
How to Connect Python with SQL Database?
How to parse JSON Data into React Table Component ?
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
|
[
{
"code": null,
"e": 25084,
"s": 25056,
"text": "\n29 Apr, 2022"
},
{
"code": null,
"e": 25294,
"s": 25084,
"text": "In order to understand one must have a strong grasp over Java OOPs, Java Multithreading & Java Interrupted-Exception. If not go through them as the title in itself is a sheer implementation of multithreading."
},
{
"code": null,
"e": 25306,
"s": 25294,
"text": "Approaches:"
},
{
"code": null,
"e": 25396,
"s": 25306,
"text": "Rookie approachMultithreading approachSynchronization invoking in multithreading approach"
},
{
"code": null,
"e": 25412,
"s": 25396,
"text": "Rookie approach"
},
{
"code": null,
"e": 25436,
"s": 25412,
"text": "Multithreading approach"
},
{
"code": null,
"e": 25488,
"s": 25436,
"text": "Synchronization invoking in multithreading approach"
},
{
"code": null,
"e": 25580,
"s": 25488,
"text": "In order to understand, let us consider an illustration in order to implement the approach."
},
{
"code": null,
"e": 25594,
"s": 25580,
"text": "Illustration:"
},
{
"code": null,
"e": 26108,
"s": 25594,
"text": "We will discuss the architecture of the banking transaction system using java. Throughout this editorial, I will hold your hands and take you through the entire transaction procedure and make it Easy-Pease for you to understand so that you can even explain it to your friends. For the sake of simplicity, we have considered a joint bank account having 5 owners(Arnab, Monodwip, Mukta, Rinkel, and Shubham) and the initial balance is a hundred dollars ($100). The transactions of the account are listed as follows:"
},
{
"code": null,
"e": 26156,
"s": 26108,
"text": "Arnab has withdrawn 20 "
},
{
"code": null,
"e": 26191,
"s": 26156,
"text": "Balance after withdrawal: 80 "
},
{
"code": null,
"e": 26213,
"s": 26191,
"text": "Monodwip withdrawn 40"
},
{
"code": null,
"e": 26245,
"s": 26213,
"text": "Balance after withdrawal: 40 "
},
{
"code": null,
"e": 26264,
"s": 26245,
"text": "Mukta deposited 35"
},
{
"code": null,
"e": 26290,
"s": 26264,
"text": "Balance after deposit: 75"
},
{
"code": null,
"e": 26321,
"s": 26290,
"text": "Rinkel you can not withdraw 80"
},
{
"code": null,
"e": 26344,
"s": 26321,
"text": "your balance is: 75 "
},
{
"code": null,
"e": 26367,
"s": 26344,
"text": "Shubham withdrawn 40 "
},
{
"code": null,
"e": 26402,
"s": 26367,
"text": "Balance after withdrawal: 35 "
},
{
"code": null,
"e": 26430,
"s": 26402,
"text": "Approach 1: Rookie approach"
},
{
"code": null,
"e": 26596,
"s": 26430,
"text": "We have declared the “withdraw” and “deposit” method inside the class “Bank” and accessed them from the driver class “GFG” by creating an object “obj” of Bank class."
},
{
"code": null,
"e": 26604,
"s": 26596,
"text": "Example"
},
{
"code": null,
"e": 26609,
"s": 26604,
"text": "Java"
},
{
"code": "// Java Program to illustrate Rookie Approach// In Banking transaction system // Class 1// Bank class// Defining the banking transactionclass Bank { // Initial balance $100 int total = 100; // Money withdrawal method. Withdraw only if // total money greater than or equal to the money // requested for withdrawal // Method // To withdraw money void withdrawn(String name, int withdrawal) { if (total >= withdrawal) { System.out.println(name + \" withdrawn \" + withdrawal); total = total - withdrawal; System.out.println(\"Balance after withdrawal: \" + total); // Making the thread sleep for 1 second after // each withdrawal // Try block to check for exceptions try { // Making thread t osleep for 1 second Thread.sleep(1000); } // Catch block to handle the exceptions catch (InterruptedException e) { // Display the exception along with line // number // using printStacktrace() method e.printStackTrace(); } } // If the money requested for withdrawal is greater // than the balance then deny transaction*/ else { // Print statements System.out.println(name + \" you can not withdraw \" + withdrawal); System.out.println(\"your balance is: \" + total); // Making the thread sleep for 1 second after // each transaction failure // Try block to check for exceptions try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } // Method - to deposit money // Accept money whenever deposited void deposit(String name, int deposit) { System.out.println(name + \" deposited \" + deposit); total = total + deposit; System.out.println(\"Balance after deposit: \" + total); // Making the thread sleep for 1 second after // each deposit try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }}// Class 2// main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring an object of Bank class and calling the // withdarwn and deposit methods with suitable // parameters // Creating object of class 1 inside main() Bank obj = new Bank(); // Custom input - Transactions obj.withdrawn(\"Arnab\", 20); obj.withdrawn(\"Monodwip\", 40); obj.deposit(\"Mukta\", 35); obj.withdrawn(\"Rinkel\", 80); obj.withdrawn(\"Shubham\", 40); }}",
"e": 29576,
"s": 26609,
"text": null
},
{
"code": null,
"e": 29584,
"s": 29576,
"text": "Output:"
},
{
"code": null,
"e": 30023,
"s": 29584,
"text": "C:\\Users\\USER\\Desktop\\LearnCoding\\MultiThreading>javac GFG.java\nC:\\Users\\USER\\Desktop\\LearnCoding\\MultiThreading>java GFG\nArnab withdrawn 20\nBalance after withdrawal: 80\n\n//After 1 Second\nMonodwip withdrawn 40\nBalance after withdrawal: 40\n\n//After 1 Second\nMukta deposited 35\nBalance after deposit: 75\n\n//After 1 Second\nRinkel you can not withdraw 80\nyour balance is: 75\n\n//After 1 Second\nShubham withdrawn 40\nBalance after withdrawal: 35"
},
{
"code": null,
"e": 30102,
"s": 30023,
"text": "There are certain cons associated with the Rookie approach as depicted below: "
},
{
"code": null,
"e": 30537,
"s": 30102,
"text": "No 2 people can make transactions at the same time, one needs to wait till the former finishes its transaction. If the number of people is large then we need to wait and wait until our turn comes. To demonstrate this problem, we made the thread sleep for 3 seconds during each transaction in the video provided below. In real life, it would take much time making this approach incapable of implementation in real transaction projects."
},
{
"code": null,
"e": 30571,
"s": 30537,
"text": "Method 2: Multithreading Approach"
},
{
"code": null,
"e": 30600,
"s": 30571,
"text": "How multithreading can help?"
},
{
"code": null,
"e": 30781,
"s": 30600,
"text": "Multithreading allows different threads to work at the same time without having any dependency on one-another. So large group of threads can perform an operation at the same time. "
},
{
"code": null,
"e": 30789,
"s": 30781,
"text": "Example"
},
{
"code": null,
"e": 30794,
"s": 30789,
"text": "Java"
},
{
"code": "// Java Program to illustrate Multithreading Approach// In Banking transaction system // Class 1// Helper classclass Bank { // Initial custom balance int total = 100; // Money withdrawal method. Withdraw only if total money // greater than or equal to the money requested for // withdrawal void withdrawn(String name, int withdrawal) { if (total >= withdrawal) { System.out.println(name + \" withdrawn \" + withdrawal); total = total - withdrawal; System.out.println(total); // Making the thread sleep for 1 second after // each withdrawal // Try block to check for exceptions try { // Making thread to sleep for 1 second Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } // Else if the money requested for withdrawal is // greater than the balance then deny transaction else { System.out.println(name + \" you can not withdraw \" + withdrawal); System.out.println(\"your balance is: \" + total); // Making the thread sleep for 1 second after // each transaction failure try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } // Method - To deposit money // Accepting money whenever deposited void deposit(String name, int deposit) { System.out.println(name + \" deposited \" + deposit); total = total + deposit; System.out.println(\"Balance after deposit: \" + total); // Making the thread sleep for 1 second after // each deposit try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }} // Method - Withdraw method// Called from ThreadWithdrawal class// using the object of Bank class passed// from the main() methodclass ThreadWithdrawal extends Thread { Bank object; String name; int dollar; // Constructor of this method ThreadWithdrawal(Bank ob, String name, int money) { this.object = ob; this.name = name; this.dollar = money; } // run() method for thread public void run() { object.withdrawn(name, dollar); }}// Deposit method is called from ThreadDeposit class// using the object of Bank class passed// from the main methodclass ThreadDeposit extends Thread { Bank object; String name; int dollar; ThreadDeposit(Bank ob, String name, int money) { // This keyword refers t ocurrent instance itself this.object = ob; this.name = name; this.dollar = money; } public void run() { object.deposit(name, dollar); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring an object of Bank class and passing the // object along with other parameters to the // ThreadWithdrawal and ThreadDeposit class. This // will be required to call withdrawn and deposit // methods from those class // Creating an object of class1 Bank obj = new Bank(); ThreadWithdrawal t1 = new ThreadWithdrawal(obj, \"Arnab\", 20); ThreadWithdrawal t2 = new ThreadWithdrawal(obj, \"Monodwip\", 40); ThreadDeposit t3 = new ThreadDeposit(obj, \"Mukta\", 35); ThreadWithdrawal t4 = new ThreadWithdrawal(obj, \"Rinkel\", 80); ThreadWithdrawal t5 = new ThreadWithdrawal(obj, \"Shubham\", 40); // When a program calls the start() method, a new // thread is created and then the run() method is // executed. // Starting threads created above t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); }}",
"e": 34888,
"s": 30794,
"text": null
},
{
"code": null,
"e": 34896,
"s": 34888,
"text": "Output:"
},
{
"code": null,
"e": 34977,
"s": 34896,
"text": "Now there are certain problems with the multithreading approach as listed below:"
},
{
"code": null,
"e": 35250,
"s": 34977,
"text": "When multiple threads try to do a particular operation at the same time then there exists a possibility of bad output, this is because all the threads are updating the same resource at a time. In the above output, we got balance in negative figures due to the same reason."
},
{
"code": null,
"e": 35342,
"s": 35250,
"text": "How to handle those cases where multiple people try to access the same operation at a time?"
},
{
"code": null,
"e": 35496,
"s": 35342,
"text": "If multiple threads access a single resource at a time then there exists a possibility of bad output. This unwanted phenomenon is defined as data racing."
},
{
"code": null,
"e": 35764,
"s": 35496,
"text": "Suppose we have $100 in our joint bank account. To trick the banker, both of us can request $100 simultaneously at a time. The system will create an object, assign 2 threads and pass them to the withdrawal method. At the end of the process, both of us will have $100!"
},
{
"code": null,
"e": 35839,
"s": 35764,
"text": "To handle this problem engineers came up with the synchronization concept."
},
{
"code": null,
"e": 36654,
"s": 35839,
"text": "YouTubeGeeksforGeeks502K subscribersSynchronization | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 18:31•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=IIgHG_YHXPE\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 36714,
"s": 36654,
"text": "Method 3: Incorporating synchronization with multithreading"
},
{
"code": null,
"e": 37066,
"s": 36714,
"text": "Synchronization provides a lock to the object and declares a sensitive area (withdraw & deposit methods). An object can have multiple threads but the sensitive area can only be accessed by 1 thread at a time. The thread scheduler chooses the order of execution of the threads. As it is a random process the output is different for each interpretation."
},
{
"code": null,
"e": 37108,
"s": 37066,
"text": "Why should we use static synchronization?"
},
{
"code": null,
"e": 37492,
"s": 37108,
"text": "Say we have 5 thread classes with 1 object each. Each object have multiple threads. Now the sensitive area will be accessed by 5 threads at a time! To handle this problem engineers came up with the idea of static synchronization. We provide a lock to the class. The class will select 1 object at a time. The object in turn will choose 1 thread and pass it through the sensitive area."
},
{
"code": null,
"e": 37591,
"s": 37492,
"text": "Does synchronized multithreaded execution slower than the normal execution without multithreading?"
},
{
"code": null,
"e": 37991,
"s": 37591,
"text": "No. The amount of time one task spends waiting for another is considered as overhead. In synchronized multithreading, this overhead time can be used to do other productive work until the waiting thread gets the key from the thread scheduler to get inside the synchronized area. Thus the overhead would be minimal in the case of synchronized multithreaded execution, so we can expect it to be faster."
},
{
"code": null,
"e": 37999,
"s": 37991,
"text": "Example"
},
{
"code": null,
"e": 38004,
"s": 37999,
"text": "Java"
},
{
"code": "// Java Program to illustrate Multithreading Approach// With Synchronization In Banking transaction system // Class 1// Helper classclass Bank { // Initial balance $100 static int total = 100; // Money withdrawal method. Withdraw only if total money // greater than or equal to the money requested for // withdrawal static synchronized void withdrawn(String name, int withdrawal) { if (total >= withdrawal) { System.out.println(name + \" withdrawn \" + withdrawal); total = total - withdrawal; System.out.println(\"Balance after withdrawal: \" + total); /* Making the thread sleep for 1 second after each withdrawal.*/ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } // If the money requested for withdrawal is greater // than the balance then deny transaction else { System.out.println(name + \" you can not withdraw \" + withdrawal); System.out.println(\"your balance is: \" + total); // Making the thread sleep for 1 second after // each transaction failure // Try block to check for exceptions try { // Making thread to sleep for 1 second Thread.sleep(1000); } // Catch bloc kto handle exceptions catch (InterruptedException e) { // Displa ythe line number where exception // occurred // Using printStackTrace() method e.printStackTrace(); } } } // Method - Deposit method // Accepting money whenever deposited static synchronized void deposit(String name, int deposit) { System.out.println(name + \" deposited \" + deposit); total = total + deposit; System.out.println(\"Balance after deposit: \" + total); // Making the thread sleep for 1 second // after each deposit // Try block to check for exceptions try { // Making thread to sleep for 1 second Thread.sleep(1000); } // Catch block to handle InterruptedException // exception catch (InterruptedException e) { e.printStackTrace(); } }} // Method - Withdraw// It is called from ThreadWithdrawal class using// the object of Bank class passed from the main methodclass ThreadWithdrawal extends Thread { // Attributes of this class Bank object; String name; int dollar; // Constructor of this class ThreadWithdrawal(Bank ob, String name, int money) { // This keyword refers to parent class this.object = ob; this.name = name; this.dollar = money; } // run() method for the thread public void run() { object.withdrawn(name, dollar); }} // Deposit method is called from ThreadDeposit class using// the object of Bank class passed from the main method*/ // Class 2// Helper class extending Thread classclass ThreadDeposit extends Thread { Bank object; String name; int dollar; ThreadDeposit(Bank ob, String name, int money) { this.object = ob; this.name = name; this.dollar = money; } public void run() { object.deposit(name, dollar); }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring an object of Bank class and passing the // object along with other parameters to the // ThreadWithdrawal and ThreadDeposit class. This // will be required to call withdrawn and deposit // methods from those class // Creating object of above class inside main() Bank obj = new Bank(); // Creating threads ThreadWithdrawal t1 = new ThreadWithdrawal(obj, \"Arnab\", 20); ThreadWithdrawal t2 = new ThreadWithdrawal(obj, \"Monodwip\", 40); ThreadDeposit t3 = new ThreadDeposit(obj, \"Mukta\", 35); ThreadWithdrawal t4 = new ThreadWithdrawal(obj, \"Rinkel\", 80); ThreadWithdrawal t5 = new ThreadWithdrawal(obj, \"Shubham\", 40); // When a program calls the start() method, a new // thread is created and then the run() method is // executed t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); }}",
"e": 42713,
"s": 38004,
"text": null
},
{
"code": null,
"e": 42745,
"s": 42713,
"text": "Output(Compiled & Interpreted):"
},
{
"code": null,
"e": 42810,
"s": 42745,
"text": "Output(Interpreted): Shubham & Monodwip failed to withdraw money"
},
{
"code": null,
"e": 43101,
"s": 42810,
"text": "C:\\Users\\USER\\Desktop\\Network Java>java GFG\n\nArnab withdrawn 20\nBalance after withdrawal: 80\nRinkel withdrawn 80\nBalance after withdrawal: 0\nShubham you can not withdraw 40\nyour balance is: 0\nMukta deposited 35\nBalance after deposit: 35\nMonodwip you can not withdraw 40\nyour balance is: 35"
},
{
"code": null,
"e": 43155,
"s": 43101,
"text": "Output(Interpreted): Rinkel failed to withdraw money."
},
{
"code": null,
"e": 43445,
"s": 43155,
"text": "C:\\Users\\USER\\Desktop\\Network Java>java GFG\n\nArnab withdrawn 20\nBalance after withdrawal: 80\nShubham withdrawn 40\nBalance after withdrawal: 40\nMonodwip withdrawn 40\nBalance after withdrawal: 0\nMukta deposited 35\nBalance after deposit: 35\nRinkel you can not withdraw 80\nyour balance is: 35"
},
{
"code": null,
"e": 43501,
"s": 43445,
"text": "Output(Interpreted): Monodwip failed to withdraw money."
},
{
"code": null,
"e": 43791,
"s": 43501,
"text": "C:\\Users\\USER\\Desktop\\Network Java>java GFG\n\nArnab withdrawn 20\nBalance after withdrawal: 80\nRinkel withdrawn 80\nBalance after withdrawal: 0\nShubham you can not withdraw 40\nyour balance is: 0\nMonodwip you can not withdraw 40\nyour balance is: 0\nMukta deposited 35\nBalance after deposit: 35"
},
{
"code": null,
"e": 43940,
"s": 43791,
"text": "Note: The thread scheduler chooses the order of execution of the threads. As it is a random process the output is different for each interpretation."
},
{
"code": null,
"e": 43955,
"s": 43940,
"text": "dattabikash505"
},
{
"code": null,
"e": 43973,
"s": 43955,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 43985,
"s": 43973,
"text": "anikakapoor"
},
{
"code": null,
"e": 43994,
"s": 43985,
"text": "sweetyty"
},
{
"code": null,
"e": 44009,
"s": 43994,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 44019,
"s": 44009,
"text": "Blogathon"
},
{
"code": null,
"e": 44024,
"s": 44019,
"text": "Java"
},
{
"code": null,
"e": 44032,
"s": 44024,
"text": "Project"
},
{
"code": null,
"e": 44037,
"s": 44032,
"text": "Java"
},
{
"code": null,
"e": 44135,
"s": 44037,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44161,
"s": 44135,
"text": "Python NOT EQUAL operator"
},
{
"code": null,
"e": 44223,
"s": 44161,
"text": "Difference Between Local Storage, Session Storage And Cookies"
},
{
"code": null,
"e": 44271,
"s": 44223,
"text": "Changing CSS styling with React onClick() Event"
},
{
"code": null,
"e": 44312,
"s": 44271,
"text": "How to Connect Python with SQL Database?"
},
{
"code": null,
"e": 44364,
"s": 44312,
"text": "How to parse JSON Data into React Table Component ?"
},
{
"code": null,
"e": 44386,
"s": 44364,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 44411,
"s": 44386,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 44447,
"s": 44411,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 44479,
"s": 44447,
"text": "Initialize an ArrayList in Java"
}
] |
Check if a number can be represented as sum of two positive perfect cubes - GeeksforGeeks
|
21 Sep, 2021
Given an integer N, the task is to check if N can be represented as the sum of two positive perfect cubes or not.
Examples:
Input: N = 28Output: YesExplanation: Since, 28 = 27 + 1 = 33 + 13.Therefore, the required answer is Yes.
Input: N = 34Output: No
Approach: The idea is to store the perfect cubes of all numbers from 1 to cubic root of N in a Map and check if N can be represented as the sum of two numbers present in the Map or not. Follow the steps below to solve the problem:
Initialize an ordered map, say cubes, to store the perfect cubes of first N natural numbers in sorted order.
Traverse the map and check for the pair having a sum equal to N.
If such a pair is found having sum N, then print “Yes”. Otherwise, print “No”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to check if N can be represented// as sum of two perfect cubes or notvoid sumOfTwoPerfectCubes(int N){ // Stores the perfect cubes // of first N natural numbers map<int, int> cubes; for (int i = 1; i * i * i <= N; i++) cubes[i * i * i] = i; // Traverse the map map<int, int>::iterator itr; for (itr = cubes.begin(); itr != cubes.end(); itr++) { // Stores first number int firstNumber = itr->first; // Stores second number int secondNumber = N - itr->first; // Search the pair for the first // number to obtain sum N from the Map if (cubes.find(secondNumber) != cubes.end()) { cout << "True"; return; } } // If N cannot be represented as // sum of two positive perfect cubes cout << "False";} // Driver Codeint main(){ int N = 28; // Function call to check if N // can be represented as // sum of two perfect cubes or not sumOfTwoPerfectCubes(N); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Function to check if N can be represented // as sum of two perfect cubes or not public static void sumOfTwoPerfectCubes(int N) { // Stores the perfect cubes // of first N natural numbers HashMap<Integer, Integer> cubes = new HashMap<>(); for (int i = 1; i * i * i <= N; i++) cubes.put((i * i * i), i); // Traverse the map Iterator<Map.Entry<Integer, Integer> > itr = cubes.entrySet().iterator(); while (itr.hasNext()) { Map.Entry<Integer, Integer> entry = itr.next(); // Stores first number int firstNumber = entry.getKey(); // Stores second number int secondNumber = N - entry.getKey(); // Search the pair for the first // number to obtain sum N from the Map if (cubes.containsKey(secondNumber)) { System.out.println("True"); return; } } // If N cannot be represented as // sum of two positive perfect cubes System.out.println("False"); } // Driver code public static void main(String[] args) { int N = 28; // Function call to check if N // can be represented as // sum of two perfect cubes or not sumOfTwoPerfectCubes(N); }} // This code is contributed by shailjapriya.
# Python3 program for the above approach # Function to check if N can be represented# as sum of two perfect cubes or notdef sumOfTwoPerfectCubes(N) : # Stores the perfect cubes # of first N natural numbers cubes = {} i = 1 while i*i*i <= N : cubes[i*i*i] = i i += 1 # Traverse the map for itr in cubes : # Stores first number firstNumber = itr # Stores second number secondNumber = N - itr # Search the pair for the first # number to obtain sum N from the Map if secondNumber in cubes : print("True", end = "") return # If N cannot be represented as # sum of two positive perfect cubes print("False", end = "") N = 28 # Function call to check if N# can be represented as# sum of two perfect cubes or notsumOfTwoPerfectCubes(N) # This code is contributed by divyeshrabadiya07.
// C# program for the above approachusing System;using System.Collections.Generic;using System.Linq; class GFG{ // Function to check if N can be represented // as sum of two perfect cubes or not public static void sumOfTwoPerfectCubes(int N) { // Stores the perfect cubes // of first N natural numbers Dictionary<int, int> cubes = new Dictionary<int, int>(); for (int i = 1; i * i * i <= N; i++) cubes.Add((i * i * i), i); var val = cubes.Keys.ToList(); foreach(var key in val) { // Stores first number int firstNumber = cubes[1]; // Stores second number int secondNumber = N - cubes[1]; // Search the pair for the first // number to obtain sum N from the Map if (cubes.ContainsKey(secondNumber)) { Console.Write("True"); return; } } // If N cannot be represented as // sum of two positive perfect cubes Console.Write("False"); } // Driver Codestatic public void Main(){ int N = 28; // Function call to check if N // can be represented as // sum of two perfect cubes or not sumOfTwoPerfectCubes(N);}} // This code is contributed by code_hunt.
<script> // Javascript program for the above approach // Function to check if N can be represented// as sum of two perfect cubes or notfunction sumOfTwoPerfectCubes(N){ // Stores the perfect cubes // of first N natural numbers var cubes = new Map(); for (var i = 1; i * i * i <= N; i++) cubes.set(i * i * i, i); var ans = false; // Traverse the map cubes.forEach((value, key) => { // Stores first number var firstNumber = key; // Stores second number var secondNumber = N - value; // Search the pair for the first // number to obtain sum N from the Map if (cubes.has(secondNumber)) { document.write( "True"); ans = true; return; } }); if(ans) { return; } // If N cannot be represented as // sum of two positive perfect cubes document.write( "False");} // Driver Codevar N = 28;// Function call to check if N// can be represented as// sum of two perfect cubes or notsumOfTwoPerfectCubes(N); </script>
True
Time Complexity: O(N1/3 * log(N1/3)) Auxiliary Space: O(N1/3)
Approach 2 :
Using two Pointers:
We will declare lo to 1 and hi to cube root of n(the given number), then by (lo<=hi) this condition, if current is smaller than n we will increment the lo and in other hand if it is greater then decrement the hi, where current is (lo*lo*lo + hi*hi*hi)
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to check if N can be represented// as sum of two perfect cubes or notbool sumOfTwoCubes(int n){ long long int lo = 1, hi = (long long int)cbrt(n); while (lo <= hi) { long long int curr = (lo * lo * lo + hi * hi * hi); if (curr == n) // if it is same return true; return true; if (curr < n) // if the curr smaller than n increment the lo lo++; else // if the curr is greater than curr decrement // the hi hi--; } return false;} // Driver Codeint main(){ int N = 28; // Function call to check if N // can be represented as // sum of two perfect cubes or not if (sumOfTwoCubes(N)) { cout << "True"; } else { cout << "False"; } return 0;}
// Java program for the above approachimport java.io.*; class GFG{ // Function to check if N can be represented// as sum of two perfect cubes or notstatic boolean sumOfTwoCubes(int n){ int lo = 1, hi = (int)Math.cbrt(n); while (lo <= hi) { int curr = (lo * lo * lo + hi * hi * hi); if (curr == n) // if it is same return true; return true; if (curr < n) // if the curr smaller than n increment the lo lo++; else // if the curr is greater than curr decrement // the hi hi--; } return false;} // Driver Codepublic static void main (String[] args){ int N = 28; // Function call to check if N // can be represented as // sum of two perfect cubes or not if (sumOfTwoCubes(N)) { System.out.println("True"); } else { System.out.println("False"); } }} // This code is contributed by shivanisinghss2110
# Python3 program for the above approachimport math # Function to check if N can be represented# as sum of two perfect cubes or notdef sumOfTwoCubes(n): lo = 1 hi = round(math.pow(n, 1 / 3)) while (lo <= hi): curr = (lo * lo * lo + hi * hi * hi) if (curr == n): # If it is same return true; return True if (curr < n): # If the curr smaller than n increment the lo lo += 1 else: # If the curr is greater than curr decrement # the hi hi -= 1 return False # Driver CodeN = 28 # Function call to check if N# can be represented as sum of# two perfect cubes or notif (sumOfTwoCubes(N)): print("True")else: print("False") # This code is contributed by shivanisinghss2110
// C# program for the above approachusing System; class GFG{ // Function to check if N can be represented// as sum of two perfect cubes or notstatic bool sumOfTwoCubes(int n){ int lo = 1, hi = (int)Math.Pow(n, (1.0 / 3.0)); while (lo <= hi) { int curr = (lo * lo * lo + hi * hi * hi); if (curr == n) // if it is same return true; return true; if (curr < n) // if the curr smaller than n increment the lo lo++; else // if the curr is greater than curr decrement // the hi hi--; } return false;} // Driver Codepublic static void Main (String[] args){ int N = 28; // Function call to check if N // can be represented as // sum of two perfect cubes or not if (sumOfTwoCubes(N)) { Console.Write("True"); } else { Console.Write("False"); } }} // This code is contributed by shivanisinghss2110
<script>// JavaScript program for the above approach// Function to check if N can be represented// as sum of two perfect cubes or notfunction sumOfTwoCubes(n){ var lo = 1, hi = (n); while (lo <= hi) { var curr = (lo * lo * lo + hi * hi * hi); if (curr == n) // if it is same return true; return true; if (curr < n) // if the curr smaller than n increment the lo lo++; else // if the curr is greater than curr decrement // the hi hi--; } return false;} // Driver Code var N = 28; // Function call to check if N // can be represented as // sum of two perfect cubes or not if (sumOfTwoCubes(N)) { document.write("True"); } else { document.write("False"); } // This code is contributed by shivanisinghss2110</script>
True
Time Complexity : O(sqrt(n)),where n is given number
Space Complexity : O(1)
shailjapriya
code_hunt
divyeshrabadiya07
harjotsingh7
rrrtnx
heyy2001
shivanisinghss2110
maths-perfect-cube
Hash
Mathematical
Hash
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Rearrange an array such that arr[i] = i
Quadratic Probing in Hashing
Hashing in Java
What are Hash Functions and How to choose a good Hash Function?
Real-time application of Data Structures
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 24765,
"s": 24737,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 24879,
"s": 24765,
"text": "Given an integer N, the task is to check if N can be represented as the sum of two positive perfect cubes or not."
},
{
"code": null,
"e": 24889,
"s": 24879,
"text": "Examples:"
},
{
"code": null,
"e": 24994,
"s": 24889,
"text": "Input: N = 28Output: YesExplanation: Since, 28 = 27 + 1 = 33 + 13.Therefore, the required answer is Yes."
},
{
"code": null,
"e": 25018,
"s": 24994,
"text": "Input: N = 34Output: No"
},
{
"code": null,
"e": 25249,
"s": 25018,
"text": "Approach: The idea is to store the perfect cubes of all numbers from 1 to cubic root of N in a Map and check if N can be represented as the sum of two numbers present in the Map or not. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25358,
"s": 25249,
"text": "Initialize an ordered map, say cubes, to store the perfect cubes of first N natural numbers in sorted order."
},
{
"code": null,
"e": 25423,
"s": 25358,
"text": "Traverse the map and check for the pair having a sum equal to N."
},
{
"code": null,
"e": 25502,
"s": 25423,
"text": "If such a pair is found having sum N, then print “Yes”. Otherwise, print “No”."
},
{
"code": null,
"e": 25553,
"s": 25502,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25557,
"s": 25553,
"text": "C++"
},
{
"code": null,
"e": 25562,
"s": 25557,
"text": "Java"
},
{
"code": null,
"e": 25570,
"s": 25562,
"text": "Python3"
},
{
"code": null,
"e": 25573,
"s": 25570,
"text": "C#"
},
{
"code": null,
"e": 25584,
"s": 25573,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to check if N can be represented// as sum of two perfect cubes or notvoid sumOfTwoPerfectCubes(int N){ // Stores the perfect cubes // of first N natural numbers map<int, int> cubes; for (int i = 1; i * i * i <= N; i++) cubes[i * i * i] = i; // Traverse the map map<int, int>::iterator itr; for (itr = cubes.begin(); itr != cubes.end(); itr++) { // Stores first number int firstNumber = itr->first; // Stores second number int secondNumber = N - itr->first; // Search the pair for the first // number to obtain sum N from the Map if (cubes.find(secondNumber) != cubes.end()) { cout << \"True\"; return; } } // If N cannot be represented as // sum of two positive perfect cubes cout << \"False\";} // Driver Codeint main(){ int N = 28; // Function call to check if N // can be represented as // sum of two perfect cubes or not sumOfTwoPerfectCubes(N); return 0;}",
"e": 26698,
"s": 25584,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to check if N can be represented // as sum of two perfect cubes or not public static void sumOfTwoPerfectCubes(int N) { // Stores the perfect cubes // of first N natural numbers HashMap<Integer, Integer> cubes = new HashMap<>(); for (int i = 1; i * i * i <= N; i++) cubes.put((i * i * i), i); // Traverse the map Iterator<Map.Entry<Integer, Integer> > itr = cubes.entrySet().iterator(); while (itr.hasNext()) { Map.Entry<Integer, Integer> entry = itr.next(); // Stores first number int firstNumber = entry.getKey(); // Stores second number int secondNumber = N - entry.getKey(); // Search the pair for the first // number to obtain sum N from the Map if (cubes.containsKey(secondNumber)) { System.out.println(\"True\"); return; } } // If N cannot be represented as // sum of two positive perfect cubes System.out.println(\"False\"); } // Driver code public static void main(String[] args) { int N = 28; // Function call to check if N // can be represented as // sum of two perfect cubes or not sumOfTwoPerfectCubes(N); }} // This code is contributed by shailjapriya.",
"e": 27984,
"s": 26698,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to check if N can be represented# as sum of two perfect cubes or notdef sumOfTwoPerfectCubes(N) : # Stores the perfect cubes # of first N natural numbers cubes = {} i = 1 while i*i*i <= N : cubes[i*i*i] = i i += 1 # Traverse the map for itr in cubes : # Stores first number firstNumber = itr # Stores second number secondNumber = N - itr # Search the pair for the first # number to obtain sum N from the Map if secondNumber in cubes : print(\"True\", end = \"\") return # If N cannot be represented as # sum of two positive perfect cubes print(\"False\", end = \"\") N = 28 # Function call to check if N# can be represented as# sum of two perfect cubes or notsumOfTwoPerfectCubes(N) # This code is contributed by divyeshrabadiya07.",
"e": 28886,
"s": 27984,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;using System.Linq; class GFG{ // Function to check if N can be represented // as sum of two perfect cubes or not public static void sumOfTwoPerfectCubes(int N) { // Stores the perfect cubes // of first N natural numbers Dictionary<int, int> cubes = new Dictionary<int, int>(); for (int i = 1; i * i * i <= N; i++) cubes.Add((i * i * i), i); var val = cubes.Keys.ToList(); foreach(var key in val) { // Stores first number int firstNumber = cubes[1]; // Stores second number int secondNumber = N - cubes[1]; // Search the pair for the first // number to obtain sum N from the Map if (cubes.ContainsKey(secondNumber)) { Console.Write(\"True\"); return; } } // If N cannot be represented as // sum of two positive perfect cubes Console.Write(\"False\"); } // Driver Codestatic public void Main(){ int N = 28; // Function call to check if N // can be represented as // sum of two perfect cubes or not sumOfTwoPerfectCubes(N);}} // This code is contributed by code_hunt.",
"e": 30107,
"s": 28886,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to check if N can be represented// as sum of two perfect cubes or notfunction sumOfTwoPerfectCubes(N){ // Stores the perfect cubes // of first N natural numbers var cubes = new Map(); for (var i = 1; i * i * i <= N; i++) cubes.set(i * i * i, i); var ans = false; // Traverse the map cubes.forEach((value, key) => { // Stores first number var firstNumber = key; // Stores second number var secondNumber = N - value; // Search the pair for the first // number to obtain sum N from the Map if (cubes.has(secondNumber)) { document.write( \"True\"); ans = true; return; } }); if(ans) { return; } // If N cannot be represented as // sum of two positive perfect cubes document.write( \"False\");} // Driver Codevar N = 28;// Function call to check if N// can be represented as// sum of two perfect cubes or notsumOfTwoPerfectCubes(N); </script>",
"e": 31159,
"s": 30107,
"text": null
},
{
"code": null,
"e": 31164,
"s": 31159,
"text": "True"
},
{
"code": null,
"e": 31228,
"s": 31164,
"text": "Time Complexity: O(N1/3 * log(N1/3)) Auxiliary Space: O(N1/3) "
},
{
"code": null,
"e": 31241,
"s": 31228,
"text": "Approach 2 :"
},
{
"code": null,
"e": 31261,
"s": 31241,
"text": "Using two Pointers:"
},
{
"code": null,
"e": 31513,
"s": 31261,
"text": "We will declare lo to 1 and hi to cube root of n(the given number), then by (lo<=hi) this condition, if current is smaller than n we will increment the lo and in other hand if it is greater then decrement the hi, where current is (lo*lo*lo + hi*hi*hi)"
},
{
"code": null,
"e": 31517,
"s": 31513,
"text": "C++"
},
{
"code": null,
"e": 31522,
"s": 31517,
"text": "Java"
},
{
"code": null,
"e": 31530,
"s": 31522,
"text": "Python3"
},
{
"code": null,
"e": 31533,
"s": 31530,
"text": "C#"
},
{
"code": null,
"e": 31544,
"s": 31533,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to check if N can be represented// as sum of two perfect cubes or notbool sumOfTwoCubes(int n){ long long int lo = 1, hi = (long long int)cbrt(n); while (lo <= hi) { long long int curr = (lo * lo * lo + hi * hi * hi); if (curr == n) // if it is same return true; return true; if (curr < n) // if the curr smaller than n increment the lo lo++; else // if the curr is greater than curr decrement // the hi hi--; } return false;} // Driver Codeint main(){ int N = 28; // Function call to check if N // can be represented as // sum of two perfect cubes or not if (sumOfTwoCubes(N)) { cout << \"True\"; } else { cout << \"False\"; } return 0;}",
"e": 32434,
"s": 31544,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*; class GFG{ // Function to check if N can be represented// as sum of two perfect cubes or notstatic boolean sumOfTwoCubes(int n){ int lo = 1, hi = (int)Math.cbrt(n); while (lo <= hi) { int curr = (lo * lo * lo + hi * hi * hi); if (curr == n) // if it is same return true; return true; if (curr < n) // if the curr smaller than n increment the lo lo++; else // if the curr is greater than curr decrement // the hi hi--; } return false;} // Driver Codepublic static void main (String[] args){ int N = 28; // Function call to check if N // can be represented as // sum of two perfect cubes or not if (sumOfTwoCubes(N)) { System.out.println(\"True\"); } else { System.out.println(\"False\"); } }} // This code is contributed by shivanisinghss2110",
"e": 33417,
"s": 32434,
"text": null
},
{
"code": "# Python3 program for the above approachimport math # Function to check if N can be represented# as sum of two perfect cubes or notdef sumOfTwoCubes(n): lo = 1 hi = round(math.pow(n, 1 / 3)) while (lo <= hi): curr = (lo * lo * lo + hi * hi * hi) if (curr == n): # If it is same return true; return True if (curr < n): # If the curr smaller than n increment the lo lo += 1 else: # If the curr is greater than curr decrement # the hi hi -= 1 return False # Driver CodeN = 28 # Function call to check if N# can be represented as sum of# two perfect cubes or notif (sumOfTwoCubes(N)): print(\"True\")else: print(\"False\") # This code is contributed by shivanisinghss2110",
"e": 34258,
"s": 33417,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to check if N can be represented// as sum of two perfect cubes or notstatic bool sumOfTwoCubes(int n){ int lo = 1, hi = (int)Math.Pow(n, (1.0 / 3.0)); while (lo <= hi) { int curr = (lo * lo * lo + hi * hi * hi); if (curr == n) // if it is same return true; return true; if (curr < n) // if the curr smaller than n increment the lo lo++; else // if the curr is greater than curr decrement // the hi hi--; } return false;} // Driver Codepublic static void Main (String[] args){ int N = 28; // Function call to check if N // can be represented as // sum of two perfect cubes or not if (sumOfTwoCubes(N)) { Console.Write(\"True\"); } else { Console.Write(\"False\"); } }} // This code is contributed by shivanisinghss2110",
"e": 35234,
"s": 34258,
"text": null
},
{
"code": "<script>// JavaScript program for the above approach// Function to check if N can be represented// as sum of two perfect cubes or notfunction sumOfTwoCubes(n){ var lo = 1, hi = (n); while (lo <= hi) { var curr = (lo * lo * lo + hi * hi * hi); if (curr == n) // if it is same return true; return true; if (curr < n) // if the curr smaller than n increment the lo lo++; else // if the curr is greater than curr decrement // the hi hi--; } return false;} // Driver Code var N = 28; // Function call to check if N // can be represented as // sum of two perfect cubes or not if (sumOfTwoCubes(N)) { document.write(\"True\"); } else { document.write(\"False\"); } // This code is contributed by shivanisinghss2110</script>",
"e": 36130,
"s": 35234,
"text": null
},
{
"code": null,
"e": 36135,
"s": 36130,
"text": "True"
},
{
"code": null,
"e": 36189,
"s": 36135,
"text": "Time Complexity : O(sqrt(n)),where n is given number "
},
{
"code": null,
"e": 36213,
"s": 36189,
"text": "Space Complexity : O(1)"
},
{
"code": null,
"e": 36226,
"s": 36213,
"text": "shailjapriya"
},
{
"code": null,
"e": 36236,
"s": 36226,
"text": "code_hunt"
},
{
"code": null,
"e": 36254,
"s": 36236,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 36267,
"s": 36254,
"text": "harjotsingh7"
},
{
"code": null,
"e": 36274,
"s": 36267,
"text": "rrrtnx"
},
{
"code": null,
"e": 36283,
"s": 36274,
"text": "heyy2001"
},
{
"code": null,
"e": 36302,
"s": 36283,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 36321,
"s": 36302,
"text": "maths-perfect-cube"
},
{
"code": null,
"e": 36326,
"s": 36321,
"text": "Hash"
},
{
"code": null,
"e": 36339,
"s": 36326,
"text": "Mathematical"
},
{
"code": null,
"e": 36344,
"s": 36339,
"text": "Hash"
},
{
"code": null,
"e": 36357,
"s": 36344,
"text": "Mathematical"
},
{
"code": null,
"e": 36455,
"s": 36357,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36464,
"s": 36455,
"text": "Comments"
},
{
"code": null,
"e": 36477,
"s": 36464,
"text": "Old Comments"
},
{
"code": null,
"e": 36517,
"s": 36477,
"text": "Rearrange an array such that arr[i] = i"
},
{
"code": null,
"e": 36546,
"s": 36517,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 36562,
"s": 36546,
"text": "Hashing in Java"
},
{
"code": null,
"e": 36626,
"s": 36562,
"text": "What are Hash Functions and How to choose a good Hash Function?"
},
{
"code": null,
"e": 36667,
"s": 36626,
"text": "Real-time application of Data Structures"
},
{
"code": null,
"e": 36697,
"s": 36667,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 36757,
"s": 36697,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 36772,
"s": 36757,
"text": "C++ Data Types"
},
{
"code": null,
"e": 36815,
"s": 36772,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to change the thickness of hr tag using CSS ? - GeeksforGeeks
|
21 Oct, 2021
The HTML <hr> tag is used to insert a horizontal rule or a thematic break in an HTML page to divide or separate document sections.The thickness of the hr tag can be set using the height property in CSS. The minimum height can be 1px since the smallest unit available is 1 pixel. Images can be added to make the hr tag more beautiful in appearance. It is an empty tag, and it does not require an end tag.
Syntax:
<hr property: value;> ...
Property value:
align: It is used to specify the alignment of the horizontal rule. The values are left, center & right.
noshade: It is used to specify the bar without shading effect. The default value is noshade.
size: It is used to specify the height of the horizontal rule. The default value is pixels.
width: It is Used to specify the width of the horizontal rule. The default value is pixels.
color: It is used to specify the color of a Horizontal rule. It is not supported by HTML 5.
We will utilize the above property values through the examples.
Example 1: This example shows the basic use of the <hr> tag to insert a horizontal rule along with some CSS properties.
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title> Document </title> <style> div { width: 300px; } h1, h3 { color: green; } hr { position: relative; top: 20px; border: none; height: 12px; background: black; margin-bottom: 50px; } </style></head> <body> <center> <div> <h1>GeeksforGeeks</h1> <hr /> <h3>A Computer Science Portal</h3> </div> </center></body></html>
Output:
Example 2: This example demonstrates the different styles of the horizontal rule or a thematic break in HTML.
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> <style> div { width: 200px; } body { background-color: #f0f0f0; width: 80px; float: center; } hr.class-1 { border-top: 10px solid #8c8b8b; } hr.class-2 { border-top: 3px double #8c8b8b; } hr.class-3 { border-top: 1px dashed #8c8b8b; } hr.class-4 { border-top: 1px dotted #8c8b8b; } hr.class-5 { background-color: #fff; border-top: 2px dashed #8c8b8b; } hr.class-6 { background-color: #fff; border-top: 5px dotted #8c8b8b; } </style></head> <body> <div> <hr class="class-1" /> <br /> <hr class="class-2" /> <br /> <hr class="class-3" /> <br /> <hr class="class-4" /> <br /> <hr class="class-5" /> <br /> <hr class="class-6" /> </div></body></html>
Output:
Supported Browsers:
Google Chrome 1.0
Microsoft Edge 12.0
Internet Explorer 5.5
Firefox 1.0
Opera 12.1
Safari 3.0
CSS is the foundation of web pages, is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
bhaskargeeksforgeeks
CSS-Misc
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to Upload Image into Database and Display it using PHP ?
Form validation using jQuery
Making a div vertically scrollable using CSS
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": 24286,
"s": 24258,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 24690,
"s": 24286,
"text": "The HTML <hr> tag is used to insert a horizontal rule or a thematic break in an HTML page to divide or separate document sections.The thickness of the hr tag can be set using the height property in CSS. The minimum height can be 1px since the smallest unit available is 1 pixel. Images can be added to make the hr tag more beautiful in appearance. It is an empty tag, and it does not require an end tag."
},
{
"code": null,
"e": 24698,
"s": 24690,
"text": "Syntax:"
},
{
"code": null,
"e": 24724,
"s": 24698,
"text": "<hr property: value;> ..."
},
{
"code": null,
"e": 24740,
"s": 24724,
"text": "Property value:"
},
{
"code": null,
"e": 24844,
"s": 24740,
"text": "align: It is used to specify the alignment of the horizontal rule. The values are left, center & right."
},
{
"code": null,
"e": 24937,
"s": 24844,
"text": "noshade: It is used to specify the bar without shading effect. The default value is noshade."
},
{
"code": null,
"e": 25029,
"s": 24937,
"text": "size: It is used to specify the height of the horizontal rule. The default value is pixels."
},
{
"code": null,
"e": 25121,
"s": 25029,
"text": "width: It is Used to specify the width of the horizontal rule. The default value is pixels."
},
{
"code": null,
"e": 25213,
"s": 25121,
"text": "color: It is used to specify the color of a Horizontal rule. It is not supported by HTML 5."
},
{
"code": null,
"e": 25277,
"s": 25213,
"text": "We will utilize the above property values through the examples."
},
{
"code": null,
"e": 25398,
"s": 25277,
"text": "Example 1: This example shows the basic use of the <hr> tag to insert a horizontal rule along with some CSS properties."
},
{
"code": null,
"e": 25403,
"s": 25398,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\" /> <title> Document </title> <style> div { width: 300px; } h1, h3 { color: green; } hr { position: relative; top: 20px; border: none; height: 12px; background: black; margin-bottom: 50px; } </style></head> <body> <center> <div> <h1>GeeksforGeeks</h1> <hr /> <h3>A Computer Science Portal</h3> </div> </center></body></html>",
"e": 26094,
"s": 25403,
"text": null
},
{
"code": null,
"e": 26102,
"s": 26094,
"text": "Output:"
},
{
"code": null,
"e": 26212,
"s": 26102,
"text": "Example 2: This example demonstrates the different styles of the horizontal rule or a thematic break in HTML."
},
{
"code": null,
"e": 26217,
"s": 26212,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\" /> <title>Document</title> <style> div { width: 200px; } body { background-color: #f0f0f0; width: 80px; float: center; } hr.class-1 { border-top: 10px solid #8c8b8b; } hr.class-2 { border-top: 3px double #8c8b8b; } hr.class-3 { border-top: 1px dashed #8c8b8b; } hr.class-4 { border-top: 1px dotted #8c8b8b; } hr.class-5 { background-color: #fff; border-top: 2px dashed #8c8b8b; } hr.class-6 { background-color: #fff; border-top: 5px dotted #8c8b8b; } </style></head> <body> <div> <hr class=\"class-1\" /> <br /> <hr class=\"class-2\" /> <br /> <hr class=\"class-3\" /> <br /> <hr class=\"class-4\" /> <br /> <hr class=\"class-5\" /> <br /> <hr class=\"class-6\" /> </div></body></html>",
"e": 27384,
"s": 26217,
"text": null
},
{
"code": null,
"e": 27392,
"s": 27384,
"text": "Output:"
},
{
"code": null,
"e": 27412,
"s": 27392,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 27430,
"s": 27412,
"text": "Google Chrome 1.0"
},
{
"code": null,
"e": 27450,
"s": 27430,
"text": "Microsoft Edge 12.0"
},
{
"code": null,
"e": 27472,
"s": 27450,
"text": "Internet Explorer 5.5"
},
{
"code": null,
"e": 27484,
"s": 27472,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 27495,
"s": 27484,
"text": "Opera 12.1"
},
{
"code": null,
"e": 27506,
"s": 27495,
"text": "Safari 3.0"
},
{
"code": null,
"e": 27694,
"s": 27506,
"text": "CSS is the foundation of web pages, is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 27715,
"s": 27694,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 27724,
"s": 27715,
"text": "CSS-Misc"
},
{
"code": null,
"e": 27731,
"s": 27724,
"text": "Picked"
},
{
"code": null,
"e": 27735,
"s": 27731,
"text": "CSS"
},
{
"code": null,
"e": 27752,
"s": 27735,
"text": "Web Technologies"
},
{
"code": null,
"e": 27850,
"s": 27752,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27891,
"s": 27850,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 27928,
"s": 27891,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 27989,
"s": 27928,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 28018,
"s": 27989,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28063,
"s": 28018,
"text": "Making a div vertically scrollable using CSS"
},
{
"code": null,
"e": 28105,
"s": 28063,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28138,
"s": 28105,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28181,
"s": 28138,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28226,
"s": 28181,
"text": "Convert a string to an integer in JavaScript"
}
] |
Convert a String to a List of Characters in Java
|
Let’s say the following is our string −
String str = "Website!";
Now, convert the above string to a list of characters −
List<Character>list = str.chars().mapToObj(n -> (char)n).collect(Collectors.toList());
Following is the program to convert a string to a list of characters in Java −
Live Demo
import java.util.*;
import java.util.stream.Collectors;
public class Demo {
public static void main(String[] args){
String str = "Website!";
System.out.println("String = "+str);
List<Character>list = str.chars().mapToObj(n -> (char)n).collect(Collectors.toList());
System.out.println("List of Characters = "+list);
}
}
String = Website!
List of Characters = [W, e, b, s, i, t, e, !]
|
[
{
"code": null,
"e": 1102,
"s": 1062,
"text": "Let’s say the following is our string −"
},
{
"code": null,
"e": 1127,
"s": 1102,
"text": "String str = \"Website!\";"
},
{
"code": null,
"e": 1183,
"s": 1127,
"text": "Now, convert the above string to a list of characters −"
},
{
"code": null,
"e": 1270,
"s": 1183,
"text": "List<Character>list = str.chars().mapToObj(n -> (char)n).collect(Collectors.toList());"
},
{
"code": null,
"e": 1349,
"s": 1270,
"text": "Following is the program to convert a string to a list of characters in Java −"
},
{
"code": null,
"e": 1360,
"s": 1349,
"text": " Live Demo"
},
{
"code": null,
"e": 1709,
"s": 1360,
"text": "import java.util.*;\nimport java.util.stream.Collectors;\npublic class Demo {\n public static void main(String[] args){\n String str = \"Website!\";\n System.out.println(\"String = \"+str);\n List<Character>list = str.chars().mapToObj(n -> (char)n).collect(Collectors.toList());\n System.out.println(\"List of Characters = \"+list);\n }\n}"
},
{
"code": null,
"e": 1773,
"s": 1709,
"text": "String = Website!\nList of Characters = [W, e, b, s, i, t, e, !]"
}
] |
How to remove the HTML tags from a given string in Java?
|
A String is a final class in Java and it is immutable, it means that we cannot change the object itself, but we can change the reference to the object. The HTML tags can be removed from a given string by using replaceAll() method of String class. We can remove the HTML tags from a given string by using a regular expression. After removing the HTML tags from a string, it will return a string as normal text.
public String replaceAll(String regex, String replacement)
public class RemoveHTMLTagsTest {
public static void main(String[] args) {
String str = "<p><b>Welcome to Tutorials Point</b></p>";
System.out.println("Before removing HTML Tags: " + str);
str = str.replaceAll("\\<.*?\\>", "");
System.out.println("After removing HTML Tags: " + str);
}
}
Before removing HTML Tags: <p><b>Welcome to Tutorials Point</b></p>
After removing HTML Tags: Welcome to Tutorials Point
|
[
{
"code": null,
"e": 1472,
"s": 1062,
"text": "A String is a final class in Java and it is immutable, it means that we cannot change the object itself, but we can change the reference to the object. The HTML tags can be removed from a given string by using replaceAll() method of String class. We can remove the HTML tags from a given string by using a regular expression. After removing the HTML tags from a string, it will return a string as normal text."
},
{
"code": null,
"e": 1531,
"s": 1472,
"text": "public String replaceAll(String regex, String replacement)"
},
{
"code": null,
"e": 1849,
"s": 1531,
"text": "public class RemoveHTMLTagsTest {\n public static void main(String[] args) {\n String str = \"<p><b>Welcome to Tutorials Point</b></p>\";\n System.out.println(\"Before removing HTML Tags: \" + str);\n str = str.replaceAll(\"\\\\<.*?\\\\>\", \"\");\n System.out.println(\"After removing HTML Tags: \" + str);\n }\n}"
},
{
"code": null,
"e": 1970,
"s": 1849,
"text": "Before removing HTML Tags: <p><b>Welcome to Tutorials Point</b></p>\nAfter removing HTML Tags: Welcome to Tutorials Point"
}
] |
The Pattern Matcher | Practice | GeeksforGeeks
|
All right! Let's implement some pattern-matching using CPP strings.
You are given a string s of x and y. You need to verify whether the string follows the pattern xnyn. That is the string is valid only if equal number of ys follow equal number of xs.As an example: xxyyxxyy is valid. xy is valid. xxyyx is invalid. xxxyyyxxyyxy is valid.
Example 1:
Input:s = xxyyOutput:1
Example 2:
Input:s = xyxOutput:0
Your Task:Since this is a function problem, you don't need to take any input. Just complete the function follPatt(string s) that outputs 1 if string is valid, else it outputs 0. In a new line, print 1 if the string is valid else print 0.Expected Time Complexity:O(|s|)Expected Auxilary Space:O(1)
Constraints:1 <= |s| <=100
0
hgaur7013 weeks ago
TIME TAKEN : 0.1 , TIME COMPLEXITY : O(n); AUXILARY CASE : O(1) , USING STACK CONTAINER.
void follPatt(string s)
{
stack<char> s1;
int n = s.length();
int ans = 1, i = 0;
if (n % 2 != 0)
{
cout << 0 << endl;
return;
}
else if (s.at(0) == 'y')
{
cout << 0 << endl;
return;
}
while (i < n)
{
while (s.at(i) == 'x')
{
s1.push(s.at(i));
i++;
if (i == n)
{
cout << 0 << endl;
return;
}
}
while (s.at(i) == 'y')
{
if (s1.empty() == true)
{
cout << 0 << endl;
return;
}
s1.pop();
i++;
if (i == n)
{
break;
}
}
if (s1.empty() != true)
{
ans = 0;
}
}
cout << ans << endl;
return;
}
+2
badgujarsachin833 months ago
void follPatt(string s)
{
//Your code here
int n=s.size();
int count=0,i=0,ans=1;
while(i<n){
while(s[i]=='x'){
count++;
i++;
}
while(s[i]=='y'){
count--;
i++;
}
if(count!=0){
ans=0;
}
}
cout<<ans<<endl;
}
0
mayank20213 months ago
C++void follPatt(string s) { if (s.size()&1) { cout<<"0"<<endl; return; } int countx=0, county=0, flag=0; for(int i=0; i<s.size(); i++) { if( flag==1 && (countx == county)) { countx=0; county=0; flag=0; } else if(flag==1) { cout<<"0"<<endl; return; } if(s[i]=='x') { countx++; } else if(s[i]=='y') { county++; if( (i==s.size()-1) && (countx != county)) { cout<<"0"<<endl; return; } else if (s[i+1] !='y') { flag=1; } } } cout<<"1"<<endl; }
0
darshitagupta3 months ago
void follPatt(string s) { //Your code here int count=0; int n=s.size(); int i=0; int ans =1; while(i<n) { while(s[i]=='x') { count ++; i++; } while(s[i]=='y') { count--; i++; } if(count!=0) ans=0; } cout<<ans; cout<<endl; }
0
_luffy_3 months ago
O(|s|) solution.
int countX=0;
int ans = 1;
int i=0;
while(i<s.size())
{
while(s[i] == 'x')
{
countX++;
i++;
}
while(s[i] == 'y')
{
countX--;
i++;
}
if(countX!=0)
ans = 0;
}
cout<<ans;
0
Rishi Verma10 months ago
Rishi Verma
Correct Answer. Execution Time:0.01https://uploads.disquscdn.c...
0
Aditya Sharan
This comment was deleted.
0
Aditya Sharan
This comment was deleted.
0
Aditya Sharan
This comment was deleted.
0
Aditya Sharan
This comment was deleted.
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": 294,
"s": 226,
"text": "All right! Let's implement some pattern-matching using CPP strings."
},
{
"code": null,
"e": 564,
"s": 294,
"text": "You are given a string s of x and y. You need to verify whether the string follows the pattern xnyn. That is the string is valid only if equal number of ys follow equal number of xs.As an example: xxyyxxyy is valid. xy is valid. xxyyx is invalid. xxxyyyxxyyxy is valid."
},
{
"code": null,
"e": 575,
"s": 564,
"text": "Example 1:"
},
{
"code": null,
"e": 598,
"s": 575,
"text": "Input:s = xxyyOutput:1"
},
{
"code": null,
"e": 609,
"s": 598,
"text": "Example 2:"
},
{
"code": null,
"e": 631,
"s": 609,
"text": "Input:s = xyxOutput:0"
},
{
"code": null,
"e": 928,
"s": 631,
"text": "Your Task:Since this is a function problem, you don't need to take any input. Just complete the function follPatt(string s) that outputs 1 if string is valid, else it outputs 0. In a new line, print 1 if the string is valid else print 0.Expected Time Complexity:O(|s|)Expected Auxilary Space:O(1)"
},
{
"code": null,
"e": 955,
"s": 928,
"text": "Constraints:1 <= |s| <=100"
},
{
"code": null,
"e": 957,
"s": 955,
"text": "0"
},
{
"code": null,
"e": 977,
"s": 957,
"text": "hgaur7013 weeks ago"
},
{
"code": null,
"e": 1067,
"s": 977,
"text": "TIME TAKEN : 0.1 , TIME COMPLEXITY : O(n); AUXILARY CASE : O(1) , USING STACK CONTAINER."
},
{
"code": null,
"e": 2157,
"s": 1069,
"text": "void follPatt(string s)\n {\n stack<char> s1;\n int n = s.length();\n int ans = 1, i = 0;\n\n if (n % 2 != 0)\n {\n cout << 0 << endl;\n return;\n }\n else if (s.at(0) == 'y')\n {\n cout << 0 << endl;\n return;\n }\n\n while (i < n)\n {\n\n while (s.at(i) == 'x')\n {\n s1.push(s.at(i));\n i++;\n if (i == n)\n {\n cout << 0 << endl;\n return;\n }\n }\n while (s.at(i) == 'y')\n {\n if (s1.empty() == true)\n {\n cout << 0 << endl;\n return;\n }\n s1.pop();\n i++;\n\n if (i == n)\n {\n break;\n }\n }\n if (s1.empty() != true)\n {\n ans = 0;\n }\n }\n cout << ans << endl;\n return;\n }"
},
{
"code": null,
"e": 2160,
"s": 2157,
"text": "+2"
},
{
"code": null,
"e": 2189,
"s": 2160,
"text": "badgujarsachin833 months ago"
},
{
"code": null,
"e": 2588,
"s": 2189,
"text": " void follPatt(string s)\n {\n //Your code here\n int n=s.size();\n int count=0,i=0,ans=1;\n while(i<n){\n while(s[i]=='x'){\n count++;\n i++;\n }\n while(s[i]=='y'){\n count--;\n i++;\n }\n if(count!=0){\n ans=0;\n }\n }\n cout<<ans<<endl;\n }"
},
{
"code": null,
"e": 2590,
"s": 2588,
"text": "0"
},
{
"code": null,
"e": 2613,
"s": 2590,
"text": "mayank20213 months ago"
},
{
"code": null,
"e": 3581,
"s": 2613,
"text": "C++void follPatt(string s) { if (s.size()&1) { cout<<\"0\"<<endl; return; } int countx=0, county=0, flag=0; for(int i=0; i<s.size(); i++) { if( flag==1 && (countx == county)) { countx=0; county=0; flag=0; } else if(flag==1) { cout<<\"0\"<<endl; return; } if(s[i]=='x') { countx++; } else if(s[i]=='y') { county++; if( (i==s.size()-1) && (countx != county)) { cout<<\"0\"<<endl; return; } else if (s[i+1] !='y') { flag=1; } } } cout<<\"1\"<<endl; }"
},
{
"code": null,
"e": 3583,
"s": 3581,
"text": "0"
},
{
"code": null,
"e": 3609,
"s": 3583,
"text": "darshitagupta3 months ago"
},
{
"code": null,
"e": 4015,
"s": 3609,
"text": "void follPatt(string s) { //Your code here int count=0; int n=s.size(); int i=0; int ans =1; while(i<n) { while(s[i]=='x') { count ++; i++; } while(s[i]=='y') { count--; i++; } if(count!=0) ans=0; } cout<<ans; cout<<endl; }"
},
{
"code": null,
"e": 4017,
"s": 4015,
"text": "0"
},
{
"code": null,
"e": 4037,
"s": 4017,
"text": "_luffy_3 months ago"
},
{
"code": null,
"e": 4054,
"s": 4037,
"text": "O(|s|) solution."
},
{
"code": null,
"e": 4427,
"s": 4056,
"text": "int countX=0;\n int ans = 1;\n int i=0;\n while(i<s.size())\n {\n while(s[i] == 'x')\n {\n countX++;\n i++;\n }\n while(s[i] == 'y')\n {\n countX--;\n i++;\n }\n if(countX!=0)\n ans = 0;\n }\n cout<<ans;"
},
{
"code": null,
"e": 4429,
"s": 4427,
"text": "0"
},
{
"code": null,
"e": 4454,
"s": 4429,
"text": "Rishi Verma10 months ago"
},
{
"code": null,
"e": 4466,
"s": 4454,
"text": "Rishi Verma"
},
{
"code": null,
"e": 4532,
"s": 4466,
"text": "Correct Answer. Execution Time:0.01https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 4534,
"s": 4532,
"text": "0"
},
{
"code": null,
"e": 4548,
"s": 4534,
"text": "Aditya Sharan"
},
{
"code": null,
"e": 4574,
"s": 4548,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4576,
"s": 4574,
"text": "0"
},
{
"code": null,
"e": 4590,
"s": 4576,
"text": "Aditya Sharan"
},
{
"code": null,
"e": 4616,
"s": 4590,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4618,
"s": 4616,
"text": "0"
},
{
"code": null,
"e": 4632,
"s": 4618,
"text": "Aditya Sharan"
},
{
"code": null,
"e": 4658,
"s": 4632,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4660,
"s": 4658,
"text": "0"
},
{
"code": null,
"e": 4674,
"s": 4660,
"text": "Aditya Sharan"
},
{
"code": null,
"e": 4700,
"s": 4674,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4846,
"s": 4700,
"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": 4882,
"s": 4846,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4892,
"s": 4882,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4902,
"s": 4892,
"text": "\nContest\n"
},
{
"code": null,
"e": 4965,
"s": 4902,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5113,
"s": 4965,
"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": 5321,
"s": 5113,
"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": 5427,
"s": 5321,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Angular Material - Tooltips
|
Angular Material provides various special methods to show unobtrusive tooltips to the users. It provides ways to assign directions for them and the md-tooltip directive is used to show tooltips. A tooltip activates whenever the user focuses, hovers over, or touches the parent component.
md-visible
This is Boolean bound and determines whether the tooltip is currently visible.
md-delay
How many milliseconds to wait to show the tooltip after the user focuses, hovers, or touches the parent. By default, it is 300ms.
md-autohide
If present or provided with a boolean value, the tooltip will hide on mouse leave, regardless of focus.
md-direction
This determines the direction in which the tooltip goes - supports left, right, top, and bottom. By default, the direction is towards bottom.
The following example shows the use of tooltips.
am_tooltips.htm
<html lang = "en">
<head>
<link rel = "stylesheet"
href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>
<link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons">
<script language = "javascript">
angular
.module('firstApplication', ['ngMaterial'])
.controller('tooltipController', tooltipController);
function tooltipController ($scope) {
$scope.demo = {
showTooltip : false,
tooltipDirection : ''
};
}
</script>
</head>
<body ng-app = "firstApplication">
<div id = "tooltipContainer" ng-controller = "tooltipController as ctrl"
layout = "column" style = "width:200px;margin-left: 100px; margin-right: 20px"
ng-cloak>
<br/><br/><br/>
<md-button class = "md-raised md-primary">Hello
<md-tooltip md-visible = "demo.showTooltip"
md-direction = "{{demo.tooltipDirection}}">Hello World!</md-tooltip>
</md-button>
<p>Tool Tip Direction </p>
<md-radio-group ng-model = "demo.tooltipDirection" >
<md-radio-button value = "left">Left </md-radio-button>
<md-radio-button value = "top">Top</md-radio-button>
<md-radio-button value = "bottom" class = "md-primary">
Bottom</md-radio-button>
<md-radio-button value = "right">Right</md-radio-button>
</md-radio-group>
</div>
</body>
</html>
Verify the result.
Tool Tip Directio.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2478,
"s": 2190,
"text": "Angular Material provides various special methods to show unobtrusive tooltips to the users. It provides ways to assign directions for them and the md-tooltip directive is used to show tooltips. A tooltip activates whenever the user focuses, hovers over, or touches the parent component."
},
{
"code": null,
"e": 2489,
"s": 2478,
"text": "md-visible"
},
{
"code": null,
"e": 2568,
"s": 2489,
"text": "This is Boolean bound and determines whether the tooltip is currently visible."
},
{
"code": null,
"e": 2577,
"s": 2568,
"text": "md-delay"
},
{
"code": null,
"e": 2707,
"s": 2577,
"text": "How many milliseconds to wait to show the tooltip after the user focuses, hovers, or touches the parent. By default, it is 300ms."
},
{
"code": null,
"e": 2719,
"s": 2707,
"text": "md-autohide"
},
{
"code": null,
"e": 2823,
"s": 2719,
"text": "If present or provided with a boolean value, the tooltip will hide on mouse leave, regardless of focus."
},
{
"code": null,
"e": 2836,
"s": 2823,
"text": "md-direction"
},
{
"code": null,
"e": 2978,
"s": 2836,
"text": "This determines the direction in which the tooltip goes - supports left, right, top, and bottom. By default, the direction is towards bottom."
},
{
"code": null,
"e": 3027,
"s": 2978,
"text": "The following example shows the use of tooltips."
},
{
"code": null,
"e": 3043,
"s": 3027,
"text": "am_tooltips.htm"
},
{
"code": null,
"e": 5234,
"s": 3043,
"text": "<html lang = \"en\">\n <head>\n <link rel = \"stylesheet\"\n href = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js\"></script>\n <link rel = \"stylesheet\" href = \"https://fonts.googleapis.com/icon?family=Material+Icons\">\n \n <script language = \"javascript\">\n angular\n .module('firstApplication', ['ngMaterial'])\n .controller('tooltipController', tooltipController);\n \n function tooltipController ($scope) { \n $scope.demo = {\n showTooltip : false,\n tooltipDirection : ''\n };\n }\t \n </script> \n </head>\n \n <body ng-app = \"firstApplication\"> \n <div id = \"tooltipContainer\" ng-controller = \"tooltipController as ctrl\"\n layout = \"column\" style = \"width:200px;margin-left: 100px; margin-right: 20px\"\n ng-cloak>\n <br/><br/><br/>\n \n <md-button class = \"md-raised md-primary\">Hello\n <md-tooltip md-visible = \"demo.showTooltip\" \n md-direction = \"{{demo.tooltipDirection}}\">Hello World!</md-tooltip>\n </md-button>\n \n <p>Tool Tip Direction </p>\n \n <md-radio-group ng-model = \"demo.tooltipDirection\" >\n <md-radio-button value = \"left\">Left </md-radio-button>\n <md-radio-button value = \"top\">Top</md-radio-button>\n <md-radio-button value = \"bottom\" class = \"md-primary\">\n Bottom</md-radio-button>\n <md-radio-button value = \"right\">Right</md-radio-button>\n </md-radio-group>\n \n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 5253,
"s": 5234,
"text": "Verify the result."
},
{
"code": null,
"e": 5272,
"s": 5253,
"text": "Tool Tip Directio."
},
{
"code": null,
"e": 5307,
"s": 5272,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5321,
"s": 5307,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5356,
"s": 5321,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5370,
"s": 5356,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5405,
"s": 5370,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5425,
"s": 5405,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 5460,
"s": 5425,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5477,
"s": 5460,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5510,
"s": 5477,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5522,
"s": 5510,
"text": " Senol Atac"
},
{
"code": null,
"e": 5557,
"s": 5522,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5569,
"s": 5557,
"text": " Senol Atac"
},
{
"code": null,
"e": 5576,
"s": 5569,
"text": " Print"
},
{
"code": null,
"e": 5587,
"s": 5576,
"text": " Add Notes"
}
] |
How to disable “Establishing SSL connection without server's identity verification is not recommended” warning when connecting to MySQL database in Java?
|
To disable the warning while connecting to a database in Java, use the below concept −
autoReconnect=true&useSSL=false
The complete syntax is as follows −
yourJdbcURL="jdbc:mysql://localhost:yourPortNumber/yourDatabaseName?autoReconnect=true&useSSL=false";
Here is the warning message if you do not include “useSSL=false” −
Wed Feb 06 18:53:39 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
The snapshot is as follows −
If you want to avoid the above MySQL warning, use the syntax mention in the beginning.
The Java code is as follows −
import java.sql.Connection;
import java.sql.DriverManager;
public class AvoidSQLWarnDemo {
public static void main(String[] args) {
String JdbcURL = "jdbc:mysql://localhost:3306/mybusiness?" + "autoReconnect=true&useSSL=false";
String Username = "root";
String password = "123456";
Connection con = null;
try {
con = DriverManager.getConnection(JdbcURL, Username, password);
System.out.println("Your JDBC URL is as follows:" + JdbcURL);
} catch (Exception exec) {
exec.printStackTrace();
}
}
}
After running the above java program, you won’t get the warning. However, you will get the following output −
|
[
{
"code": null,
"e": 1149,
"s": 1062,
"text": "To disable the warning while connecting to a database in Java, use the below concept −"
},
{
"code": null,
"e": 1181,
"s": 1149,
"text": "autoReconnect=true&useSSL=false"
},
{
"code": null,
"e": 1217,
"s": 1181,
"text": "The complete syntax is as follows −"
},
{
"code": null,
"e": 1319,
"s": 1217,
"text": "yourJdbcURL=\"jdbc:mysql://localhost:yourPortNumber/yourDatabaseName?autoReconnect=true&useSSL=false\";"
},
{
"code": null,
"e": 1386,
"s": 1319,
"text": "Here is the warning message if you do not include “useSSL=false” −"
},
{
"code": null,
"e": 1902,
"s": 1386,
"text": "Wed Feb 06 18:53:39 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification."
},
{
"code": null,
"e": 1931,
"s": 1902,
"text": "The snapshot is as follows −"
},
{
"code": null,
"e": 2018,
"s": 1931,
"text": "If you want to avoid the above MySQL warning, use the syntax mention in the beginning."
},
{
"code": null,
"e": 2048,
"s": 2018,
"text": "The Java code is as follows −"
},
{
"code": null,
"e": 2617,
"s": 2048,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\npublic class AvoidSQLWarnDemo {\n public static void main(String[] args) {\n String JdbcURL = \"jdbc:mysql://localhost:3306/mybusiness?\" + \"autoReconnect=true&useSSL=false\";\n String Username = \"root\";\n String password = \"123456\";\n Connection con = null;\n try {\n con = DriverManager.getConnection(JdbcURL, Username, password);\n System.out.println(\"Your JDBC URL is as follows:\" + JdbcURL);\n } catch (Exception exec) {\n exec.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 2727,
"s": 2617,
"text": "After running the above java program, you won’t get the warning. However, you will get the following output −"
}
] |
Basic Ensemble Learning (Random Forest, AdaBoost, Gradient Boosting)- Step by Step Explained | by Lilly Chen | Towards Data Science
|
We all do that. Before we make any big decisions, we ask people’s opinions, like our friends, our family members, even our dogs/cats, to prevent us from being biased😕 or irrational😍.
The model does that too. it is very common that the individual model suffers from bias or variances and that’s why we need the ensemble learning.
Ensemble learning, in general, is a model that makes predictions based on a number of different models. By combining individual models, the ensemble model tends to be more flexible🤸♀️ (less bias) and less data-sensitive🧘♀️ (less variance).
Two most popular ensemble methods are bagging and boosting.
Bagging: Training a bunch of individual models in a parallel way. Each model is trained by a random subset of the data
Boosting: Training a bunch of individual models in a sequential way. Each individual model learns from mistakes made by the previous model.
With a basic understanding of what ensemble learning is, let’s grow some “trees” 🎄.
The following content will cover step by step explanation on Random Forest, AdaBoost, and Gradient Boosting, and their implementation in Python Sklearn.
Random forest is an ensemble model using bagging as the ensemble method and decision tree as the individual model.
Let’s take a closer look at the magic🔮 of the randomness:
Step 1: Select n (e.g. 1000) random subsets from the training set
Step 2: Train n (e.g. 1000) decision trees
one random subset is used to train one decision tree
the optimal splits for each decision tree are based on a random subset of features (e.g. 10 features in total, randomly select 5 out of 10 features to split)
Step 3: Each individual tree predicts the records/candidates in the test set, independently.
Step 4: Make the final prediction
For each candidate in the test set, Random Forest uses the class (e.g. cat or dog) with the majority vote as this candidate’s final prediction.
Of course, our 1000 trees are the parliament here.
AdaBoost is a boosting ensemble model and works especially well with the decision tree. Boosting model’s key is learning from the previous mistakes, e.g. misclassification data points.
AdaBoost learns from the mistakes by increasing the weight of misclassified data points.
Let’s illustrate how AdaBoost adapts.
Step 0: Initialize the weights of data points. if the training set has 100 data points, then each point’s initial weight should be 1/100 = 0.01.
Step 1: Train a decision tree
Step 2: Calculate the weighted error rate (e) of the decision tree. The weighted error rate (e) is just how many wrong predictions out of total and you treat the wrong predictions differently based on its data point’s weight. The higher the weight, the more the corresponding error will be weighted during the calculation of the (e).
Step 3: Calculate this decision tree’s weight in the ensemble
the weight of this tree = learning rate * log( (1 — e) / e)
the higher weighted error rate of a tree, 😫, the less decision power the tree will be given during the later voting
the lower weighted error rate of a tree, 😃, the higher decision power the tree will be given during the later voting
Step 4: Update weights of wrongly classified points
the weight of each data point =
if the model got this data point correct, the weight stays the same
if the model got this data point wrong, the new weight of this point = old weight * np.exp(weight of this tree)
Note: The higher the weight of the tree (more accurate this tree performs), the more boost (importance) the misclassified data point by this tree will get. The weights of the data points are normalized after all the misclassified points are updated.
Step 5: Repeat Step 1(until the number of trees we set to train is reached)
Step 6: Make the final prediction
The AdaBoost makes a new prediction by adding up the weight (of each tree) multiply the prediction (of each tree). Obviously, the tree with higher weight will have more power of influence the final decision.
Gradient boosting is another boosting model. Remember, boosting model’s key is learning from the previous mistakes.
Gradient Boosting learns from the mistake — residual error directly, rather than update the weights of data points.
Let’s illustrate how Gradient Boost learns.
Step 1: Train a decision tree
Step 2: Apply the decision tree just trained to predict
Step 3: Calculate the residual of this decision tree, Save residual errors as the new y
Step 4: Repeat Step 1 (until the number of trees we set to train is reached)
Step 5: Make the final prediction
The Gradient Boosting makes a new prediction by simply adding up the predictions (of all trees).
Here is a simple implementation of those three methods explained above in Python Sklearn.
# Load Libraryfrom sklearn.datasets import make_moonsfrom sklearn.metrics import accuracy_scorefrom sklearn.model_selection import train_test_splitfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.ensemble import RandomForestClassifier,AdaBoostClassifier,GradientBoostingClassifier# Step1: Create data setX, y = make_moons(n_samples=10000, noise=.5, random_state=0)# Step2: Split the training test setX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# Step 3: Fit a Decision Tree model as comparisonclf = DecisionTreeClassifier()clf.fit(X_train, y_train)y_pred = clf.predict(X_test)accuracy_score(y_test, y_pred)OUTPUT: 0.756# Step 4: Fit a Random Forest model, " compared to "Decision Tree model, accuracy go up by 5%clf = RandomForestClassifier(n_estimators=100, max_features="auto",random_state=0)clf.fit(X_train, y_train)y_pred = clf.predict(X_test)accuracy_score(y_test, y_pred)OUTPUT: 0.797# Step 5: Fit a AdaBoost model, " compared to "Decision Tree model, accuracy go up by 10%clf = AdaBoostClassifier(n_estimators=100)clf.fit(X_train, y_train)y_pred = clf.predict(X_test)accuracy_score(y_test, y_pred)OUTPUT:0.833# Step 6: Fit a Gradient Boosting model, " compared to "Decision Tree model, accuracy go up by 10%clf = GradientBoostingClassifier(n_estimators=100)clf.fit(X_train, y_train)y_pred = clf.predict(X_test)accuracy_score(y_test, y_pred)OUTPUT:0.834Note: Parameter - n_estimators stands for how many tree we want to grow
Overall, ensemble learning is very powerful and can be used not only for classification problem but regression also. In this blog, I only apply decision tree as the individual model within those ensemble methods, but other individual models (linear model, SVM, etc.)can also be applied within the bagging or boosting ensembles, to lead better performance.
The code for this blog can be found in my GitHub Link here also.
Please feel free to leave any comment, question or suggestion below. Thank you!
|
[
{
"code": null,
"e": 354,
"s": 171,
"text": "We all do that. Before we make any big decisions, we ask people’s opinions, like our friends, our family members, even our dogs/cats, to prevent us from being biased😕 or irrational😍."
},
{
"code": null,
"e": 500,
"s": 354,
"text": "The model does that too. it is very common that the individual model suffers from bias or variances and that’s why we need the ensemble learning."
},
{
"code": null,
"e": 742,
"s": 500,
"text": "Ensemble learning, in general, is a model that makes predictions based on a number of different models. By combining individual models, the ensemble model tends to be more flexible🤸♀️ (less bias) and less data-sensitive🧘♀️ (less variance)."
},
{
"code": null,
"e": 802,
"s": 742,
"text": "Two most popular ensemble methods are bagging and boosting."
},
{
"code": null,
"e": 921,
"s": 802,
"text": "Bagging: Training a bunch of individual models in a parallel way. Each model is trained by a random subset of the data"
},
{
"code": null,
"e": 1061,
"s": 921,
"text": "Boosting: Training a bunch of individual models in a sequential way. Each individual model learns from mistakes made by the previous model."
},
{
"code": null,
"e": 1145,
"s": 1061,
"text": "With a basic understanding of what ensemble learning is, let’s grow some “trees” 🎄."
},
{
"code": null,
"e": 1298,
"s": 1145,
"text": "The following content will cover step by step explanation on Random Forest, AdaBoost, and Gradient Boosting, and their implementation in Python Sklearn."
},
{
"code": null,
"e": 1413,
"s": 1298,
"text": "Random forest is an ensemble model using bagging as the ensemble method and decision tree as the individual model."
},
{
"code": null,
"e": 1471,
"s": 1413,
"text": "Let’s take a closer look at the magic🔮 of the randomness:"
},
{
"code": null,
"e": 1537,
"s": 1471,
"text": "Step 1: Select n (e.g. 1000) random subsets from the training set"
},
{
"code": null,
"e": 1580,
"s": 1537,
"text": "Step 2: Train n (e.g. 1000) decision trees"
},
{
"code": null,
"e": 1633,
"s": 1580,
"text": "one random subset is used to train one decision tree"
},
{
"code": null,
"e": 1791,
"s": 1633,
"text": "the optimal splits for each decision tree are based on a random subset of features (e.g. 10 features in total, randomly select 5 out of 10 features to split)"
},
{
"code": null,
"e": 1884,
"s": 1791,
"text": "Step 3: Each individual tree predicts the records/candidates in the test set, independently."
},
{
"code": null,
"e": 1918,
"s": 1884,
"text": "Step 4: Make the final prediction"
},
{
"code": null,
"e": 2062,
"s": 1918,
"text": "For each candidate in the test set, Random Forest uses the class (e.g. cat or dog) with the majority vote as this candidate’s final prediction."
},
{
"code": null,
"e": 2113,
"s": 2062,
"text": "Of course, our 1000 trees are the parliament here."
},
{
"code": null,
"e": 2298,
"s": 2113,
"text": "AdaBoost is a boosting ensemble model and works especially well with the decision tree. Boosting model’s key is learning from the previous mistakes, e.g. misclassification data points."
},
{
"code": null,
"e": 2387,
"s": 2298,
"text": "AdaBoost learns from the mistakes by increasing the weight of misclassified data points."
},
{
"code": null,
"e": 2425,
"s": 2387,
"text": "Let’s illustrate how AdaBoost adapts."
},
{
"code": null,
"e": 2570,
"s": 2425,
"text": "Step 0: Initialize the weights of data points. if the training set has 100 data points, then each point’s initial weight should be 1/100 = 0.01."
},
{
"code": null,
"e": 2600,
"s": 2570,
"text": "Step 1: Train a decision tree"
},
{
"code": null,
"e": 2934,
"s": 2600,
"text": "Step 2: Calculate the weighted error rate (e) of the decision tree. The weighted error rate (e) is just how many wrong predictions out of total and you treat the wrong predictions differently based on its data point’s weight. The higher the weight, the more the corresponding error will be weighted during the calculation of the (e)."
},
{
"code": null,
"e": 2996,
"s": 2934,
"text": "Step 3: Calculate this decision tree’s weight in the ensemble"
},
{
"code": null,
"e": 3056,
"s": 2996,
"text": "the weight of this tree = learning rate * log( (1 — e) / e)"
},
{
"code": null,
"e": 3172,
"s": 3056,
"text": "the higher weighted error rate of a tree, 😫, the less decision power the tree will be given during the later voting"
},
{
"code": null,
"e": 3289,
"s": 3172,
"text": "the lower weighted error rate of a tree, 😃, the higher decision power the tree will be given during the later voting"
},
{
"code": null,
"e": 3341,
"s": 3289,
"text": "Step 4: Update weights of wrongly classified points"
},
{
"code": null,
"e": 3373,
"s": 3341,
"text": "the weight of each data point ="
},
{
"code": null,
"e": 3441,
"s": 3373,
"text": "if the model got this data point correct, the weight stays the same"
},
{
"code": null,
"e": 3553,
"s": 3441,
"text": "if the model got this data point wrong, the new weight of this point = old weight * np.exp(weight of this tree)"
},
{
"code": null,
"e": 3803,
"s": 3553,
"text": "Note: The higher the weight of the tree (more accurate this tree performs), the more boost (importance) the misclassified data point by this tree will get. The weights of the data points are normalized after all the misclassified points are updated."
},
{
"code": null,
"e": 3879,
"s": 3803,
"text": "Step 5: Repeat Step 1(until the number of trees we set to train is reached)"
},
{
"code": null,
"e": 3913,
"s": 3879,
"text": "Step 6: Make the final prediction"
},
{
"code": null,
"e": 4121,
"s": 3913,
"text": "The AdaBoost makes a new prediction by adding up the weight (of each tree) multiply the prediction (of each tree). Obviously, the tree with higher weight will have more power of influence the final decision."
},
{
"code": null,
"e": 4237,
"s": 4121,
"text": "Gradient boosting is another boosting model. Remember, boosting model’s key is learning from the previous mistakes."
},
{
"code": null,
"e": 4353,
"s": 4237,
"text": "Gradient Boosting learns from the mistake — residual error directly, rather than update the weights of data points."
},
{
"code": null,
"e": 4397,
"s": 4353,
"text": "Let’s illustrate how Gradient Boost learns."
},
{
"code": null,
"e": 4427,
"s": 4397,
"text": "Step 1: Train a decision tree"
},
{
"code": null,
"e": 4483,
"s": 4427,
"text": "Step 2: Apply the decision tree just trained to predict"
},
{
"code": null,
"e": 4571,
"s": 4483,
"text": "Step 3: Calculate the residual of this decision tree, Save residual errors as the new y"
},
{
"code": null,
"e": 4648,
"s": 4571,
"text": "Step 4: Repeat Step 1 (until the number of trees we set to train is reached)"
},
{
"code": null,
"e": 4682,
"s": 4648,
"text": "Step 5: Make the final prediction"
},
{
"code": null,
"e": 4779,
"s": 4682,
"text": "The Gradient Boosting makes a new prediction by simply adding up the predictions (of all trees)."
},
{
"code": null,
"e": 4869,
"s": 4779,
"text": "Here is a simple implementation of those three methods explained above in Python Sklearn."
},
{
"code": null,
"e": 6356,
"s": 4869,
"text": "# Load Libraryfrom sklearn.datasets import make_moonsfrom sklearn.metrics import accuracy_scorefrom sklearn.model_selection import train_test_splitfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.ensemble import RandomForestClassifier,AdaBoostClassifier,GradientBoostingClassifier# Step1: Create data setX, y = make_moons(n_samples=10000, noise=.5, random_state=0)# Step2: Split the training test setX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# Step 3: Fit a Decision Tree model as comparisonclf = DecisionTreeClassifier()clf.fit(X_train, y_train)y_pred = clf.predict(X_test)accuracy_score(y_test, y_pred)OUTPUT: 0.756# Step 4: Fit a Random Forest model, \" compared to \"Decision Tree model, accuracy go up by 5%clf = RandomForestClassifier(n_estimators=100, max_features=\"auto\",random_state=0)clf.fit(X_train, y_train)y_pred = clf.predict(X_test)accuracy_score(y_test, y_pred)OUTPUT: 0.797# Step 5: Fit a AdaBoost model, \" compared to \"Decision Tree model, accuracy go up by 10%clf = AdaBoostClassifier(n_estimators=100)clf.fit(X_train, y_train)y_pred = clf.predict(X_test)accuracy_score(y_test, y_pred)OUTPUT:0.833# Step 6: Fit a Gradient Boosting model, \" compared to \"Decision Tree model, accuracy go up by 10%clf = GradientBoostingClassifier(n_estimators=100)clf.fit(X_train, y_train)y_pred = clf.predict(X_test)accuracy_score(y_test, y_pred)OUTPUT:0.834Note: Parameter - n_estimators stands for how many tree we want to grow"
},
{
"code": null,
"e": 6712,
"s": 6356,
"text": "Overall, ensemble learning is very powerful and can be used not only for classification problem but regression also. In this blog, I only apply decision tree as the individual model within those ensemble methods, but other individual models (linear model, SVM, etc.)can also be applied within the bagging or boosting ensembles, to lead better performance."
},
{
"code": null,
"e": 6777,
"s": 6712,
"text": "The code for this blog can be found in my GitHub Link here also."
}
] |
CSS content Property - GeeksforGeeks
|
21 Oct, 2021
The content property in CSS is used to generate the content dynamically (during run time) ie., it replaces the element with generated content value. It is used to generate content ::before & ::after pseudo-element.
Syntax:
content: normal|none|counter|attr|string|open-quote|close-quote|
no-open-quote|no-close-quote|url|initial|inherit;
Property Values: All the properties are described well with the example below.
normal: It is used to set the content if the content property is normal, also, it is used to sets the default value.
Syntax:
Element::before|after {
content: normal;
}
Example: This example demonstrates the use of the content property to generate content ::before & ::after pseudo-element.
HTML
<!DOCTYPE html><html><head> <title> CSS | content Property </title> <style> p::before { content: "Welcome "; } a::before { content: normal; } </style></head> <body> <p>to GeeksforGeeks</p> <p id="a">you</p> </body></html>
Output:
Welcome to GeeksforGeeks
Welcome you
none: It does not set the content before and after the pseudo-element.
Syntax:
Element::before|after {
content: none;
}
Example: This example demonstrates the use of the content property where the content inside the <p> tag, will be displayed dynamically with different values.
HTML
<!DOCTYPE html><html><head> <title> CSS | content Property </title> <style> p::before { content: "Hello"; } p#a::before { content: none; } </style></head> <body> <p> GeeksforGeeks!</p> <p id="a">Welcomes to GeeksforGeeks!</p> </body></html>
Output:
Hello GeeksforGeeks!
Welcome to GeeksforGeeks!
initial: It sets the property to its default value.
Syntax:
Element::before|after {
content: initial;
}
Example: This example demonstrates the use of the content property where the content is displayed to its initial value.
HTML
<!DOCTYPE html><html><head> <title> CSS | content Property </title> <style> p::before { content: "Welcome "; } a::before { content: initial; } </style></head> <body> <p>to GeeksforGeeks</p> <p id="a">you</p> </body></html>
Output:
Hello GeeksforGeeks!
Hello Welcomes to GeeksforGeeks!
attribute: It sets the attribute value containing a specified value.
Syntax:
Element::before|after {
content:attr(href);
}
Example: This example demonstrates the use of the content property where the attribute value is set to the specified values.
HTML
<!DOCTYPE html><html><head> <title> CSS | content Property </title> <style> a::after { content: attr(href); } </style></head> <body> <a href="https://www.geeksforgeeks.org/html-style-attribute/"> Click Here! </a> </body></html>
Output:
Click Here! https://www.geeksforgeeks.org/html-style-attribute/
String: It is used to generate any string before and after the HTML element.
Syntax:
Element::before|after {
content: string;
}
Example: This example demonstrates the use of the content property where the string value will generate any string before and after the HTML element.
HTML
<!DOCTYPE html><html><head> <title>CSS | content Property</title> <style> /* String value used here */ p::before { content: "Hello"; } </style></head> <body> <p> GeeksforGeeks!</p> </body></html>
Output:
Hello GeeksforGeeks!
open-quote: It generates an opening quote before and after an element.
Syntax:
Element::before|after {
content: open-quote;
}
Example: This example demonstrates the use of the content property where the property value of content is set to open-quote.
HTML
<!DOCTYPE html><html><head> <title> CSS | content Property </title> <style> p::before { content: open-quote; } </style></head> <body> <p>Welcome to GeeksforGeeks!</p></body></html>
Output:
"Welcome to GeeksforGeeks!
close-quote: It generates a closing quote before and after an element.
Syntax:
Element::before|after {
content: close-quote;
}
Example: This example demonstrates the use of the content property where the property value of content is set to close-quote.
HTML
<!DOCTYPE html><html><head> <title> CSS | content Property </title> <style> p::after { content: close-quote; } p::before { content: open-quote; } </style></head> <body> <p>Welcome to GeeksforGeeks!</p></body></html>
Output:
"Welcome to GeeksforGeeks!"
no-open-quote: It removes the opening quote from the content if it is specified.
Syntax:
Element::before|after {
content: no-open-quote;
}
Example: This example demonstrates the use of the content property where the property value of content is set to no-open-quote.
HTML
<!DOCTYPE html><html><head> <title> CSS | content Property </title> <style> p::before { content: open-quote; } p::before { content: no-open-quote; } </style></head> <body> <p>Welcome to GeeksforGeeks!</p> </body></html>
Output:
Welcome to GeeksforGeeks!
no-close-quote: It removes closing quotes from the content if it is specified.
Syntax:
Element::before|after {
content: no-close-quote;
}
Example: This example demonstrates the use of the content property where the property value of content is set to no-close-quote.
HTML
<!DOCTYPE html><html><head> <title> CSS | content Property </title> <style> p::before { content: open-quote; } p::after { content: no-close-quote; } </style></head><body> <p>Welcome to GeeksforGeeks!</p></body></html>
Output:
"Welcome to GeeksforGeeks!
inherit: This property is inherited from its parent element.
Syntax:
Element::before|after {
content: inherit;
}
Supported Browsers: The browser supported by the content property are listed below:
Google Chrome 1.0
Internet Explorer 8.0
Microsoft Edge 12.0
Firefox 1.0
Opera 4.0
Safari 1.0
ManasChhabra2
bhaskargeeksforgeeks
CSS-Properties
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 23645,
"s": 23617,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 23860,
"s": 23645,
"text": "The content property in CSS is used to generate the content dynamically (during run time) ie., it replaces the element with generated content value. It is used to generate content ::before & ::after pseudo-element."
},
{
"code": null,
"e": 23868,
"s": 23860,
"text": "Syntax:"
},
{
"code": null,
"e": 23983,
"s": 23868,
"text": "content: normal|none|counter|attr|string|open-quote|close-quote|\nno-open-quote|no-close-quote|url|initial|inherit;"
},
{
"code": null,
"e": 24062,
"s": 23983,
"text": "Property Values: All the properties are described well with the example below."
},
{
"code": null,
"e": 24179,
"s": 24062,
"text": "normal: It is used to set the content if the content property is normal, also, it is used to sets the default value."
},
{
"code": null,
"e": 24188,
"s": 24179,
"text": "Syntax: "
},
{
"code": null,
"e": 24236,
"s": 24188,
"text": "Element::before|after { \n content: normal;\n}"
},
{
"code": null,
"e": 24358,
"s": 24236,
"text": "Example: This example demonstrates the use of the content property to generate content ::before & ::after pseudo-element."
},
{
"code": null,
"e": 24363,
"s": 24358,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title> CSS | content Property </title> <style> p::before { content: \"Welcome \"; } a::before { content: normal; } </style></head> <body> <p>to GeeksforGeeks</p> <p id=\"a\">you</p> </body></html>",
"e": 24636,
"s": 24363,
"text": null
},
{
"code": null,
"e": 24645,
"s": 24636,
"text": "Output: "
},
{
"code": null,
"e": 24682,
"s": 24645,
"text": "Welcome to GeeksforGeeks\nWelcome you"
},
{
"code": null,
"e": 24753,
"s": 24682,
"text": "none: It does not set the content before and after the pseudo-element."
},
{
"code": null,
"e": 24762,
"s": 24753,
"text": "Syntax: "
},
{
"code": null,
"e": 24808,
"s": 24762,
"text": "Element::before|after { \n content: none;\n}"
},
{
"code": null,
"e": 24966,
"s": 24808,
"text": "Example: This example demonstrates the use of the content property where the content inside the <p> tag, will be displayed dynamically with different values."
},
{
"code": null,
"e": 24971,
"s": 24966,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title> CSS | content Property </title> <style> p::before { content: \"Hello\"; } p#a::before { content: none; } </style></head> <body> <p> GeeksforGeeks!</p> <p id=\"a\">Welcomes to GeeksforGeeks!</p> </body></html>",
"e": 25263,
"s": 24971,
"text": null
},
{
"code": null,
"e": 25272,
"s": 25263,
"text": "Output: "
},
{
"code": null,
"e": 25319,
"s": 25272,
"text": "Hello GeeksforGeeks!\nWelcome to GeeksforGeeks!"
},
{
"code": null,
"e": 25371,
"s": 25319,
"text": "initial: It sets the property to its default value."
},
{
"code": null,
"e": 25379,
"s": 25371,
"text": "Syntax:"
},
{
"code": null,
"e": 25427,
"s": 25379,
"text": "Element::before|after {\n content: initial;\n}"
},
{
"code": null,
"e": 25547,
"s": 25427,
"text": "Example: This example demonstrates the use of the content property where the content is displayed to its initial value."
},
{
"code": null,
"e": 25552,
"s": 25547,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title> CSS | content Property </title> <style> p::before { content: \"Welcome \"; } a::before { content: initial; } </style></head> <body> <p>to GeeksforGeeks</p> <p id=\"a\">you</p> </body></html>",
"e": 25826,
"s": 25552,
"text": null
},
{
"code": null,
"e": 25835,
"s": 25826,
"text": "Output: "
},
{
"code": null,
"e": 25889,
"s": 25835,
"text": "Hello GeeksforGeeks!\nHello Welcomes to GeeksforGeeks!"
},
{
"code": null,
"e": 25958,
"s": 25889,
"text": "attribute: It sets the attribute value containing a specified value."
},
{
"code": null,
"e": 25967,
"s": 25958,
"text": "Syntax: "
},
{
"code": null,
"e": 26019,
"s": 25967,
"text": "Element::before|after { \n content:attr(href); \n}"
},
{
"code": null,
"e": 26144,
"s": 26019,
"text": "Example: This example demonstrates the use of the content property where the attribute value is set to the specified values."
},
{
"code": null,
"e": 26149,
"s": 26144,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title> CSS | content Property </title> <style> a::after { content: attr(href); } </style></head> <body> <a href=\"https://www.geeksforgeeks.org/html-style-attribute/\"> Click Here! </a> </body></html>",
"e": 26416,
"s": 26149,
"text": null
},
{
"code": null,
"e": 26424,
"s": 26416,
"text": "Output:"
},
{
"code": null,
"e": 26488,
"s": 26424,
"text": "Click Here! https://www.geeksforgeeks.org/html-style-attribute/"
},
{
"code": null,
"e": 26565,
"s": 26488,
"text": "String: It is used to generate any string before and after the HTML element."
},
{
"code": null,
"e": 26573,
"s": 26565,
"text": "Syntax:"
},
{
"code": null,
"e": 26621,
"s": 26573,
"text": "Element::before|after { \n content: string;\n}"
},
{
"code": null,
"e": 26771,
"s": 26621,
"text": "Example: This example demonstrates the use of the content property where the string value will generate any string before and after the HTML element."
},
{
"code": null,
"e": 26776,
"s": 26771,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>CSS | content Property</title> <style> /* String value used here */ p::before { content: \"Hello\"; } </style></head> <body> <p> GeeksforGeeks!</p> </body></html>",
"e": 27025,
"s": 26776,
"text": null
},
{
"code": null,
"e": 27034,
"s": 27025,
"text": "Output: "
},
{
"code": null,
"e": 27055,
"s": 27034,
"text": "Hello GeeksforGeeks!"
},
{
"code": null,
"e": 27126,
"s": 27055,
"text": "open-quote: It generates an opening quote before and after an element."
},
{
"code": null,
"e": 27134,
"s": 27126,
"text": "Syntax:"
},
{
"code": null,
"e": 27186,
"s": 27134,
"text": "Element::before|after { \n content: open-quote;\n}"
},
{
"code": null,
"e": 27311,
"s": 27186,
"text": "Example: This example demonstrates the use of the content property where the property value of content is set to open-quote."
},
{
"code": null,
"e": 27316,
"s": 27311,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title> CSS | content Property </title> <style> p::before { content: open-quote; } </style></head> <body> <p>Welcome to GeeksforGeeks!</p></body></html>",
"e": 27536,
"s": 27316,
"text": null
},
{
"code": null,
"e": 27544,
"s": 27536,
"text": "Output:"
},
{
"code": null,
"e": 27571,
"s": 27544,
"text": "\"Welcome to GeeksforGeeks!"
},
{
"code": null,
"e": 27642,
"s": 27571,
"text": "close-quote: It generates a closing quote before and after an element."
},
{
"code": null,
"e": 27650,
"s": 27642,
"text": "Syntax:"
},
{
"code": null,
"e": 27703,
"s": 27650,
"text": "Element::before|after { \n content: close-quote;\n}"
},
{
"code": null,
"e": 27829,
"s": 27703,
"text": "Example: This example demonstrates the use of the content property where the property value of content is set to close-quote."
},
{
"code": null,
"e": 27834,
"s": 27829,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title> CSS | content Property </title> <style> p::after { content: close-quote; } p::before { content: open-quote; } </style></head> <body> <p>Welcome to GeeksforGeeks!</p></body></html>",
"e": 28116,
"s": 27834,
"text": null
},
{
"code": null,
"e": 28124,
"s": 28116,
"text": "Output:"
},
{
"code": null,
"e": 28152,
"s": 28124,
"text": "\"Welcome to GeeksforGeeks!\""
},
{
"code": null,
"e": 28233,
"s": 28152,
"text": "no-open-quote: It removes the opening quote from the content if it is specified."
},
{
"code": null,
"e": 28242,
"s": 28233,
"text": "Syntax: "
},
{
"code": null,
"e": 28297,
"s": 28242,
"text": "Element::before|after { \n content: no-open-quote;\n}"
},
{
"code": null,
"e": 28425,
"s": 28297,
"text": "Example: This example demonstrates the use of the content property where the property value of content is set to no-open-quote."
},
{
"code": null,
"e": 28430,
"s": 28425,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title> CSS | content Property </title> <style> p::before { content: open-quote; } p::before { content: no-open-quote; } </style></head> <body> <p>Welcome to GeeksforGeeks!</p> </body></html>",
"e": 28715,
"s": 28430,
"text": null
},
{
"code": null,
"e": 28724,
"s": 28715,
"text": "Output: "
},
{
"code": null,
"e": 28750,
"s": 28724,
"text": "Welcome to GeeksforGeeks!"
},
{
"code": null,
"e": 28829,
"s": 28750,
"text": "no-close-quote: It removes closing quotes from the content if it is specified."
},
{
"code": null,
"e": 28837,
"s": 28829,
"text": "Syntax:"
},
{
"code": null,
"e": 28893,
"s": 28837,
"text": "Element::before|after { \n content: no-close-quote;\n}"
},
{
"code": null,
"e": 29022,
"s": 28893,
"text": "Example: This example demonstrates the use of the content property where the property value of content is set to no-close-quote."
},
{
"code": null,
"e": 29027,
"s": 29022,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title> CSS | content Property </title> <style> p::before { content: open-quote; } p::after { content: no-close-quote; } </style></head><body> <p>Welcome to GeeksforGeeks!</p></body></html>",
"e": 29307,
"s": 29027,
"text": null
},
{
"code": null,
"e": 29315,
"s": 29307,
"text": "Output:"
},
{
"code": null,
"e": 29342,
"s": 29315,
"text": "\"Welcome to GeeksforGeeks!"
},
{
"code": null,
"e": 29403,
"s": 29342,
"text": "inherit: This property is inherited from its parent element."
},
{
"code": null,
"e": 29412,
"s": 29403,
"text": "Syntax: "
},
{
"code": null,
"e": 29461,
"s": 29412,
"text": "Element::before|after { \n content: inherit;\n}"
},
{
"code": null,
"e": 29545,
"s": 29461,
"text": "Supported Browsers: The browser supported by the content property are listed below:"
},
{
"code": null,
"e": 29563,
"s": 29545,
"text": "Google Chrome 1.0"
},
{
"code": null,
"e": 29585,
"s": 29563,
"text": "Internet Explorer 8.0"
},
{
"code": null,
"e": 29605,
"s": 29585,
"text": "Microsoft Edge 12.0"
},
{
"code": null,
"e": 29617,
"s": 29605,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 29627,
"s": 29617,
"text": "Opera 4.0"
},
{
"code": null,
"e": 29638,
"s": 29627,
"text": "Safari 1.0"
},
{
"code": null,
"e": 29652,
"s": 29638,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 29673,
"s": 29652,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 29688,
"s": 29673,
"text": "CSS-Properties"
},
{
"code": null,
"e": 29695,
"s": 29688,
"text": "Picked"
},
{
"code": null,
"e": 29699,
"s": 29695,
"text": "CSS"
},
{
"code": null,
"e": 29716,
"s": 29699,
"text": "Web Technologies"
},
{
"code": null,
"e": 29814,
"s": 29716,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29823,
"s": 29814,
"text": "Comments"
},
{
"code": null,
"e": 29836,
"s": 29823,
"text": "Old Comments"
},
{
"code": null,
"e": 29898,
"s": 29836,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29948,
"s": 29898,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 29996,
"s": 29948,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 30054,
"s": 29996,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 30104,
"s": 30054,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 30146,
"s": 30104,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 30179,
"s": 30146,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30222,
"s": 30179,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30284,
"s": 30222,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Python String ljust() Method
|
Python string method ljust() returns the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).
Following is the syntax for ljust() method −
str.ljust(width[, fillchar])
width − This is string length in total after padding.
width − This is string length in total after padding.
fillchar − This is filler character, default is a space.
fillchar − This is filler character, default is a space.
This method returns the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).
The following example shows the usage of ljust() method.
#!/usr/bin/python
str = "this is string example....wow!!!";
print str.ljust(50, '0')
When we run above program, it produces following result −
this is string example....wow!!!000000000000000000
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": 2466,
"s": 2244,
"text": "Python string method ljust() returns the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s)."
},
{
"code": null,
"e": 2511,
"s": 2466,
"text": "Following is the syntax for ljust() method −"
},
{
"code": null,
"e": 2541,
"s": 2511,
"text": "str.ljust(width[, fillchar])\n"
},
{
"code": null,
"e": 2595,
"s": 2541,
"text": "width − This is string length in total after padding."
},
{
"code": null,
"e": 2649,
"s": 2595,
"text": "width − This is string length in total after padding."
},
{
"code": null,
"e": 2706,
"s": 2649,
"text": "fillchar − This is filler character, default is a space."
},
{
"code": null,
"e": 2763,
"s": 2706,
"text": "fillchar − This is filler character, default is a space."
},
{
"code": null,
"e": 2967,
"s": 2763,
"text": "This method returns the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s)."
},
{
"code": null,
"e": 3024,
"s": 2967,
"text": "The following example shows the usage of ljust() method."
},
{
"code": null,
"e": 3110,
"s": 3024,
"text": "#!/usr/bin/python\n\nstr = \"this is string example....wow!!!\";\nprint str.ljust(50, '0')"
},
{
"code": null,
"e": 3168,
"s": 3110,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 3220,
"s": 3168,
"text": "this is string example....wow!!!000000000000000000\n"
},
{
"code": null,
"e": 3257,
"s": 3220,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3273,
"s": 3257,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3306,
"s": 3273,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3325,
"s": 3306,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3360,
"s": 3325,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3382,
"s": 3360,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3416,
"s": 3382,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3444,
"s": 3416,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3479,
"s": 3444,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3493,
"s": 3479,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3526,
"s": 3493,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3543,
"s": 3526,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3550,
"s": 3543,
"text": " Print"
},
{
"code": null,
"e": 3561,
"s": 3550,
"text": " Add Notes"
}
] |
JavaScript String - charAt() Method
|
charAt() is a method that returns the character from the specified index.
Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string, called stringName, is stringName.length – 1.
Use the following syntax to find the character at a particular index.
string.charAt(index);
index − An integer between 0 and 1 less than the length of the string.
Returns the character from the specified index.
Try the following example.
<html>
<head>
<title>JavaScript String charAt() Method</title>
</head>
<body>
<script type = "text/javascript">
var str = new String( "This is string" );
document.writeln("str.charAt(0) is:" + str.charAt(0));
document.writeln("<br />str.charAt(1) is:" + str.charAt(1));
document.writeln("<br />str.charAt(2) is:" + str.charAt(2));
document.writeln("<br />str.charAt(3) is:" + str.charAt(3));
document.writeln("<br />str.charAt(4) is:" + str.charAt(4));
document.writeln("<br />str.charAt(5) is:" + str.charAt(5));
</script>
</body>
</html>
str.charAt(0) is:T
str.charAt(1) is:h
str.charAt(2) is:i
str.charAt(3) is:s
str.charAt(4) is:
str.charAt(5) is:i
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2540,
"s": 2466,
"text": "charAt() is a method that returns the character from the specified index."
},
{
"code": null,
"e": 2728,
"s": 2540,
"text": "Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string, called stringName, is stringName.length – 1."
},
{
"code": null,
"e": 2798,
"s": 2728,
"text": "Use the following syntax to find the character at a particular index."
},
{
"code": null,
"e": 2821,
"s": 2798,
"text": "string.charAt(index);\n"
},
{
"code": null,
"e": 2892,
"s": 2821,
"text": "index − An integer between 0 and 1 less than the length of the string."
},
{
"code": null,
"e": 2940,
"s": 2892,
"text": "Returns the character from the specified index."
},
{
"code": null,
"e": 2967,
"s": 2940,
"text": "Try the following example."
},
{
"code": null,
"e": 3618,
"s": 2967,
"text": "<html>\n <head>\n <title>JavaScript String charAt() Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var str = new String( \"This is string\" );\n document.writeln(\"str.charAt(0) is:\" + str.charAt(0)); \n document.writeln(\"<br />str.charAt(1) is:\" + str.charAt(1)); \n document.writeln(\"<br />str.charAt(2) is:\" + str.charAt(2)); \n document.writeln(\"<br />str.charAt(3) is:\" + str.charAt(3)); \n document.writeln(\"<br />str.charAt(4) is:\" + str.charAt(4)); \n document.writeln(\"<br />str.charAt(5) is:\" + str.charAt(5)); \n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 3738,
"s": 3618,
"text": "str.charAt(0) is:T \nstr.charAt(1) is:h \nstr.charAt(2) is:i \nstr.charAt(3) is:s \nstr.charAt(4) is: \nstr.charAt(5) is:i \n"
},
{
"code": null,
"e": 3773,
"s": 3738,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3787,
"s": 3773,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3821,
"s": 3787,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3835,
"s": 3821,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3870,
"s": 3835,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3887,
"s": 3870,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3922,
"s": 3887,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3939,
"s": 3922,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3972,
"s": 3939,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4000,
"s": 3972,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4034,
"s": 4000,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 4062,
"s": 4034,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4069,
"s": 4062,
"text": " Print"
},
{
"code": null,
"e": 4080,
"s": 4069,
"text": " Add Notes"
}
] |
C++ goto statement
|
A goto statement provides an unconditional jump from the goto to a labeled statement in the same function.
NOTE − Use of goto statement is highly discouraged because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten so that it doesn't need the goto.
The syntax of a goto statement in C++ is −
goto label;
..
.
label: statement;
Where label is an identifier that identifies a labeled statement. A labeled statement is any statement that is preceded by an identifier followed by a colon (:).
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
// do loop execution
LOOP:do {
if( a == 15) {
// skip the iteration.
a = a + 1;
goto LOOP;
}
cout << "value of a: " << a << endl;
a = a + 1;
}
while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
One good use of goto is to exit from a deeply nested routine. For example, consider the following code fragment −
for(...) {
for(...) {
while(...) {
if(...) goto stop;
.
.
.
}
}
}
stop:
cout << "Error in program.\n";
Eliminating the goto would force a number of additional tests to be performed. A simple break statement would not work here, because it would only cause the program to exit from the innermost loop.
154 Lectures
11.5 hours
Arnab Chakraborty
14 Lectures
57 mins
Kaushik Roy Chowdhury
30 Lectures
12.5 hours
Frahaan Hussain
54 Lectures
3.5 hours
Frahaan Hussain
77 Lectures
5.5 hours
Frahaan Hussain
12 Lectures
3.5 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2425,
"s": 2318,
"text": "A goto statement provides an unconditional jump from the goto to a labeled statement in the same function."
},
{
"code": null,
"e": 2681,
"s": 2425,
"text": "NOTE − Use of goto statement is highly discouraged because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten so that it doesn't need the goto."
},
{
"code": null,
"e": 2724,
"s": 2681,
"text": "The syntax of a goto statement in C++ is −"
},
{
"code": null,
"e": 2760,
"s": 2724,
"text": "goto label;\n..\n.\nlabel: statement;\n"
},
{
"code": null,
"e": 2922,
"s": 2760,
"text": "Where label is an identifier that identifies a labeled statement. A labeled statement is any statement that is preceded by an identifier followed by a colon (:)."
},
{
"code": null,
"e": 3270,
"s": 2922,
"text": "#include <iostream>\nusing namespace std;\n \nint main () {\n // Local variable declaration:\n int a = 10;\n\n // do loop execution\n LOOP:do {\n if( a == 15) {\n // skip the iteration.\n a = a + 1;\n goto LOOP;\n }\n cout << \"value of a: \" << a << endl;\n a = a + 1;\n } \n while( a < 20 );\n \n return 0;\n}"
},
{
"code": null,
"e": 3351,
"s": 3270,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3487,
"s": 3351,
"text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 16\nvalue of a: 17\nvalue of a: 18\nvalue of a: 19\n"
},
{
"code": null,
"e": 3601,
"s": 3487,
"text": "One good use of goto is to exit from a deeply nested routine. For example, consider the following code fragment −"
},
{
"code": null,
"e": 3759,
"s": 3601,
"text": "for(...) {\n for(...) {\n while(...) {\n if(...) goto stop;\n .\n .\n .\n }\n }\n}\nstop:\ncout << \"Error in program.\\n\";\n"
},
{
"code": null,
"e": 3959,
"s": 3759,
"text": "Eliminating the goto would force a number of additional tests to be performed. A simple break statement would not work here, because it would only cause the program to exit from the innermost loop."
},
{
"code": null,
"e": 3996,
"s": 3959,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 4015,
"s": 3996,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4047,
"s": 4015,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 4070,
"s": 4047,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 4106,
"s": 4070,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 4123,
"s": 4106,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4158,
"s": 4123,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4175,
"s": 4158,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4210,
"s": 4175,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4227,
"s": 4210,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4262,
"s": 4227,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4279,
"s": 4262,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4286,
"s": 4279,
"text": " Print"
},
{
"code": null,
"e": 4297,
"s": 4286,
"text": " Add Notes"
}
] |
Insert into a Binary Search Tree in C++
|
Suppose we have a binary search tree. we have to write only one method, that performs the insertion operation with a node given as a parameter. We have to keep in mind that after the operation, the tree will remain BST also. So if the tree is like −
if we insert 5, then the tree will be −
To solve this, we will follow these steps −
This method is recursive. this is called insert(), this takes a value v.
if root is null, then create a node with given value v and make that as root
if value of root > v, thenleft of root := insert(left of the root, v)
left of root := insert(left of the root, v)
else right of the root := insert(right of the root, v)
return root
Let us see the following implementation to get a better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int data){
val = data;
left = right = NULL;
}
};
void insert(TreeNode **root, int val){
queue<TreeNode*> q;
q.push(*root);
while(q.size()){
TreeNode *temp = q.front();
q.pop();
if(!temp->left){
if(val != NULL)
temp->left = new TreeNode(val);
else
temp->left = new TreeNode(0);
return;
}
else{
q.push(temp->left);
}
if(!temp->right){
if(val != NULL)
temp->right = new TreeNode(val);
else
temp->right = new TreeNode(0);
return;
}
else{
q.push(temp->right);
}
}
}
TreeNode *make_tree(vector<int> v){
TreeNode *root = new TreeNode(v[0]);
for(int i = 1; i<v.size(); i++){
insert(&root, v[i]);
}
return root;
}
void tree_level_trav(TreeNode*root){
if (root == NULL) return;
cout << "[";
queue<TreeNode *> q;
TreeNode *curr;
q.push(root);
q.push(NULL);
while (q.size() > 1) {
curr = q.front();
q.pop();
if (curr == NULL){
q.push(NULL);
}
else {
if(curr->left)
q.push(curr->left);
if(curr->right)
q.push(curr->right);
if(curr->val == 0 || curr == NULL){
cout << "null" << ", ";
}
else{
cout << curr->val << ", ";
}
}
}
cout << "]"<<endl;
}
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(!root)return new TreeNode(val);
if(root->val > val){
root->left = insertIntoBST(root->left, val);
}
else root->right = insertIntoBST(root->right, val);
return root;
}
};
main(){
Solution ob;
vector<int> v = {4,2,7,1,3};
TreeNode *root = make_tree(v);
tree_level_trav(ob.insertIntoBST(root, 5));
}
[4,2,7,1,3]
5
[4,2,7,1,3,5]
|
[
{
"code": null,
"e": 1312,
"s": 1062,
"text": "Suppose we have a binary search tree. we have to write only one method, that performs the insertion operation with a node given as a parameter. We have to keep in mind that after the operation, the tree will remain BST also. So if the tree is like −"
},
{
"code": null,
"e": 1352,
"s": 1312,
"text": "if we insert 5, then the tree will be −"
},
{
"code": null,
"e": 1396,
"s": 1352,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1469,
"s": 1396,
"text": "This method is recursive. this is called insert(), this takes a value v."
},
{
"code": null,
"e": 1546,
"s": 1469,
"text": "if root is null, then create a node with given value v and make that as root"
},
{
"code": null,
"e": 1616,
"s": 1546,
"text": "if value of root > v, thenleft of root := insert(left of the root, v)"
},
{
"code": null,
"e": 1660,
"s": 1616,
"text": "left of root := insert(left of the root, v)"
},
{
"code": null,
"e": 1715,
"s": 1660,
"text": "else right of the root := insert(right of the root, v)"
},
{
"code": null,
"e": 1727,
"s": 1715,
"text": "return root"
},
{
"code": null,
"e": 1799,
"s": 1727,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 1810,
"s": 1799,
"text": " Live Demo"
},
{
"code": null,
"e": 3822,
"s": 1810,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass TreeNode{\n public:\n int val;\n TreeNode *left, *right;\n TreeNode(int data){\n val = data;\n left = right = NULL;\n }\n};\nvoid insert(TreeNode **root, int val){\n queue<TreeNode*> q;\n q.push(*root);\n while(q.size()){\n TreeNode *temp = q.front();\n q.pop();\n if(!temp->left){\n if(val != NULL)\n temp->left = new TreeNode(val);\n else\n temp->left = new TreeNode(0);\n return;\n }\n else{\n q.push(temp->left);\n }\n if(!temp->right){\n if(val != NULL)\n temp->right = new TreeNode(val);\n else\n temp->right = new TreeNode(0);\n return;\n }\n else{\n q.push(temp->right);\n }\n }\n}\nTreeNode *make_tree(vector<int> v){\n TreeNode *root = new TreeNode(v[0]);\n for(int i = 1; i<v.size(); i++){\n insert(&root, v[i]);\n }\n return root;\n}\nvoid tree_level_trav(TreeNode*root){\n if (root == NULL) return;\n cout << \"[\";\n queue<TreeNode *> q;\n TreeNode *curr;\n q.push(root);\n q.push(NULL);\n while (q.size() > 1) {\n curr = q.front();\n q.pop();\n if (curr == NULL){\n q.push(NULL);\n }\n else {\n if(curr->left)\n q.push(curr->left);\n if(curr->right)\n q.push(curr->right);\n if(curr->val == 0 || curr == NULL){\n cout << \"null\" << \", \";\n }\n else{\n cout << curr->val << \", \";\n }\n }\n }\n cout << \"]\"<<endl;\n}\nclass Solution {\npublic:\n TreeNode* insertIntoBST(TreeNode* root, int val) {\n if(!root)return new TreeNode(val);\n if(root->val > val){\n root->left = insertIntoBST(root->left, val);\n }\n else root->right = insertIntoBST(root->right, val);\n return root;\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {4,2,7,1,3};\n TreeNode *root = make_tree(v);\n tree_level_trav(ob.insertIntoBST(root, 5));\n}"
},
{
"code": null,
"e": 3836,
"s": 3822,
"text": "[4,2,7,1,3]\n5"
},
{
"code": null,
"e": 3850,
"s": 3836,
"text": "[4,2,7,1,3,5]"
}
] |
How to perform arithmetic operations on a date in Python?
|
It is very easy to do date and time maths in Python using timedelta objects. Whenever you want to add or subtract to a date/time, use a datetime.datetime(), then add or subtract datetime.timedelta() instances. A timedelta object represents a duration, the difference between two dates or times. The timedelta constructor has the following function signature −
datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
Note − All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative. You can read more about it here − https://docs.python.org/2/library/datetime.html#timedelta-objects
An example of using the timedelta objects and dates −
import datetime
old_time = datetime.datetime.now()
print(old_time)
new_time = old_time - datetime.timedelta(hours=2, minutes=10)
print(new_time)
This will give the output −
2018-01-04 11:09:00.694602
2018-01-04 08:59:00.694602
timedelta() arithmetic is not supported for datetime.time() objects; if you need to use offsets from an existing datetime.time() object, just use datetime.datetime.combine() to form a datetime.datetime() instance, do your calculations, and 'extract' the time again with the .time() method.
Subtracting 2 datetime objects gives a timedelta object. This timedelta object can be used to find the exact difference between the 2 datetimes.
t1 = datetime.datetime.now()
t2 = datetime.datetime.now()
print(t1 - t2)
print(type(t1 - t2))
This will give the output −
-1 day, 23:59:56.653627
<class 'datetime.timedelta'>
|
[
{
"code": null,
"e": 1422,
"s": 1062,
"text": "It is very easy to do date and time maths in Python using timedelta objects. Whenever you want to add or subtract to a date/time, use a datetime.datetime(), then add or subtract datetime.timedelta() instances. A timedelta object represents a duration, the difference between two dates or times. The timedelta constructor has the following function signature −"
},
{
"code": null,
"e": 1521,
"s": 1422,
"text": "datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])"
},
{
"code": null,
"e": 1747,
"s": 1521,
"text": "Note − All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative. You can read more about it here − https://docs.python.org/2/library/datetime.html#timedelta-objects"
},
{
"code": null,
"e": 1801,
"s": 1747,
"text": "An example of using the timedelta objects and dates −"
},
{
"code": null,
"e": 1946,
"s": 1801,
"text": "import datetime\nold_time = datetime.datetime.now()\nprint(old_time)\nnew_time = old_time - datetime.timedelta(hours=2, minutes=10)\nprint(new_time)"
},
{
"code": null,
"e": 1974,
"s": 1946,
"text": "This will give the output −"
},
{
"code": null,
"e": 2028,
"s": 1974,
"text": "2018-01-04 11:09:00.694602\n2018-01-04 08:59:00.694602"
},
{
"code": null,
"e": 2318,
"s": 2028,
"text": "timedelta() arithmetic is not supported for datetime.time() objects; if you need to use offsets from an existing datetime.time() object, just use datetime.datetime.combine() to form a datetime.datetime() instance, do your calculations, and 'extract' the time again with the .time() method."
},
{
"code": null,
"e": 2463,
"s": 2318,
"text": "Subtracting 2 datetime objects gives a timedelta object. This timedelta object can be used to find the exact difference between the 2 datetimes."
},
{
"code": null,
"e": 2557,
"s": 2463,
"text": "t1 = datetime.datetime.now()\nt2 = datetime.datetime.now()\nprint(t1 - t2)\nprint(type(t1 - t2))"
},
{
"code": null,
"e": 2585,
"s": 2557,
"text": "This will give the output −"
},
{
"code": null,
"e": 2638,
"s": 2585,
"text": "-1 day, 23:59:56.653627\n<class 'datetime.timedelta'>"
}
] |
CSS Layout - The display Property
|
The display property is the most important CSS property for controlling layout.
The display property specifies if/how an element is displayed.
Every HTML element has a default display value depending on what type
of element it is. The default display value for most elements is block or
inline.
Click to show panel
This panel contains a <div> element, which is hidden by default (display: none).
It is styled with CSS, and we use JavaScript to show it (change it to (display: block).
A block-level element always starts on a new line and takes up the full width available
(stretches out to the left and right as far as it can).
Examples of block-level elements:
<div>
<h1> - <h6>
<p>
<form>
<header>
<footer>
<section>
An inline element does not start on a new line and only takes up as much width as necessary.
This is an inline <span> element
inside a paragraph.
Examples of inline elements:
<span>
<a>
<img>
display: none; is commonly used with JavaScript to hide
and show elements without deleting and recreating them. Take a look at our last
example on this page if you want to know how this can be achieved.
The <script> element uses display: none;
as default.
As mentioned, every element has a default display value. However, you can
override this.
Changing an inline element to a block element, or vice versa, can be useful for
making the page look a specific way, and still follow the web standards.
A common example is making inline <li> elements for horizontal menus:
Note: Setting the display property of an element only changes how the element is displayed,
NOT what kind of element it is. So, an inline element with display: block; is not allowed
to have other block elements inside it.
The following example displays <span> elements as block elements:
The following example displays <a> elements as block elements:
display:none
Remove
visibility:hidden
Hide
Reset
Reset All
Hiding an element can be done by setting the display property to
none.
The element will be hidden, and the page will be displayed as if the element is not
there:
visibility:hidden; also hides an element.
However, the element will still take up the same space
as before. The element will be hidden, but still affect the layout:
Differences between display: none; and visibility: hidden;
This example demonstrates display: none; versus visibility: hidden;
Using CSS together with JavaScript to show content
This example demonstrates how to use CSS and JavaScript to show an element on
click.
Hide the <h1> element. It should still take up the same space as before.
<style>
h1 {
: ;
}
</style>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph</p>
<p>This is a paragraph</p>
</body>
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": 80,
"s": 0,
"text": "The display property is the most important CSS property for controlling layout."
},
{
"code": null,
"e": 143,
"s": 80,
"text": "The display property specifies if/how an element is displayed."
},
{
"code": null,
"e": 297,
"s": 143,
"text": "Every HTML element has a default display value depending on what type \nof element it is. The default display value for most elements is block or \ninline."
},
{
"code": null,
"e": 317,
"s": 297,
"text": "Click to show panel"
},
{
"code": null,
"e": 398,
"s": 317,
"text": "This panel contains a <div> element, which is hidden by default (display: none)."
},
{
"code": null,
"e": 486,
"s": 398,
"text": "It is styled with CSS, and we use JavaScript to show it (change it to (display: block)."
},
{
"code": null,
"e": 631,
"s": 486,
"text": "A block-level element always starts on a new line and takes up the full width available \n(stretches out to the left and right as far as it can)."
},
{
"code": null,
"e": 665,
"s": 631,
"text": "Examples of block-level elements:"
},
{
"code": null,
"e": 671,
"s": 665,
"text": "<div>"
},
{
"code": null,
"e": 683,
"s": 671,
"text": "<h1> - <h6>"
},
{
"code": null,
"e": 687,
"s": 683,
"text": "<p>"
},
{
"code": null,
"e": 694,
"s": 687,
"text": "<form>"
},
{
"code": null,
"e": 703,
"s": 694,
"text": "<header>"
},
{
"code": null,
"e": 712,
"s": 703,
"text": "<footer>"
},
{
"code": null,
"e": 722,
"s": 712,
"text": "<section>"
},
{
"code": null,
"e": 815,
"s": 722,
"text": "An inline element does not start on a new line and only takes up as much width as necessary."
},
{
"code": null,
"e": 869,
"s": 815,
"text": "This is an inline <span> element \ninside a paragraph."
},
{
"code": null,
"e": 898,
"s": 869,
"text": "Examples of inline elements:"
},
{
"code": null,
"e": 905,
"s": 898,
"text": "<span>"
},
{
"code": null,
"e": 909,
"s": 905,
"text": "<a>"
},
{
"code": null,
"e": 915,
"s": 909,
"text": "<img>"
},
{
"code": null,
"e": 1120,
"s": 915,
"text": "display: none; is commonly used with JavaScript to hide \nand show elements without deleting and recreating them. Take a look at our last \nexample on this page if you want to know how this can be achieved."
},
{
"code": null,
"e": 1175,
"s": 1120,
"text": "The <script> element uses display: none; \nas default. "
},
{
"code": null,
"e": 1265,
"s": 1175,
"text": "As mentioned, every element has a default display value. However, you can \noverride this."
},
{
"code": null,
"e": 1419,
"s": 1265,
"text": "Changing an inline element to a block element, or vice versa, can be useful for \nmaking the page look a specific way, and still follow the web standards."
},
{
"code": null,
"e": 1489,
"s": 1419,
"text": "A common example is making inline <li> elements for horizontal menus:"
},
{
"code": null,
"e": 1712,
"s": 1489,
"text": "Note: Setting the display property of an element only changes how the element is displayed, \nNOT what kind of element it is. So, an inline element with display: block; is not allowed\nto have other block elements inside it."
},
{
"code": null,
"e": 1778,
"s": 1712,
"text": "The following example displays <span> elements as block elements:"
},
{
"code": null,
"e": 1841,
"s": 1778,
"text": "The following example displays <a> elements as block elements:"
},
{
"code": null,
"e": 1854,
"s": 1841,
"text": "display:none"
},
{
"code": null,
"e": 1861,
"s": 1854,
"text": "Remove"
},
{
"code": null,
"e": 1879,
"s": 1861,
"text": "visibility:hidden"
},
{
"code": null,
"e": 1884,
"s": 1879,
"text": "Hide"
},
{
"code": null,
"e": 1890,
"s": 1884,
"text": "Reset"
},
{
"code": null,
"e": 1900,
"s": 1890,
"text": "Reset All"
},
{
"code": null,
"e": 2065,
"s": 1900,
"text": "Hiding an element can be done by setting the display property to \nnone. \nThe element will be hidden, and the page will be displayed as if the element is not \nthere:"
},
{
"code": null,
"e": 2107,
"s": 2065,
"text": "visibility:hidden; also hides an element."
},
{
"code": null,
"e": 2231,
"s": 2107,
"text": "However, the element will still take up the same space \nas before. The element will be hidden, but still affect the layout:"
},
{
"code": null,
"e": 2358,
"s": 2231,
"text": "Differences between display: none; and visibility: hidden;\nThis example demonstrates display: none; versus visibility: hidden;"
},
{
"code": null,
"e": 2495,
"s": 2358,
"text": "Using CSS together with JavaScript to show content\nThis example demonstrates how to use CSS and JavaScript to show an element on \nclick."
},
{
"code": null,
"e": 2568,
"s": 2495,
"text": "Hide the <h1> element. It should still take up the same space as before."
},
{
"code": null,
"e": 2702,
"s": 2568,
"text": "<style>\nh1 {\n : ;\n}\n</style>\n\n<body>\n <h1>This is a heading</h1>\n <p>This is a paragraph</p>\n <p>This is a paragraph</p>\n</body>\n"
},
{
"code": null,
"e": 2721,
"s": 2702,
"text": "Start the Exercise"
},
{
"code": null,
"e": 2754,
"s": 2721,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2796,
"s": 2754,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2903,
"s": 2796,
"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": 2922,
"s": 2903,
"text": "[email protected]"
}
] |
AnalyzeTheChat — Python-based WhatsApp chat analyzer | by Aqeel Anwar | Towards Data Science
|
Analyze your WhatsApp chat in the form of interesting graphs
A couple of weeks ago my wife and I started looking at our Whatsapp chat over the last year. There were too many messages and we simply couldn’t go over all of them. I have been using Python for over 3 years now and thought of creating a very simple analyzer to provide me with some useful insights into our WhatsApp chat. The resulting graphs were pretty interesting.
In this article, I will go through the GitHub repository I created for analyzing WhatsApp chat.
To check out the online easy-to-use demo without going through the hassle of installing the repository and Python packages, please click below and follow the instructions.
AnalyzeTheChat is a Python-based repository to generate useful statistics for your WhatsApp chat. It crawls the provided .txt file of the WhatsApp chat and generates a pandas dataframe. This dataframe is then processed to plot the following contact-wise and time-wise statistics
Number of messages per contact
Number of words per contact
Number of average words per message per contact
Number of emojis per contact
The average number of emojis per message per contact
Number of Media per contact
Number of keywords per contact
Number of messages per hour
Number of messages per weekday
Number of messages per month
Number of messages per year
An example of generates statistics can be seen below
It is advisable to make a new virtual environment (with python 3.6) for this project. Step-by-Step details on creating a virtual environment can be found here
Once you have created the virtual environment, activate it, and use the following command to clone the repository.
git clone https://github.com/aqeelanwar/AnalyzeTheChat.git
cd AnalyzeTheChatpip install -r requirements.txt
Export the WhatsApp chat you like to analyze using the following steps
Open the WhatsApp chatClick the three vertical dots on top-rightClick MoreClick Export ChatClick Without MediaSave the generated .txt file where it is accessible
Open the WhatsApp chat
Click the three vertical dots on top-right
Click More
Click Export Chat
Click Without Media
Save the generated .txt file where it is accessible
# Genericpython main.py --path <path-to-chat> --save_as <save-type># Examplepython main.py --path theoffice.txt --keyword 'jello' --save_as pdf
The results are saved in the results folder in the format selected by the user through the argument save_as.
AnalyzeTheChat is a python-baed WhatsApp chat analyzer that generates interesting bar graphs. It can be used to analyze the activity of a person or a group chat to deduce useful results. The online demo can be found here
|
[
{
"code": null,
"e": 233,
"s": 172,
"text": "Analyze your WhatsApp chat in the form of interesting graphs"
},
{
"code": null,
"e": 602,
"s": 233,
"text": "A couple of weeks ago my wife and I started looking at our Whatsapp chat over the last year. There were too many messages and we simply couldn’t go over all of them. I have been using Python for over 3 years now and thought of creating a very simple analyzer to provide me with some useful insights into our WhatsApp chat. The resulting graphs were pretty interesting."
},
{
"code": null,
"e": 698,
"s": 602,
"text": "In this article, I will go through the GitHub repository I created for analyzing WhatsApp chat."
},
{
"code": null,
"e": 870,
"s": 698,
"text": "To check out the online easy-to-use demo without going through the hassle of installing the repository and Python packages, please click below and follow the instructions."
},
{
"code": null,
"e": 1149,
"s": 870,
"text": "AnalyzeTheChat is a Python-based repository to generate useful statistics for your WhatsApp chat. It crawls the provided .txt file of the WhatsApp chat and generates a pandas dataframe. This dataframe is then processed to plot the following contact-wise and time-wise statistics"
},
{
"code": null,
"e": 1180,
"s": 1149,
"text": "Number of messages per contact"
},
{
"code": null,
"e": 1208,
"s": 1180,
"text": "Number of words per contact"
},
{
"code": null,
"e": 1256,
"s": 1208,
"text": "Number of average words per message per contact"
},
{
"code": null,
"e": 1285,
"s": 1256,
"text": "Number of emojis per contact"
},
{
"code": null,
"e": 1338,
"s": 1285,
"text": "The average number of emojis per message per contact"
},
{
"code": null,
"e": 1366,
"s": 1338,
"text": "Number of Media per contact"
},
{
"code": null,
"e": 1397,
"s": 1366,
"text": "Number of keywords per contact"
},
{
"code": null,
"e": 1425,
"s": 1397,
"text": "Number of messages per hour"
},
{
"code": null,
"e": 1456,
"s": 1425,
"text": "Number of messages per weekday"
},
{
"code": null,
"e": 1485,
"s": 1456,
"text": "Number of messages per month"
},
{
"code": null,
"e": 1513,
"s": 1485,
"text": "Number of messages per year"
},
{
"code": null,
"e": 1566,
"s": 1513,
"text": "An example of generates statistics can be seen below"
},
{
"code": null,
"e": 1725,
"s": 1566,
"text": "It is advisable to make a new virtual environment (with python 3.6) for this project. Step-by-Step details on creating a virtual environment can be found here"
},
{
"code": null,
"e": 1840,
"s": 1725,
"text": "Once you have created the virtual environment, activate it, and use the following command to clone the repository."
},
{
"code": null,
"e": 1899,
"s": 1840,
"text": "git clone https://github.com/aqeelanwar/AnalyzeTheChat.git"
},
{
"code": null,
"e": 1948,
"s": 1899,
"text": "cd AnalyzeTheChatpip install -r requirements.txt"
},
{
"code": null,
"e": 2019,
"s": 1948,
"text": "Export the WhatsApp chat you like to analyze using the following steps"
},
{
"code": null,
"e": 2181,
"s": 2019,
"text": "Open the WhatsApp chatClick the three vertical dots on top-rightClick MoreClick Export ChatClick Without MediaSave the generated .txt file where it is accessible"
},
{
"code": null,
"e": 2204,
"s": 2181,
"text": "Open the WhatsApp chat"
},
{
"code": null,
"e": 2247,
"s": 2204,
"text": "Click the three vertical dots on top-right"
},
{
"code": null,
"e": 2258,
"s": 2247,
"text": "Click More"
},
{
"code": null,
"e": 2276,
"s": 2258,
"text": "Click Export Chat"
},
{
"code": null,
"e": 2296,
"s": 2276,
"text": "Click Without Media"
},
{
"code": null,
"e": 2348,
"s": 2296,
"text": "Save the generated .txt file where it is accessible"
},
{
"code": null,
"e": 2492,
"s": 2348,
"text": "# Genericpython main.py --path <path-to-chat> --save_as <save-type># Examplepython main.py --path theoffice.txt --keyword 'jello' --save_as pdf"
},
{
"code": null,
"e": 2601,
"s": 2492,
"text": "The results are saved in the results folder in the format selected by the user through the argument save_as."
}
] |
How to implement immutable Data structures in Python?
|
You need to implement immutable data structures in Python.
Immutable data structures are very handy when you want to prevent multiple people modifying a piece of data in parallel programming at same time. Mutable data structures( e.g. Array) can be changed at any time while immutable data structures cannot be.
Let me show you step by step how to deal with immutable and mutable data structures.
# STEP 01 - Create a Mutable array.
# Define an array
atp_players = ['Murray', 'Nadal', 'Djokovic']
print(f" *** Original Data in my array is - {atp_players}")
*** Original Data in my array is -
['Murray', 'Nadal', 'Djokovic']
# Changing the player name from Murray to Federer
atp_players[0] = 'Federer'
print(f" *** Modified Data in my array is - {atp_players}")
*** Modified Data in my array is -
['Federer', 'Nadal', 'Djokovic']
Conclusion
We have been able to change the array value just like that which might be useful if you are an exclusive user of this array. However, in realtime production multiple programs might be using this array for changes and might result in unexpected data.
Tuples on other hand behaves a bit differently, have a look at below example.
# STEP 02 - Try changing a Tuple
try:
atp_players_tuple = ('Murray', 'Nadal', 'Djokovic')
print(f" *** Original Data in my tuple is - {atp_players_tuple}")
atp_players_tuple[0] = 'Federer'
except Exception as error:
print(f" *** Tried modifying data but ended up with - {error}")
*** Original Data in my tuple is - ('Murray', 'Nadal', 'Djokovic')
*** Tried modifying data but ended up with - 'tuple' object does not support item assignment
Conclusion :
What you have seen above is, tuple cannot be modified right ?. However there is one exception, if there are arrays with in a tuple the values can be changed.
atp_players_array_in_tuple = (['Murray'], ['Nadal'], ['Djokovic'])
print(f" *** Original Data in my tuple with arrays is - {atp_players_array_in_tuple}")
atp_players_array_in_tuple[0][0] = 'Federer'
print(f" *** Modified Data in my tuple with arrays is - {atp_players_array_in_tuple}")
*** Original Data in my tuple with arrays is - (['Murray'], ['Nadal'], ['Djokovic'])
*** Modified Data in my tuple with arrays is - (['Federer'], ['Nadal'], ['Djokovic'])
So how to protect the data ? Hmm, just by converting the arrays to tuples.
try:
atp_players_tuple_in_tuple = (('Murray'), ('Nadal'), ('Djokovic'))
print(f" *** Original Data in my tuple is - {atp_players_tuple_in_tuple}")
atp_players_tuple_in_tuple[0] = 'Federer'
except Exception as error:
print(f" *** Tried modifying data in my tuple but ended up with - {error}")
*** Original Data in my tuple is - ('Murray', 'Nadal', 'Djokovic')
*** Tried modifying data in my tuple but ended up with - 'tuple' object does not support item assignment
There is more.. Python has a wonderful built in tool called NamedTuple. It's a class you can extend to create a constructor. Let us understand programatically.
# Create a simple class on Grandslam titles in pythons way.
class GrandSlamsPythonWay:
def __init__(self, player, titles):
self.player = player
self.titles = titles
stats = GrandSlamsPythonWay("Federer", 20)
print(f" *** Stats has details as {stats.player} - {stats.titles}")
*** Stats has details as Federer - 20
What do you think of this class, is it immutable ? Let us check it out by changing Federer to Nadal.
stats.player = 'Nadal'
print(f" *** Stats has details as {stats.player} - {stats.titles}")
*** Stats has details as Nadal - 20
So no surprise it is a immutable data structure as we are able to Update Federer to Nadal. Now let us create a class with NamedTuple and see what is it's default behaviour.
from typing import NamedTuple
class GrandSlamsWithNamedTuple(NamedTuple):
player: str
titles: int
stats = GrandSlamsWithNamedTuple("Federer", 20)
print(f" *** Stats has details as {stats.player} - {stats.titles}")
stats.player = 'Djokovic'
print(f" *** Stats has details as {stats.player} - {stats.titles}")
*** Stats has details as Federer - 20
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
in
10 print(f" *** Stats has details as {stats.player} - {stats.titles}")
11
---> 12 stats.player = 'Djokovic'
13 print(f" *** Stats has details as {stats.player} - {stats.titles}")
AttributeError: can't set attribute
Looks like Djokovic had to wait some more time to reach 20 Grandslam titles.
However we can make use of _replace method to make a copy and update the values during the _replace.
djokovic_stats = stats._replace(player="Djokovic", titles=17)
print(f" *** djokovic_stats has details as {djokovic_stats.player} - {djokovic_stats.titles}")
*** djokovic_stats has details as Djokovic - 17
Finally i will put one example which covers everything explained above.
For this example, pretend we're writing software for vegetable shop.
from typing import Tuple
# Create a Class to represent one purchase
class Prices(NamedTuple):
id: int
name: str
price: int # Price in dollars
# Create a Class to track the purchase
class Purchase(NamedTuple):
purchase_id: int
items: Tuple[Prices]
# Create vegetable items and their corresponding prices
carrot = Prices(1, "carrot", 2)
tomato = Prices(2, "tomato", 3)
eggplant = Prices(3, "eggplant", 5)
# Now let say our first cusotmer Mr.Tom had purchased carrot and tomato
tom_order = Purchase(1, (carrot, tomato))
# Know the total cost we need to charge Mr.Tom
total_cost = sum(item.price for item in tom_order.items)
print(f"*** Total Cost from Mr.Tom is - {total_cost}$")
*** Total Cost from Mr.Tom is - 5$
|
[
{
"code": null,
"e": 1121,
"s": 1062,
"text": "You need to implement immutable data structures in Python."
},
{
"code": null,
"e": 1374,
"s": 1121,
"text": "Immutable data structures are very handy when you want to prevent multiple people modifying a piece of data in parallel programming at same time. Mutable data structures( e.g. Array) can be changed at any time while immutable data structures cannot be."
},
{
"code": null,
"e": 1459,
"s": 1374,
"text": "Let me show you step by step how to deal with immutable and mutable data structures."
},
{
"code": null,
"e": 1620,
"s": 1459,
"text": "# STEP 01 - Create a Mutable array.\n\n# Define an array\natp_players = ['Murray', 'Nadal', 'Djokovic']\nprint(f\" *** Original Data in my array is - {atp_players}\")"
},
{
"code": null,
"e": 1655,
"s": 1620,
"text": "*** Original Data in my array is -"
},
{
"code": null,
"e": 1687,
"s": 1655,
"text": "['Murray', 'Nadal', 'Djokovic']"
},
{
"code": null,
"e": 1824,
"s": 1687,
"text": "# Changing the player name from Murray to Federer\natp_players[0] = 'Federer'\nprint(f\" *** Modified Data in my array is - {atp_players}\")"
},
{
"code": null,
"e": 1859,
"s": 1824,
"text": "*** Modified Data in my array is -"
},
{
"code": null,
"e": 1892,
"s": 1859,
"text": "['Federer', 'Nadal', 'Djokovic']"
},
{
"code": null,
"e": 1904,
"s": 1892,
"text": "Conclusion "
},
{
"code": null,
"e": 2154,
"s": 1904,
"text": "We have been able to change the array value just like that which might be useful if you are an exclusive user of this array. However, in realtime production multiple programs might be using this array for changes and might result in unexpected data."
},
{
"code": null,
"e": 2232,
"s": 2154,
"text": "Tuples on other hand behaves a bit differently, have a look at below example."
},
{
"code": null,
"e": 2513,
"s": 2232,
"text": "# STEP 02 - Try changing a Tuple\n\ntry:\natp_players_tuple = ('Murray', 'Nadal', 'Djokovic')\nprint(f\" *** Original Data in my tuple is - {atp_players_tuple}\")\natp_players_tuple[0] = 'Federer'\nexcept Exception as error:\nprint(f\" *** Tried modifying data but ended up with - {error}\")"
},
{
"code": null,
"e": 2673,
"s": 2513,
"text": "*** Original Data in my tuple is - ('Murray', 'Nadal', 'Djokovic')\n*** Tried modifying data but ended up with - 'tuple' object does not support item assignment"
},
{
"code": null,
"e": 2686,
"s": 2673,
"text": "Conclusion :"
},
{
"code": null,
"e": 2844,
"s": 2686,
"text": "What you have seen above is, tuple cannot be modified right ?. However there is one exception, if there are arrays with in a tuple the values can be changed."
},
{
"code": null,
"e": 3131,
"s": 2844,
"text": "atp_players_array_in_tuple = (['Murray'], ['Nadal'], ['Djokovic'])\nprint(f\" *** Original Data in my tuple with arrays is - {atp_players_array_in_tuple}\")\n\natp_players_array_in_tuple[0][0] = 'Federer'\nprint(f\" *** Modified Data in my tuple with arrays is - {atp_players_array_in_tuple}\")"
},
{
"code": null,
"e": 3302,
"s": 3131,
"text": "*** Original Data in my tuple with arrays is - (['Murray'], ['Nadal'], ['Djokovic'])\n*** Modified Data in my tuple with arrays is - (['Federer'], ['Nadal'], ['Djokovic'])"
},
{
"code": null,
"e": 3377,
"s": 3302,
"text": "So how to protect the data ? Hmm, just by converting the arrays to tuples."
},
{
"code": null,
"e": 3669,
"s": 3377,
"text": "try:\natp_players_tuple_in_tuple = (('Murray'), ('Nadal'), ('Djokovic'))\nprint(f\" *** Original Data in my tuple is - {atp_players_tuple_in_tuple}\")\natp_players_tuple_in_tuple[0] = 'Federer'\nexcept Exception as error:\nprint(f\" *** Tried modifying data in my tuple but ended up with - {error}\")"
},
{
"code": null,
"e": 3841,
"s": 3669,
"text": "*** Original Data in my tuple is - ('Murray', 'Nadal', 'Djokovic')\n*** Tried modifying data in my tuple but ended up with - 'tuple' object does not support item assignment"
},
{
"code": null,
"e": 4001,
"s": 3841,
"text": "There is more.. Python has a wonderful built in tool called NamedTuple. It's a class you can extend to create a constructor. Let us understand programatically."
},
{
"code": null,
"e": 4278,
"s": 4001,
"text": "# Create a simple class on Grandslam titles in pythons way.\nclass GrandSlamsPythonWay:\ndef __init__(self, player, titles):\nself.player = player\nself.titles = titles\n\nstats = GrandSlamsPythonWay(\"Federer\", 20)\nprint(f\" *** Stats has details as {stats.player} - {stats.titles}\")"
},
{
"code": null,
"e": 4316,
"s": 4278,
"text": "*** Stats has details as Federer - 20"
},
{
"code": null,
"e": 4417,
"s": 4316,
"text": "What do you think of this class, is it immutable ? Let us check it out by changing Federer to Nadal."
},
{
"code": null,
"e": 4508,
"s": 4417,
"text": "stats.player = 'Nadal'\nprint(f\" *** Stats has details as {stats.player} - {stats.titles}\")"
},
{
"code": null,
"e": 4544,
"s": 4508,
"text": "*** Stats has details as Nadal - 20"
},
{
"code": null,
"e": 4717,
"s": 4544,
"text": "So no surprise it is a immutable data structure as we are able to Update Federer to Nadal. Now let us create a class with NamedTuple and see what is it's default behaviour."
},
{
"code": null,
"e": 5028,
"s": 4717,
"text": "from typing import NamedTuple\n\nclass GrandSlamsWithNamedTuple(NamedTuple):\nplayer: str\ntitles: int\n\nstats = GrandSlamsWithNamedTuple(\"Federer\", 20)\nprint(f\" *** Stats has details as {stats.player} - {stats.titles}\")\n\nstats.player = 'Djokovic'\nprint(f\" *** Stats has details as {stats.player} - {stats.titles}\")"
},
{
"code": null,
"e": 5066,
"s": 5028,
"text": "*** Stats has details as Federer - 20"
},
{
"code": null,
"e": 5410,
"s": 5066,
"text": "---------------------------------------------------------------------------\nAttributeError Traceback (most recent call last)\nin\n10 print(f\" *** Stats has details as {stats.player} - {stats.titles}\")\n11\n---> 12 stats.player = 'Djokovic'\n13 print(f\" *** Stats has details as {stats.player} - {stats.titles}\")\n\nAttributeError: can't set attribute"
},
{
"code": null,
"e": 5487,
"s": 5410,
"text": "Looks like Djokovic had to wait some more time to reach 20 Grandslam titles."
},
{
"code": null,
"e": 5588,
"s": 5487,
"text": "However we can make use of _replace method to make a copy and update the values during the _replace."
},
{
"code": null,
"e": 5745,
"s": 5588,
"text": "djokovic_stats = stats._replace(player=\"Djokovic\", titles=17)\nprint(f\" *** djokovic_stats has details as {djokovic_stats.player} - {djokovic_stats.titles}\")"
},
{
"code": null,
"e": 5793,
"s": 5745,
"text": "*** djokovic_stats has details as Djokovic - 17"
},
{
"code": null,
"e": 5865,
"s": 5793,
"text": "Finally i will put one example which covers everything explained above."
},
{
"code": null,
"e": 5934,
"s": 5865,
"text": "For this example, pretend we're writing software for vegetable shop."
},
{
"code": null,
"e": 6616,
"s": 5934,
"text": "from typing import Tuple\n\n# Create a Class to represent one purchase\nclass Prices(NamedTuple):\nid: int\nname: str\nprice: int # Price in dollars\n\n# Create a Class to track the purchase\nclass Purchase(NamedTuple):\npurchase_id: int\nitems: Tuple[Prices]\n\n# Create vegetable items and their corresponding prices\ncarrot = Prices(1, \"carrot\", 2)\ntomato = Prices(2, \"tomato\", 3)\neggplant = Prices(3, \"eggplant\", 5)\n\n# Now let say our first cusotmer Mr.Tom had purchased carrot and tomato\ntom_order = Purchase(1, (carrot, tomato))\n\n# Know the total cost we need to charge Mr.Tom\ntotal_cost = sum(item.price for item in tom_order.items)\nprint(f\"*** Total Cost from Mr.Tom is - {total_cost}$\")"
},
{
"code": null,
"e": 6651,
"s": 6616,
"text": "*** Total Cost from Mr.Tom is - 5$"
}
] |
IDE | GeeksforGeeks | A computer science portal for geeks
|
Please enter your email address or userHandle.
|
[] |
Angular 2 - CRUD Operations Using HTTP
|
The basic CRUD operation we will look into this chapter is the reading of data from a web service using Angular 2.
In this example, we are going to define a data source which is a simple json file of products. Next, we are going to define a service which will be used to read the data from the json file. And then next, we will use this service in our main app.component.ts file.
Step 1 − First let’s define our product.json file in Visual Studio code.
In the products.json file, enter the following text. This will be the data which will be taken from the Angular JS application.
[{
"ProductID": 1,
"ProductName": "ProductA"
},
{
"ProductID": 2,
"ProductName": "ProductB"
}]
Step 2 − Define an interface which will be the class definition to store the information from our products.json file. Create a file called products.ts.
Step 3 − Insert the following code in the file.
export interface IProduct {
ProductID: number;
ProductName: string;
}
The above interface has the definition for the ProductID and ProductName as properties for the interface.
Step 4 − In the app.module.ts file include the following code −
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HttpModule } from '@angular/http';
@NgModule ({
imports: [ BrowserModule,HttpModule],
declarations: [ AppComponent],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Step 5 − Define a products.service.ts file in Visual Studio code
Step 6 − Insert the following code in the file.
import { Injectable } from '@angular/core';
import { Http , Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import { IProduct } from './product';
@Injectable()
export class ProductService {
private _producturl='app/products.json';
constructor(private _http: Http){}
getproducts(): Observable<IProduct[]> {
return this._http.get(this._producturl)
.map((response: Response) => <IProduct[]> response.json())
.do(data => console.log(JSON.stringify(data)));
}
}
Following points need to be noted about the above program.
The import {Http, Response} from '@angular/http' statement is used to ensure that the http function can be used to get the data from the products.json file.
The import {Http, Response} from '@angular/http' statement is used to ensure that the http function can be used to get the data from the products.json file.
The following statements are used to make use of the Reactive framework which can be used to create an Observable variable. The Observable framework is used to detect any changes in the http response which can then be sent back to the main application.
The following statements are used to make use of the Reactive framework which can be used to create an Observable variable. The Observable framework is used to detect any changes in the http response which can then be sent back to the main application.
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
The statement private _producturl = 'app/products.json' in the class is used to specify the location of our data source. It can also specify the location of web service if required.
The statement private _producturl = 'app/products.json' in the class is used to specify the location of our data source. It can also specify the location of web service if required.
Next, we define a variable of the type Http which will be used to get the response from the data source.
Next, we define a variable of the type Http which will be used to get the response from the data source.
Once we get the data from the data source, we then use the JSON.stringify(data) command to send the data to the console in the browser.
Once we get the data from the data source, we then use the JSON.stringify(data) command to send the data to the console in the browser.
Step 7 − Now in the app.component.ts file, place the following code.
import { Component } from '@angular/core';
import { IProduct } from './product';
import { ProductService } from './products.service';
import { appService } from './app.service';
import { Http , Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Component ({
selector: 'my-app',
template: '<div>Hello</div>',
providers: [ProductService]
})
export class AppComponent {
iproducts: IProduct[];
constructor(private _product: ProductService) {
}
ngOnInit() : void {
this._product.getproducts()
.subscribe(iproducts => this.iproducts = iproducts);
}
}
Here, the main thing in the code is the subscribe option which is used to listen to the Observable getproducts() function to listen for data from the data source.
Now save all the codes and run the application using npm. Go to the browser, we will see the following output.
In the Console, we will see the data being retrieved from products.json file.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2412,
"s": 2297,
"text": "The basic CRUD operation we will look into this chapter is the reading of data from a web service using Angular 2."
},
{
"code": null,
"e": 2677,
"s": 2412,
"text": "In this example, we are going to define a data source which is a simple json file of products. Next, we are going to define a service which will be used to read the data from the json file. And then next, we will use this service in our main app.component.ts file."
},
{
"code": null,
"e": 2750,
"s": 2677,
"text": "Step 1 − First let’s define our product.json file in Visual Studio code."
},
{
"code": null,
"e": 2878,
"s": 2750,
"text": "In the products.json file, enter the following text. This will be the data which will be taken from the Angular JS application."
},
{
"code": null,
"e": 2986,
"s": 2878,
"text": "[{\n \"ProductID\": 1,\n \"ProductName\": \"ProductA\"\n},\n\n{\n \"ProductID\": 2,\n \"ProductName\": \"ProductB\"\n}]"
},
{
"code": null,
"e": 3138,
"s": 2986,
"text": "Step 2 − Define an interface which will be the class definition to store the information from our products.json file. Create a file called products.ts."
},
{
"code": null,
"e": 3186,
"s": 3138,
"text": "Step 3 − Insert the following code in the file."
},
{
"code": null,
"e": 3262,
"s": 3186,
"text": "export interface IProduct {\n ProductID: number;\n ProductName: string;\n}"
},
{
"code": null,
"e": 3368,
"s": 3262,
"text": "The above interface has the definition for the ProductID and ProductName as properties for the interface."
},
{
"code": null,
"e": 3432,
"s": 3368,
"text": "Step 4 − In the app.module.ts file include the following code −"
},
{
"code": null,
"e": 3789,
"s": 3432,
"text": "import { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { AppComponent } from './app.component';\nimport { HttpModule } from '@angular/http';\n\n@NgModule ({\n imports: [ BrowserModule,HttpModule],\n declarations: [ AppComponent],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 3854,
"s": 3789,
"text": "Step 5 − Define a products.service.ts file in Visual Studio code"
},
{
"code": null,
"e": 3902,
"s": 3854,
"text": "Step 6 − Insert the following code in the file."
},
{
"code": null,
"e": 4488,
"s": 3902,
"text": "import { Injectable } from '@angular/core';\nimport { Http , Response } from '@angular/http';\nimport { Observable } from 'rxjs/Observable';\nimport 'rxjs/add/operator/map';\nimport 'rxjs/add/operator/do';\nimport { IProduct } from './product';\n\n@Injectable()\nexport class ProductService {\n private _producturl='app/products.json';\n constructor(private _http: Http){}\n \n getproducts(): Observable<IProduct[]> {\n return this._http.get(this._producturl)\n .map((response: Response) => <IProduct[]> response.json())\n .do(data => console.log(JSON.stringify(data)));\n }\n}"
},
{
"code": null,
"e": 4547,
"s": 4488,
"text": "Following points need to be noted about the above program."
},
{
"code": null,
"e": 4704,
"s": 4547,
"text": "The import {Http, Response} from '@angular/http' statement is used to ensure that the http function can be used to get the data from the products.json file."
},
{
"code": null,
"e": 4861,
"s": 4704,
"text": "The import {Http, Response} from '@angular/http' statement is used to ensure that the http function can be used to get the data from the products.json file."
},
{
"code": null,
"e": 5114,
"s": 4861,
"text": "The following statements are used to make use of the Reactive framework which can be used to create an Observable variable. The Observable framework is used to detect any changes in the http response which can then be sent back to the main application."
},
{
"code": null,
"e": 5367,
"s": 5114,
"text": "The following statements are used to make use of the Reactive framework which can be used to create an Observable variable. The Observable framework is used to detect any changes in the http response which can then be sent back to the main application."
},
{
"code": null,
"e": 5477,
"s": 5367,
"text": "import { Observable } from 'rxjs/Observable';\nimport 'rxjs/add/operator/map';\nimport 'rxjs/add/operator/do';\n"
},
{
"code": null,
"e": 5659,
"s": 5477,
"text": "The statement private _producturl = 'app/products.json' in the class is used to specify the location of our data source. It can also specify the location of web service if required."
},
{
"code": null,
"e": 5841,
"s": 5659,
"text": "The statement private _producturl = 'app/products.json' in the class is used to specify the location of our data source. It can also specify the location of web service if required."
},
{
"code": null,
"e": 5946,
"s": 5841,
"text": "Next, we define a variable of the type Http which will be used to get the response from the data source."
},
{
"code": null,
"e": 6051,
"s": 5946,
"text": "Next, we define a variable of the type Http which will be used to get the response from the data source."
},
{
"code": null,
"e": 6187,
"s": 6051,
"text": "Once we get the data from the data source, we then use the JSON.stringify(data) command to send the data to the console in the browser."
},
{
"code": null,
"e": 6323,
"s": 6187,
"text": "Once we get the data from the data source, we then use the JSON.stringify(data) command to send the data to the console in the browser."
},
{
"code": null,
"e": 6392,
"s": 6323,
"text": "Step 7 − Now in the app.component.ts file, place the following code."
},
{
"code": null,
"e": 7045,
"s": 6392,
"text": "import { Component } from '@angular/core';\nimport { IProduct } from './product';\nimport { ProductService } from './products.service';\nimport { appService } from './app.service';\nimport { Http , Response } from '@angular/http';\nimport { Observable } from 'rxjs/Observable';\nimport 'rxjs/add/operator/map';\n\n@Component ({\n selector: 'my-app',\n template: '<div>Hello</div>',\n providers: [ProductService]\n})\n\nexport class AppComponent {\n iproducts: IProduct[];\n constructor(private _product: ProductService) {\n }\n \n ngOnInit() : void {\n this._product.getproducts()\n .subscribe(iproducts => this.iproducts = iproducts);\n }\n}"
},
{
"code": null,
"e": 7208,
"s": 7045,
"text": "Here, the main thing in the code is the subscribe option which is used to listen to the Observable getproducts() function to listen for data from the data source."
},
{
"code": null,
"e": 7319,
"s": 7208,
"text": "Now save all the codes and run the application using npm. Go to the browser, we will see the following output."
},
{
"code": null,
"e": 7397,
"s": 7319,
"text": "In the Console, we will see the data being retrieved from products.json file."
},
{
"code": null,
"e": 7432,
"s": 7397,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7446,
"s": 7432,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7481,
"s": 7446,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7495,
"s": 7481,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7530,
"s": 7495,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 7550,
"s": 7530,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 7585,
"s": 7550,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7602,
"s": 7585,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7635,
"s": 7602,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7647,
"s": 7635,
"text": " Senol Atac"
},
{
"code": null,
"e": 7682,
"s": 7647,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7694,
"s": 7682,
"text": " Senol Atac"
},
{
"code": null,
"e": 7701,
"s": 7694,
"text": " Print"
},
{
"code": null,
"e": 7712,
"s": 7701,
"text": " Add Notes"
}
] |
How to Invoke Keyboard Programmatically in Android? - GeeksforGeeks
|
23 Feb, 2021
Android System by defaults shows an on-screen keyboard when any UI element such as an Input Text element receives focus. For a better experience, a developer can explicitly specify the desired characteristics or any methods to invoke. Desired characteristics could be characters such as allowing only numerals, allowing only alphabets, or any other similar thing. Desired methods could be to provide an auto-correct function or provide an emoticon. An input text field might be present on the layout, and the developer does not wish it to gain focus unless invoked, or vice-versa. Because if it receives focus, the soft keyboard gets invoked, and there is a complete deviation from the actual context. Similarly, the reverse is persuaded in case the inputs are needed before showing any context. Through this article, we want to share with you how we can invoke the soft-keyboard, and this could be applied to any desired application. Note that we are going to implement this project using the Kotlin language.
Keyboards are generally invoked by the Input Methods such as an EditText, yet we can invoke them without such input methods. There are two ways by which we can accomplish this task, by making considerable changes to:
AndroidManifest.xml file (or)MainActivity.kt file
AndroidManifest.xml file (or)
MainActivity.kt file
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Go to either AndroidManifest.xml file or MainActivity.kt file
Go to either AndroidManifest.xml file or MainActivity.kt file and refer the following code. Note that both approaches can be implemented at a time.
Approach 1: Working with AndroidManifest.xml file
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.ao1"> <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" android:windowSoftInputMode="stateVisible"> <!--This entitity was explicitly added for desired result--> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> <!--Refer here Againandroid:windowSoftInputMode="stateVisible"-->
Approach 2: Working with the MainActivity.kt file
Kotlin
import android.os.Bundleimport android.view.WindowManagerimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Calls Soft Input Mode to make it Visible window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) }}
Android-Misc
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Flexbox-Layout in Android
Retrofit with Kotlin Coroutine in Android
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters
Kotlin when expression
|
[
{
"code": null,
"e": 26491,
"s": 26463,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 27503,
"s": 26491,
"text": "Android System by defaults shows an on-screen keyboard when any UI element such as an Input Text element receives focus. For a better experience, a developer can explicitly specify the desired characteristics or any methods to invoke. Desired characteristics could be characters such as allowing only numerals, allowing only alphabets, or any other similar thing. Desired methods could be to provide an auto-correct function or provide an emoticon. An input text field might be present on the layout, and the developer does not wish it to gain focus unless invoked, or vice-versa. Because if it receives focus, the soft keyboard gets invoked, and there is a complete deviation from the actual context. Similarly, the reverse is persuaded in case the inputs are needed before showing any context. Through this article, we want to share with you how we can invoke the soft-keyboard, and this could be applied to any desired application. Note that we are going to implement this project using the Kotlin language. "
},
{
"code": null,
"e": 27720,
"s": 27503,
"text": "Keyboards are generally invoked by the Input Methods such as an EditText, yet we can invoke them without such input methods. There are two ways by which we can accomplish this task, by making considerable changes to:"
},
{
"code": null,
"e": 27770,
"s": 27720,
"text": "AndroidManifest.xml file (or)MainActivity.kt file"
},
{
"code": null,
"e": 27800,
"s": 27770,
"text": "AndroidManifest.xml file (or)"
},
{
"code": null,
"e": 27821,
"s": 27800,
"text": "MainActivity.kt file"
},
{
"code": null,
"e": 27850,
"s": 27821,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 28014,
"s": 27850,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language."
},
{
"code": null,
"e": 28084,
"s": 28014,
"text": "Step 2: Go to either AndroidManifest.xml file or MainActivity.kt file"
},
{
"code": null,
"e": 28232,
"s": 28084,
"text": "Go to either AndroidManifest.xml file or MainActivity.kt file and refer the following code. Note that both approaches can be implemented at a time."
},
{
"code": null,
"e": 28282,
"s": 28232,
"text": "Approach 1: Working with AndroidManifest.xml file"
},
{
"code": null,
"e": 28286,
"s": 28282,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.ao1\"> <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\" android:windowSoftInputMode=\"stateVisible\"> <!--This entitity was explicitly added for desired result--> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest> <!--Refer here Againandroid:windowSoftInputMode=\"stateVisible\"-->",
"e": 29195,
"s": 28286,
"text": null
},
{
"code": null,
"e": 29245,
"s": 29195,
"text": "Approach 2: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 29252,
"s": 29245,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport android.view.WindowManagerimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Calls Soft Input Mode to make it Visible window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) }}",
"e": 29688,
"s": 29252,
"text": null
},
{
"code": null,
"e": 29701,
"s": 29688,
"text": "Android-Misc"
},
{
"code": null,
"e": 29709,
"s": 29701,
"text": "Android"
},
{
"code": null,
"e": 29716,
"s": 29709,
"text": "Kotlin"
},
{
"code": null,
"e": 29724,
"s": 29716,
"text": "Android"
},
{
"code": null,
"e": 29822,
"s": 29724,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29860,
"s": 29822,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 29899,
"s": 29860,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 29949,
"s": 29899,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 29975,
"s": 29949,
"text": "Flexbox-Layout in Android"
},
{
"code": null,
"e": 30017,
"s": 29975,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 30036,
"s": 30017,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 30049,
"s": 30036,
"text": "Kotlin Array"
},
{
"code": null,
"e": 30091,
"s": 30049,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 30118,
"s": 30091,
"text": "Kotlin Setters and Getters"
}
] |
Node.js response.write() Method - GeeksforGeeks
|
23 Sep, 2020
The response.write() (Added in v0.1.29) method is an inbuilt Application program Interface of the ‘http’ module which sends a chunk of the response body that is omitted when the request is a HEAD request. If this method is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers.
The first time response.write() is called, it will send the buffered header information and the first chunk of the body to the client. The second time response.write() is called, Node.js assumes data will be streamed and sends the new data separately. That is, the response is buffered up to the first chunk of the body. A chunk can be a string or a buffer. If the chunk is a string, the second parameter specifies how to encode it into a byte stream. And the callback will be called when this chunk of data is flushed.
In order to get a response and a proper result, we need to import ‘http’ module.
Import:
const http = require('http');
Syntax:
response.write(chunk[, encoding][, callback]);
Parameters: This method accepts three parameters as mentioned above and described below:
chunk <string> | <Buffer>: It accepts any Buffer, or String Data.
encoding <string>: The default encoding set is ‘utf8‘. It accepts String Data.
callback <Function>: It accepts a callback function.
Return Value <Boolean>: It returns true if the entire data was flushed successfully to the kernel buffer and returns false if all or part of the data was queued in user memory. The ‘drain‘ will be emitted when the buffer is free again.
The below example illustrates the use of response.write() property in Node.js.
Example 1: Filename: index.js
// Node.js program to demonstrate the // response.write() Method // Importing http modulevar http = require('http'); // Setting up PORTconst PORT = process.env.PORT || 3000; // Creating http Servervar httpServer = http.createServer(function(request, response){ // Writing string data response.write("Heyy geeksforgeeks ", 'utf8', () => { console.log("Writing string Data..."); }); // Prints Output on the browser in response response.end(' ok');}); // Listening to http ServerhttpServer.listen(PORT, () => { console.log("Server is running at port 3000...");});
Output:
Output: In-Console
Server is running at port 3000...
Writing string Data...
Now run http://localhost:3000/ in the browser.
Output: In-Browser
Heyy geeksforgeeks ok
Example 2: Filename: index.js
// Node.js program to demonstrate the // response.write() Method // Importing http modulevar http = require('http'); // Setting up PORTconst PORT = process.env.PORT || 3000; // Creating http Servervar httpServer = http.createServer(function(request, response){ var str = "GeeksForGeeks wishes you a warm welcome..."; // Writing string data with // 16-bit Unicode Transformation Format response.write(str, 'utf16', () => { console.log("Writing string Data..."); }); // Allocating predefined Buffer 'Hello world' const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); // Writing the buffer data. response.write(buf, 'utf8', () => { console.log("Writing Buffer Data..."); }); // Creating buffer const buff = Buffer.from(' hello world', 'utf8'); // Writing the buffer data. response.write(buff, 'utf8', () => { console.log("Writing Buffer Data..."); }); // Prints Output on the browser in response response.end(' ok');}); // Listening to http ServerhttpServer.listen(PORT, () => { console.log("Server is running at port 3000...");});
Run index.js file using the following command:
node index.js
Output:
Output: In-Console
Server is running at port 3000...
Writing string Data...
Writing Buffer Data...
Writing Buffer Data...
Now run http://localhost:3000/ in the browser.
Output: In-Browser
GeeksForGeeks wishes you a warm welcome...hello world hello world ok
Reference: https://nodejs.org/api/http.html#http_response_write_chunk_encoding_callback
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 24626,
"s": 24598,
"text": "\n23 Sep, 2020"
},
{
"code": null,
"e": 24973,
"s": 24626,
"text": "The response.write() (Added in v0.1.29) method is an inbuilt Application program Interface of the ‘http’ module which sends a chunk of the response body that is omitted when the request is a HEAD request. If this method is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers."
},
{
"code": null,
"e": 25493,
"s": 24973,
"text": "The first time response.write() is called, it will send the buffered header information and the first chunk of the body to the client. The second time response.write() is called, Node.js assumes data will be streamed and sends the new data separately. That is, the response is buffered up to the first chunk of the body. A chunk can be a string or a buffer. If the chunk is a string, the second parameter specifies how to encode it into a byte stream. And the callback will be called when this chunk of data is flushed."
},
{
"code": null,
"e": 25574,
"s": 25493,
"text": "In order to get a response and a proper result, we need to import ‘http’ module."
},
{
"code": null,
"e": 25582,
"s": 25574,
"text": "Import:"
},
{
"code": null,
"e": 25613,
"s": 25582,
"text": "const http = require('http');\n"
},
{
"code": null,
"e": 25621,
"s": 25613,
"text": "Syntax:"
},
{
"code": null,
"e": 25669,
"s": 25621,
"text": "response.write(chunk[, encoding][, callback]);\n"
},
{
"code": null,
"e": 25758,
"s": 25669,
"text": "Parameters: This method accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 25824,
"s": 25758,
"text": "chunk <string> | <Buffer>: It accepts any Buffer, or String Data."
},
{
"code": null,
"e": 25903,
"s": 25824,
"text": "encoding <string>: The default encoding set is ‘utf8‘. It accepts String Data."
},
{
"code": null,
"e": 25956,
"s": 25903,
"text": "callback <Function>: It accepts a callback function."
},
{
"code": null,
"e": 26192,
"s": 25956,
"text": "Return Value <Boolean>: It returns true if the entire data was flushed successfully to the kernel buffer and returns false if all or part of the data was queued in user memory. The ‘drain‘ will be emitted when the buffer is free again."
},
{
"code": null,
"e": 26271,
"s": 26192,
"text": "The below example illustrates the use of response.write() property in Node.js."
},
{
"code": null,
"e": 26301,
"s": 26271,
"text": "Example 1: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate the // response.write() Method // Importing http modulevar http = require('http'); // Setting up PORTconst PORT = process.env.PORT || 3000; // Creating http Servervar httpServer = http.createServer(function(request, response){ // Writing string data response.write(\"Heyy geeksforgeeks \", 'utf8', () => { console.log(\"Writing string Data...\"); }); // Prints Output on the browser in response response.end(' ok');}); // Listening to http ServerhttpServer.listen(PORT, () => { console.log(\"Server is running at port 3000...\");});",
"e": 26883,
"s": 26301,
"text": null
},
{
"code": null,
"e": 26891,
"s": 26883,
"text": "Output:"
},
{
"code": null,
"e": 26910,
"s": 26891,
"text": "Output: In-Console"
},
{
"code": null,
"e": 26944,
"s": 26910,
"text": "Server is running at port 3000..."
},
{
"code": null,
"e": 26967,
"s": 26944,
"text": "Writing string Data..."
},
{
"code": null,
"e": 27014,
"s": 26967,
"text": "Now run http://localhost:3000/ in the browser."
},
{
"code": null,
"e": 27033,
"s": 27014,
"text": "Output: In-Browser"
},
{
"code": null,
"e": 27056,
"s": 27033,
"text": "Heyy geeksforgeeks ok"
},
{
"code": null,
"e": 27086,
"s": 27056,
"text": "Example 2: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate the // response.write() Method // Importing http modulevar http = require('http'); // Setting up PORTconst PORT = process.env.PORT || 3000; // Creating http Servervar httpServer = http.createServer(function(request, response){ var str = \"GeeksForGeeks wishes you a warm welcome...\"; // Writing string data with // 16-bit Unicode Transformation Format response.write(str, 'utf16', () => { console.log(\"Writing string Data...\"); }); // Allocating predefined Buffer 'Hello world' const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); // Writing the buffer data. response.write(buf, 'utf8', () => { console.log(\"Writing Buffer Data...\"); }); // Creating buffer const buff = Buffer.from(' hello world', 'utf8'); // Writing the buffer data. response.write(buff, 'utf8', () => { console.log(\"Writing Buffer Data...\"); }); // Prints Output on the browser in response response.end(' ok');}); // Listening to http ServerhttpServer.listen(PORT, () => { console.log(\"Server is running at port 3000...\");});",
"e": 28171,
"s": 27086,
"text": null
},
{
"code": null,
"e": 28218,
"s": 28171,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 28232,
"s": 28218,
"text": "node index.js"
},
{
"code": null,
"e": 28240,
"s": 28232,
"text": "Output:"
},
{
"code": null,
"e": 28259,
"s": 28240,
"text": "Output: In-Console"
},
{
"code": null,
"e": 28293,
"s": 28259,
"text": "Server is running at port 3000..."
},
{
"code": null,
"e": 28316,
"s": 28293,
"text": "Writing string Data..."
},
{
"code": null,
"e": 28339,
"s": 28316,
"text": "Writing Buffer Data..."
},
{
"code": null,
"e": 28362,
"s": 28339,
"text": "Writing Buffer Data..."
},
{
"code": null,
"e": 28409,
"s": 28362,
"text": "Now run http://localhost:3000/ in the browser."
},
{
"code": null,
"e": 28428,
"s": 28409,
"text": "Output: In-Browser"
},
{
"code": null,
"e": 28497,
"s": 28428,
"text": "GeeksForGeeks wishes you a warm welcome...hello world hello world ok"
},
{
"code": null,
"e": 28585,
"s": 28497,
"text": "Reference: https://nodejs.org/api/http.html#http_response_write_chunk_encoding_callback"
},
{
"code": null,
"e": 28601,
"s": 28585,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 28609,
"s": 28601,
"text": "Node.js"
},
{
"code": null,
"e": 28626,
"s": 28609,
"text": "Web Technologies"
},
{
"code": null,
"e": 28724,
"s": 28626,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28754,
"s": 28724,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 28783,
"s": 28754,
"text": "Node.js fs.readFile() Method"
},
{
"code": null,
"e": 28840,
"s": 28783,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 28894,
"s": 28840,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 28931,
"s": 28894,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 28971,
"s": 28931,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29016,
"s": 28971,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29059,
"s": 29016,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29109,
"s": 29059,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
The dice problem
|
05 Aug, 2021
You are given a cubic dice with 6 faces. All the individual faces have a number printed on them. The numbers are in the range of 1 to 6, like any ordinary dice. You will be provided with a face of this cube, your task is to guess the number on the opposite face of the cube.
Examples:
Input: N = 2Output: 5Explanation:For dice facing number 5 opposite face will have the number 2.
Input: N = 6Output: 1
Naive Approach: In a normal 6 faced dice, 1 is opposite to 6, 2 is opposite to 5, and 3 is opposite to 4. Hence a normal if-else-if block can be placed
Approach: The idea is based on the observation that the sum of two opposite sides of a cubical dice is equal to 7. So, just subtract the given N from 7 and print the answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to find number// written on the// opposite face of the diceint oppositeFaceOfDice(int N){ // Stores number on opposite face // of dice int ans = 7 - N; // Print the answer cout << ans;} // Driver Codeint main(){ // Given value of N int N = 2; // Function call to find number written on // the opposite face of the dice oppositeFaceOfDice(N); return 0;}
// Java program for the above approachimport java.io.*; class GFG{ // Function to find number // written on the // opposite face of the dice static void oppositeFaceOfDice(int N) { // Stores number on opposite face // of dice int ans = 7 - N; // Print the answer System.out.println(ans); } // Driver Code public static void main(String[] args) { // Given value of N int N = 2; // Function call to find number written on // the opposite face of the dice oppositeFaceOfDice(N); }} // This code is contributed by Potta Lokesh
# Python3 program for the above approach # Function to find number written on the# opposite face of the dicedef oppositeFaceOfDice(N): # Stores number on opposite face # of dice ans = 7 - N # Print the answer print(ans) # Driver Code # Given value of NN = 2 # Function call to find number written on# the opposite face of the diceoppositeFaceOfDice(N) # This code is contributed by gfgking
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find number// written on the// opposite face of the dicestatic void oppositeFaceOfDice(int N){ // Stores number on opposite face // of dice int ans = 7 - N; // Print the answer Console.Write(ans);} // Driver Codepublic static void Main(){ // Given value of N int N = 2; // Function call to find number written on // the opposite face of the dice oppositeFaceOfDice(N);}} // This code is contributed by SURENDRA_GANGWAR.
<script> // JavaScript program for the above approach // Function to find number// written on the// opposite face of the dicefunction oppositeFaceOfDice(N) { // Stores number on opposite face // of dice let ans = 7 - N; // Print the answer document.write(ans);} // Driver Code // Given value of Nlet N = 2; // Function call to find number written on// the opposite face of the diceoppositeFaceOfDice(N); // This code is contributed by gfgking </script>
5
Time Complexity: O(1)Auxiliary Space: O(1)
lokeshpotta20
gfgking
SURENDRA_GANGWAR
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 328,
"s": 53,
"text": "You are given a cubic dice with 6 faces. All the individual faces have a number printed on them. The numbers are in the range of 1 to 6, like any ordinary dice. You will be provided with a face of this cube, your task is to guess the number on the opposite face of the cube."
},
{
"code": null,
"e": 338,
"s": 328,
"text": "Examples:"
},
{
"code": null,
"e": 434,
"s": 338,
"text": "Input: N = 2Output: 5Explanation:For dice facing number 5 opposite face will have the number 2."
},
{
"code": null,
"e": 456,
"s": 434,
"text": "Input: N = 6Output: 1"
},
{
"code": null,
"e": 609,
"s": 456,
"text": "Naive Approach: In a normal 6 faced dice, 1 is opposite to 6, 2 is opposite to 5, and 3 is opposite to 4. Hence a normal if-else-if block can be placed "
},
{
"code": null,
"e": 783,
"s": 609,
"text": "Approach: The idea is based on the observation that the sum of two opposite sides of a cubical dice is equal to 7. So, just subtract the given N from 7 and print the answer."
},
{
"code": null,
"e": 834,
"s": 783,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 838,
"s": 834,
"text": "C++"
},
{
"code": null,
"e": 843,
"s": 838,
"text": "Java"
},
{
"code": null,
"e": 851,
"s": 843,
"text": "Python3"
},
{
"code": null,
"e": 854,
"s": 851,
"text": "C#"
},
{
"code": null,
"e": 865,
"s": 854,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to find number// written on the// opposite face of the diceint oppositeFaceOfDice(int N){ // Stores number on opposite face // of dice int ans = 7 - N; // Print the answer cout << ans;} // Driver Codeint main(){ // Given value of N int N = 2; // Function call to find number written on // the opposite face of the dice oppositeFaceOfDice(N); return 0;}",
"e": 1347,
"s": 865,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*; class GFG{ // Function to find number // written on the // opposite face of the dice static void oppositeFaceOfDice(int N) { // Stores number on opposite face // of dice int ans = 7 - N; // Print the answer System.out.println(ans); } // Driver Code public static void main(String[] args) { // Given value of N int N = 2; // Function call to find number written on // the opposite face of the dice oppositeFaceOfDice(N); }} // This code is contributed by Potta Lokesh",
"e": 1990,
"s": 1347,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find number written on the# opposite face of the dicedef oppositeFaceOfDice(N): # Stores number on opposite face # of dice ans = 7 - N # Print the answer print(ans) # Driver Code # Given value of NN = 2 # Function call to find number written on# the opposite face of the diceoppositeFaceOfDice(N) # This code is contributed by gfgking",
"e": 2405,
"s": 1990,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find number// written on the// opposite face of the dicestatic void oppositeFaceOfDice(int N){ // Stores number on opposite face // of dice int ans = 7 - N; // Print the answer Console.Write(ans);} // Driver Codepublic static void Main(){ // Given value of N int N = 2; // Function call to find number written on // the opposite face of the dice oppositeFaceOfDice(N);}} // This code is contributed by SURENDRA_GANGWAR.",
"e": 2969,
"s": 2405,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to find number// written on the// opposite face of the dicefunction oppositeFaceOfDice(N) { // Stores number on opposite face // of dice let ans = 7 - N; // Print the answer document.write(ans);} // Driver Code // Given value of Nlet N = 2; // Function call to find number written on// the opposite face of the diceoppositeFaceOfDice(N); // This code is contributed by gfgking </script>",
"e": 3428,
"s": 2969,
"text": null
},
{
"code": null,
"e": 3430,
"s": 3428,
"text": "5"
},
{
"code": null,
"e": 3473,
"s": 3430,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3489,
"s": 3475,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 3497,
"s": 3489,
"text": "gfgking"
},
{
"code": null,
"e": 3514,
"s": 3497,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 3527,
"s": 3514,
"text": "Mathematical"
},
{
"code": null,
"e": 3540,
"s": 3527,
"text": "Mathematical"
}
] |
Python List reverse()
|
03 Aug, 2021
Python List reverse() is an inbuilt method in the Python programming language that reverses objects of the List in place.
Syntax:
list_name.reverse()
Parameters:
There are no parameters.
Returns:
The reverse() method does not return any value but reverses the given object from the list.
Error:
When anything other than list is used in place of list, then it returns an AttributeError
Python3
# Python3 program to demonstrate the# use of reverse method # a list of numberslist1 = [1, 2, 3, 4, 1, 2, 6]list1.reverse()print(list1) # a list of characterslist2 = ['a', 'b', 'c', 'd', 'a', 'a']list2.reverse()print(list2)
Output:
[6, 2, 1, 4, 3, 2, 1]
['a', 'a', 'd', 'c', 'b', 'a']
Python3
# Python3 program to demonstrate the# error in reverse() method # error when string is used in place of liststring = "abgedge"string.reverse()print(string)
Output:
Traceback (most recent call last):
File "/home/b3cf360e62d8812babb5549c3a4d3d30.py", line 5, in
string.reverse()
AttributeError: 'str' object has no attribute 'reverse'
Given a list of numbers, check if the list is a palindrome.
Note: Palindrome-sequence that reads the same backward as forwards.
Python3
# Python3 program for the# practical application of reverse() list1 = [1, 2, 3, 2, 1] # store a copy of listlist2 = list1.copy() # reverse the listlist2.reverse() # compare reversed and original listif list1 == list2: print("Palindrome")else: print("Not Palindrome")
Output:
Palindrome
AmiyaRanjanRout
python-list
python-list-functions
Reverse
Python
python-list
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 174,
"s": 52,
"text": "Python List reverse() is an inbuilt method in the Python programming language that reverses objects of the List in place."
},
{
"code": null,
"e": 183,
"s": 174,
"text": "Syntax: "
},
{
"code": null,
"e": 203,
"s": 183,
"text": "list_name.reverse()"
},
{
"code": null,
"e": 216,
"s": 203,
"text": "Parameters: "
},
{
"code": null,
"e": 241,
"s": 216,
"text": "There are no parameters."
},
{
"code": null,
"e": 251,
"s": 241,
"text": "Returns: "
},
{
"code": null,
"e": 343,
"s": 251,
"text": "The reverse() method does not return any value but reverses the given object from the list."
},
{
"code": null,
"e": 350,
"s": 343,
"text": "Error:"
},
{
"code": null,
"e": 440,
"s": 350,
"text": "When anything other than list is used in place of list, then it returns an AttributeError"
},
{
"code": null,
"e": 448,
"s": 440,
"text": "Python3"
},
{
"code": "# Python3 program to demonstrate the# use of reverse method # a list of numberslist1 = [1, 2, 3, 4, 1, 2, 6]list1.reverse()print(list1) # a list of characterslist2 = ['a', 'b', 'c', 'd', 'a', 'a']list2.reverse()print(list2)",
"e": 673,
"s": 448,
"text": null
},
{
"code": null,
"e": 682,
"s": 673,
"text": "Output: "
},
{
"code": null,
"e": 735,
"s": 682,
"text": "[6, 2, 1, 4, 3, 2, 1]\n['a', 'a', 'd', 'c', 'b', 'a']"
},
{
"code": null,
"e": 743,
"s": 735,
"text": "Python3"
},
{
"code": "# Python3 program to demonstrate the# error in reverse() method # error when string is used in place of liststring = \"abgedge\"string.reverse()print(string)",
"e": 900,
"s": 743,
"text": null
},
{
"code": null,
"e": 909,
"s": 900,
"text": "Output: "
},
{
"code": null,
"e": 1087,
"s": 909,
"text": "Traceback (most recent call last):\n File \"/home/b3cf360e62d8812babb5549c3a4d3d30.py\", line 5, in \n string.reverse() \nAttributeError: 'str' object has no attribute 'reverse' "
},
{
"code": null,
"e": 1148,
"s": 1087,
"text": "Given a list of numbers, check if the list is a palindrome. "
},
{
"code": null,
"e": 1216,
"s": 1148,
"text": "Note: Palindrome-sequence that reads the same backward as forwards."
},
{
"code": null,
"e": 1224,
"s": 1216,
"text": "Python3"
},
{
"code": "# Python3 program for the# practical application of reverse() list1 = [1, 2, 3, 2, 1] # store a copy of listlist2 = list1.copy() # reverse the listlist2.reverse() # compare reversed and original listif list1 == list2: print(\"Palindrome\")else: print(\"Not Palindrome\")",
"e": 1498,
"s": 1224,
"text": null
},
{
"code": null,
"e": 1507,
"s": 1498,
"text": "Output: "
},
{
"code": null,
"e": 1518,
"s": 1507,
"text": "Palindrome"
},
{
"code": null,
"e": 1534,
"s": 1518,
"text": "AmiyaRanjanRout"
},
{
"code": null,
"e": 1546,
"s": 1534,
"text": "python-list"
},
{
"code": null,
"e": 1568,
"s": 1546,
"text": "python-list-functions"
},
{
"code": null,
"e": 1576,
"s": 1568,
"text": "Reverse"
},
{
"code": null,
"e": 1583,
"s": 1576,
"text": "Python"
},
{
"code": null,
"e": 1595,
"s": 1583,
"text": "python-list"
},
{
"code": null,
"e": 1603,
"s": 1595,
"text": "Reverse"
}
] |
p5.js | color() Function
|
25 Jul, 2019
The color() function is used to create color and store it into variables. The parameters of color function are RGB or HSB value depending on the current colorMode() function. The default mode of color() function is RGB value from 0 to 255. Therefore, the function color(255, 204, 0) will return a bright yellow color.
Syntax:
color(gray, alpha)
color(v1, v2, v3, alpha)
color(value)
color(values)
color(color)
Parameters:
gray: It is used to set the gray value between white and black.
alpha: It is used to set the transparency of the drawing.
v1: It is used to set the red or hue value relative to current color range.
v2: It is used to set the green or saturation value relative to current color range.
v3: It is used to set the blue or brightness value relative to current color range.
value: It is used to set the value of color string.
values: It is an array containing the red, green, blue and alpha value.
color: It is used to set the stroke color.
Return Value: It returns the resulting color value.
Example 1:
function setup() { // Create Canvas of given size createCanvas(400, 300); } function draw() { background(220); // Use color() function let c = color('green'); // Use fill() function to fill color fill(c); // Draw a circle circle(200, 150, 150); }
Output:
Example 2:
function setup() { // Create Canvas of given size createCanvas(400, 300); } function draw() { // Set the background color background(220); // Use color() function let c = color(0, 155, 0); // Use fill() function to fill color fill(c) // Draw a line rect(50, 50, 250, 150); }
Output:
Reference: https://p5js.org/reference/#/p5/color
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Jul, 2019"
},
{
"code": null,
"e": 346,
"s": 28,
"text": "The color() function is used to create color and store it into variables. The parameters of color function are RGB or HSB value depending on the current colorMode() function. The default mode of color() function is RGB value from 0 to 255. Therefore, the function color(255, 204, 0) will return a bright yellow color."
},
{
"code": null,
"e": 354,
"s": 346,
"text": "Syntax:"
},
{
"code": null,
"e": 439,
"s": 354,
"text": "color(gray, alpha)\ncolor(v1, v2, v3, alpha)\ncolor(value)\ncolor(values)\ncolor(color)\n"
},
{
"code": null,
"e": 451,
"s": 439,
"text": "Parameters:"
},
{
"code": null,
"e": 515,
"s": 451,
"text": "gray: It is used to set the gray value between white and black."
},
{
"code": null,
"e": 573,
"s": 515,
"text": "alpha: It is used to set the transparency of the drawing."
},
{
"code": null,
"e": 649,
"s": 573,
"text": "v1: It is used to set the red or hue value relative to current color range."
},
{
"code": null,
"e": 734,
"s": 649,
"text": "v2: It is used to set the green or saturation value relative to current color range."
},
{
"code": null,
"e": 818,
"s": 734,
"text": "v3: It is used to set the blue or brightness value relative to current color range."
},
{
"code": null,
"e": 870,
"s": 818,
"text": "value: It is used to set the value of color string."
},
{
"code": null,
"e": 942,
"s": 870,
"text": "values: It is an array containing the red, green, blue and alpha value."
},
{
"code": null,
"e": 985,
"s": 942,
"text": "color: It is used to set the stroke color."
},
{
"code": null,
"e": 1037,
"s": 985,
"text": "Return Value: It returns the resulting color value."
},
{
"code": null,
"e": 1048,
"s": 1037,
"text": "Example 1:"
},
{
"code": "function setup() { // Create Canvas of given size createCanvas(400, 300); } function draw() { background(220); // Use color() function let c = color('green'); // Use fill() function to fill color fill(c); // Draw a circle circle(200, 150, 150); } ",
"e": 1359,
"s": 1048,
"text": null
},
{
"code": null,
"e": 1367,
"s": 1359,
"text": "Output:"
},
{
"code": null,
"e": 1378,
"s": 1367,
"text": "Example 2:"
},
{
"code": "function setup() { // Create Canvas of given size createCanvas(400, 300); } function draw() { // Set the background color background(220); // Use color() function let c = color(0, 155, 0); // Use fill() function to fill color fill(c) // Draw a line rect(50, 50, 250, 150); } ",
"e": 1722,
"s": 1378,
"text": null
},
{
"code": null,
"e": 1730,
"s": 1722,
"text": "Output:"
},
{
"code": null,
"e": 1779,
"s": 1730,
"text": "Reference: https://p5js.org/reference/#/p5/color"
},
{
"code": null,
"e": 1796,
"s": 1779,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 1807,
"s": 1796,
"text": "JavaScript"
},
{
"code": null,
"e": 1824,
"s": 1807,
"text": "Web Technologies"
}
] |
Short Circuiting Techniques in Python
|
15 May, 2022
By short-circuiting, we mean the stoppage of execution of boolean operation if the truth value of expression has been determined already. The evaluation of expression takes place from left to right. In python, short-circuiting is supported by various boolean operators and functions.
The chart given below gives an insight into the short-circuiting case of boolean expressions. Boolean operators are ordered by ascending priority.
or: When the Python interpreter scans or expression, it takes the first statement and checks to see if it is true. If the first statement is true, then Python returns that object’s value without checking the second statement. The program does not bother with the second statement. If the first value is false, only then Python check the second value, and then the result is based on the second half. and: For an and expression, Python uses a short circuit technique to check if the first statement is false then the whole statement must be false, so it returns that value. Only if the first value is true, does it check the second statement and return the value. An expression containing and or stops execution when the truth value of expression has been achieved. Evaluation takes place from left to right.
Python3
# python code to demonstrate short circuiting # using and and or # helper functiondef check(): return "geeks" # using an expression to demonstrate# prints "geeks", and gets executed # as both are required to check truth valueprint (1 and check()) # using an expression to demonstrate# prints 1# as only if 1st value is true, or # doesnt require call check() funprint (1 or check()) # using an expression to demonstrate# prints "geeks"# the value returns true when check # is encountered. 1 is not executedprint (0 or check() or 1) # using an expression to demonstrate# prints 1# as last value is required to evaluate# full expression because of "and"print (0 or check() and 1)
geeks
1
geeks
1
Inbuilt functions all() and any() in python also support short-circuiting. The example below would give you clear insight into how it works.
Python3
# python code to demonstrate short circuiting # using all() and any() # helper functiondef check(i): print ("geeks") return i # using all()# stops execution when false occurs# tells the compiler that even if one is # false, all cannot be true, hence stop # execution further.# prints 3 "geeks" print (all(check(i) for i in [1, 1, 0, 0, 3])) print("\r") # using any()# stops execution when true occurs# tells the compiler that even if one is # true, expression is true, hence stop # execution further.# prints 4 "geeks" print (any(check(i) for i in [0, 0, 0, 1, 3]))
geeks
geeks
geeks
False
geeks
geeks
geeks
geeks
True
Conditional operators also follow short-circuiting as when expression result is obtained, further execution is not required.
Python3
# python code to demonstrate short circuiting # using conditional operators # helper functiondef check(i): print ("geeks") return i # using conditional expressions# since 10 is not greater than 11# further execution is not taken place # to check for truth value.print( 10 > 11 > check(3) ) print ("\r") # using conditional expressions# since 11 is greater than 10# further execution is taken place # to check for truth value.# return true as 11 > 3print( 10 < 11 > check(3) ) print ("\r") # using conditional expressions# since 11 is greater than 10# further execution is taken place # to check for truth value.# return false as 11 < 12print( 10 < 11 > check(12) )
False
geeks
True
geeks
False
Short-circuiting in a ladder of if, elif, elif, ... else statements
When there is a sequence, aka a “ladder” of if and one or more elif statements, none of the conditions after the first one found to be True are evaluated.
Python3
a = 10b = 20c = 30 def printreturn(l): print(l) return l if a == 11: print("a == 11")elif b == 20 and c == 30: # This is True print("b==20 and c==30")elif b == a+a and 0<len(printreturn("This was evaluated")): # Though True, this is not even evaluated print("b == a+a")
b==20 and c==30
This article is contributed by Manjeet Singh. 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 if you want to share more information about the topic discussed above.
nidhi_biet
punamsingh628700
amartyaghoshgfg
dakra137
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n15 May, 2022"
},
{
"code": null,
"e": 339,
"s": 54,
"text": "By short-circuiting, we mean the stoppage of execution of boolean operation if the truth value of expression has been determined already. The evaluation of expression takes place from left to right. In python, short-circuiting is supported by various boolean operators and functions. "
},
{
"code": null,
"e": 487,
"s": 339,
"text": "The chart given below gives an insight into the short-circuiting case of boolean expressions. Boolean operators are ordered by ascending priority. "
},
{
"code": null,
"e": 1295,
"s": 487,
"text": "or: When the Python interpreter scans or expression, it takes the first statement and checks to see if it is true. If the first statement is true, then Python returns that object’s value without checking the second statement. The program does not bother with the second statement. If the first value is false, only then Python check the second value, and then the result is based on the second half. and: For an and expression, Python uses a short circuit technique to check if the first statement is false then the whole statement must be false, so it returns that value. Only if the first value is true, does it check the second statement and return the value. An expression containing and or stops execution when the truth value of expression has been achieved. Evaluation takes place from left to right."
},
{
"code": null,
"e": 1303,
"s": 1295,
"text": "Python3"
},
{
"code": "# python code to demonstrate short circuiting # using and and or # helper functiondef check(): return \"geeks\" # using an expression to demonstrate# prints \"geeks\", and gets executed # as both are required to check truth valueprint (1 and check()) # using an expression to demonstrate# prints 1# as only if 1st value is true, or # doesnt require call check() funprint (1 or check()) # using an expression to demonstrate# prints \"geeks\"# the value returns true when check # is encountered. 1 is not executedprint (0 or check() or 1) # using an expression to demonstrate# prints 1# as last value is required to evaluate# full expression because of \"and\"print (0 or check() and 1)",
"e": 2000,
"s": 1303,
"text": null
},
{
"code": null,
"e": 2017,
"s": 2000,
"text": "geeks\n1\ngeeks\n1\n"
},
{
"code": null,
"e": 2158,
"s": 2017,
"text": "Inbuilt functions all() and any() in python also support short-circuiting. The example below would give you clear insight into how it works."
},
{
"code": null,
"e": 2166,
"s": 2158,
"text": "Python3"
},
{
"code": "# python code to demonstrate short circuiting # using all() and any() # helper functiondef check(i): print (\"geeks\") return i # using all()# stops execution when false occurs# tells the compiler that even if one is # false, all cannot be true, hence stop # execution further.# prints 3 \"geeks\" print (all(check(i) for i in [1, 1, 0, 0, 3])) print(\"\\r\") # using any()# stops execution when true occurs# tells the compiler that even if one is # true, expression is true, hence stop # execution further.# prints 4 \"geeks\" print (any(check(i) for i in [0, 0, 0, 1, 3]))",
"e": 2746,
"s": 2166,
"text": null
},
{
"code": null,
"e": 2801,
"s": 2746,
"text": "geeks\ngeeks\ngeeks\nFalse\n\ngeeks\ngeeks\ngeeks\ngeeks\nTrue\n"
},
{
"code": null,
"e": 2926,
"s": 2801,
"text": "Conditional operators also follow short-circuiting as when expression result is obtained, further execution is not required."
},
{
"code": null,
"e": 2934,
"s": 2926,
"text": "Python3"
},
{
"code": "# python code to demonstrate short circuiting # using conditional operators # helper functiondef check(i): print (\"geeks\") return i # using conditional expressions# since 10 is not greater than 11# further execution is not taken place # to check for truth value.print( 10 > 11 > check(3) ) print (\"\\r\") # using conditional expressions# since 11 is greater than 10# further execution is taken place # to check for truth value.# return true as 11 > 3print( 10 < 11 > check(3) ) print (\"\\r\") # using conditional expressions# since 11 is greater than 10# further execution is taken place # to check for truth value.# return false as 11 < 12print( 10 < 11 > check(12) )",
"e": 3623,
"s": 2934,
"text": null
},
{
"code": null,
"e": 3655,
"s": 3623,
"text": "False\n\ngeeks\nTrue\n\ngeeks\nFalse\n"
},
{
"code": null,
"e": 3723,
"s": 3655,
"text": "Short-circuiting in a ladder of if, elif, elif, ... else statements"
},
{
"code": null,
"e": 3880,
"s": 3723,
"text": "When there is a sequence, aka a “ladder” of if and one or more elif statements, none of the conditions after the first one found to be True are evaluated. "
},
{
"code": null,
"e": 3888,
"s": 3880,
"text": "Python3"
},
{
"code": "a = 10b = 20c = 30 def printreturn(l): print(l) return l if a == 11: print(\"a == 11\")elif b == 20 and c == 30: # This is True print(\"b==20 and c==30\")elif b == a+a and 0<len(printreturn(\"This was evaluated\")): # Though True, this is not even evaluated print(\"b == a+a\")",
"e": 4175,
"s": 3888,
"text": null
},
{
"code": null,
"e": 4192,
"s": 4175,
"text": "b==20 and c==30\n"
},
{
"code": null,
"e": 4489,
"s": 4192,
"text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4617,
"s": 4489,
"text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4628,
"s": 4617,
"text": "nidhi_biet"
},
{
"code": null,
"e": 4645,
"s": 4628,
"text": "punamsingh628700"
},
{
"code": null,
"e": 4661,
"s": 4645,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 4670,
"s": 4661,
"text": "dakra137"
},
{
"code": null,
"e": 4677,
"s": 4670,
"text": "Python"
}
] |
IntConsumer Interface in Java with Examples
|
09 Oct, 2018
The IntConsumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one int-valued argument but does not return any value.
The lambda expression assigned to an object of IntConsumer type is used to define its accept() which eventually applies the given operation on its only argument.It is similar to using an object of type Consumer<Integer>
The IntConsumer interface consists of the following two functions:
This method accepts one value and performs the operation on its only argument.
Syntax:
void accept(int value)
Parameters: This method takes in only one parameter:
value– the input argument
Returns: This method does not return any value.
Below is the code to illustrate accept() method:
import java.util.function.IntConsumer; public class GFG { public static void main(String args[]) { // Create a IntConsimer Instance IntConsumer display = a -> System.out.println(a * 10); // Using accept() method display.accept(3); }}
30
It returns a composed IntConsumer wherein the parameterized IntConsumer will be executed after the first one. If the evaluation of either operation throws an error, it is relayed to the caller of the composed operation.
Note: The operation being passed as the argument should be of type IntConsumer.
Syntax:
default IntConsumer andThen(IntConsumer after)
Parameters: This method accepts a parameter after which is the IntConsumer to be applied after the current one.
Return Value: This method returns a composed IntConsumer that first applies the current operation first and then the after operation.
Exception: This method throws NullPointerException if the after operation is null.
Below programs illustrate andThen() method:
Program 1:
import java.util.function.IntConsumer; public class GFG { public static void main(String args[]) { // Create a IntConsimer Instance IntConsumer display = a -> System.out.println(a * 10); IntConsumer mul = a -> a *= 10; // Using andThen() method IntConsumer composite = mul.andThen(display); composite.accept(3); }}
30
Program 2: To demonstrate when NullPointerException is returned.
import java.util.function.IntConsumer; public class GFG { public static void main(String args[]) { try { // Create a IntConsimer Instance IntConsumer mul = a -> a *= 10; IntConsumer composite = mul.andThen(null); composite.accept(3); } catch (Exception e) { System.out.println("Exception : " + e); } }}
Exception : java.lang.NullPointerException
Program 3: To demonstrate how an Exception in the after function is returned and handled.
import java.util.function.IntConsumer; public class GFG { public static void main(String args[]) { try { // Create a IntConsimer Instance IntConsumer divide = a -> a = a / (a - 3); IntConsumer mul = a -> a *= 10; IntConsumer composite = mul.andThen(divide); composite.accept(3); } catch (Exception e) { System.out.println("Exception : " + e); } }}
Exception : java.lang.ArithmeticException: / by zero
Java - util package
Java 8
java-basics
Java-Functional Programming
java-interfaces
Java
Java
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
Multidimensional Arrays in Java
Collections in Java
Set in Java
Initializing a List in Java
Singleton Class in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Oct, 2018"
},
{
"code": null,
"e": 278,
"s": 28,
"text": "The IntConsumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one int-valued argument but does not return any value."
},
{
"code": null,
"e": 498,
"s": 278,
"text": "The lambda expression assigned to an object of IntConsumer type is used to define its accept() which eventually applies the given operation on its only argument.It is similar to using an object of type Consumer<Integer>"
},
{
"code": null,
"e": 565,
"s": 498,
"text": "The IntConsumer interface consists of the following two functions:"
},
{
"code": null,
"e": 644,
"s": 565,
"text": "This method accepts one value and performs the operation on its only argument."
},
{
"code": null,
"e": 652,
"s": 644,
"text": "Syntax:"
},
{
"code": null,
"e": 675,
"s": 652,
"text": "void accept(int value)"
},
{
"code": null,
"e": 728,
"s": 675,
"text": "Parameters: This method takes in only one parameter:"
},
{
"code": null,
"e": 754,
"s": 728,
"text": "value– the input argument"
},
{
"code": null,
"e": 802,
"s": 754,
"text": "Returns: This method does not return any value."
},
{
"code": null,
"e": 851,
"s": 802,
"text": "Below is the code to illustrate accept() method:"
},
{
"code": "import java.util.function.IntConsumer; public class GFG { public static void main(String args[]) { // Create a IntConsimer Instance IntConsumer display = a -> System.out.println(a * 10); // Using accept() method display.accept(3); }}",
"e": 1127,
"s": 851,
"text": null
},
{
"code": null,
"e": 1131,
"s": 1127,
"text": "30\n"
},
{
"code": null,
"e": 1351,
"s": 1131,
"text": "It returns a composed IntConsumer wherein the parameterized IntConsumer will be executed after the first one. If the evaluation of either operation throws an error, it is relayed to the caller of the composed operation."
},
{
"code": null,
"e": 1431,
"s": 1351,
"text": "Note: The operation being passed as the argument should be of type IntConsumer."
},
{
"code": null,
"e": 1439,
"s": 1431,
"text": "Syntax:"
},
{
"code": null,
"e": 1486,
"s": 1439,
"text": "default IntConsumer andThen(IntConsumer after)"
},
{
"code": null,
"e": 1598,
"s": 1486,
"text": "Parameters: This method accepts a parameter after which is the IntConsumer to be applied after the current one."
},
{
"code": null,
"e": 1732,
"s": 1598,
"text": "Return Value: This method returns a composed IntConsumer that first applies the current operation first and then the after operation."
},
{
"code": null,
"e": 1815,
"s": 1732,
"text": "Exception: This method throws NullPointerException if the after operation is null."
},
{
"code": null,
"e": 1859,
"s": 1815,
"text": "Below programs illustrate andThen() method:"
},
{
"code": null,
"e": 1870,
"s": 1859,
"text": "Program 1:"
},
{
"code": "import java.util.function.IntConsumer; public class GFG { public static void main(String args[]) { // Create a IntConsimer Instance IntConsumer display = a -> System.out.println(a * 10); IntConsumer mul = a -> a *= 10; // Using andThen() method IntConsumer composite = mul.andThen(display); composite.accept(3); }}",
"e": 2241,
"s": 1870,
"text": null
},
{
"code": null,
"e": 2245,
"s": 2241,
"text": "30\n"
},
{
"code": null,
"e": 2310,
"s": 2245,
"text": "Program 2: To demonstrate when NullPointerException is returned."
},
{
"code": "import java.util.function.IntConsumer; public class GFG { public static void main(String args[]) { try { // Create a IntConsimer Instance IntConsumer mul = a -> a *= 10; IntConsumer composite = mul.andThen(null); composite.accept(3); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}",
"e": 2710,
"s": 2310,
"text": null
},
{
"code": null,
"e": 2754,
"s": 2710,
"text": "Exception : java.lang.NullPointerException\n"
},
{
"code": null,
"e": 2844,
"s": 2754,
"text": "Program 3: To demonstrate how an Exception in the after function is returned and handled."
},
{
"code": "import java.util.function.IntConsumer; public class GFG { public static void main(String args[]) { try { // Create a IntConsimer Instance IntConsumer divide = a -> a = a / (a - 3); IntConsumer mul = a -> a *= 10; IntConsumer composite = mul.andThen(divide); composite.accept(3); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}",
"e": 3300,
"s": 2844,
"text": null
},
{
"code": null,
"e": 3354,
"s": 3300,
"text": "Exception : java.lang.ArithmeticException: / by zero\n"
},
{
"code": null,
"e": 3374,
"s": 3354,
"text": "Java - util package"
},
{
"code": null,
"e": 3381,
"s": 3374,
"text": "Java 8"
},
{
"code": null,
"e": 3393,
"s": 3381,
"text": "java-basics"
},
{
"code": null,
"e": 3421,
"s": 3393,
"text": "Java-Functional Programming"
},
{
"code": null,
"e": 3437,
"s": 3421,
"text": "java-interfaces"
},
{
"code": null,
"e": 3442,
"s": 3437,
"text": "Java"
},
{
"code": null,
"e": 3447,
"s": 3442,
"text": "Java"
},
{
"code": null,
"e": 3545,
"s": 3447,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3596,
"s": 3545,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3627,
"s": 3596,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3646,
"s": 3627,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3676,
"s": 3646,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3694,
"s": 3676,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3726,
"s": 3694,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3746,
"s": 3726,
"text": "Collections in Java"
},
{
"code": null,
"e": 3758,
"s": 3746,
"text": "Set in Java"
},
{
"code": null,
"e": 3786,
"s": 3758,
"text": "Initializing a List in Java"
}
] |
How to Control Laptop Screen Brightness using Python?
|
17 Aug, 2021
To control the brightness of the screen we are using the screen-brightness-control library. The screen-brightness-control library has only one class and few functions. The most useful functions are mentioned below:
get_brightness()set_brightness()fade_brightness()list_monitors()
get_brightness()
set_brightness()
fade_brightness()
list_monitors()
Installation: We can install the package by running the following pip command:
pip install screen-brightness-control
Example 1: How to Get Screen Brightness
The get_brightness() method returns the current brightness level.
Syntax: get_brightness(display=None, method=None, verbose_error=False)
Parameters:
display -: the specific display you wish to adjust. This can be the name, model, serial or index of the display
method -: the OS specific method to use. On Windows this can be “wmi” (for laptop displays) or “vcp” (for desktop monitors). On Linux this can be “light”, “xrandr”, “ddcutil” or “xbacklight”.
verbose_error -: a boolean value to control how much detail any error messages should contain
Returns: Current brightness level
Python3
# importing the moduleimport screen_brightness_control as sbc # get current brightness valuecurrent_brightness = sbc.get_brightness()print(current_brightness) # get the brightness of the primary displayprimary_brightness = sbc.get_brightness(display=0)print(primary_brightness)
Output: Suppose the brightness was this:
Then the output will be:
50
50
The output can be a list or an integer depending on the number of detected monitors.
Example 2: How to Set Screen Brightness
The set_brightness() method changes the brightness of the screen.
Syntax: set_brightness(value, display=None, method=None, force=False, verbose_error=False, no_return=False)
Parameters:
value: the level to set the brightness to. Can either be an integer or a string.
display: the specific display you wish to adjust. This can be the name, model, serial or index of the display
method: the OS specific method to use. On Windows this can be “wmi” (for laptop displays) or “vcp” (for desktop monitors). On Linux this can be “light”, “xrandr”, “ddcutil” or “xbacklight”.
force (Linux only): If set to False then the brightness is never set to less than 1 because on Linux this often turns the screen off. If set to True then it will bypass this check
verbose_error: A boolean value to control how much detail any error messages should contain
no_return: if False, this function will return what the brightness was set to. If True, this function returns nothing, which is slightly quicker
Python3
# importing the moduleimport screen_brightness_control as sbc # get current brightness valueprint(sbc.get_brightness()) #set brightness to 50%sbc.set_brightness(50) print(sbc.get_brightness()) #set the brightness of the primary display to 75%sbc.set_brightness(75, display=0) print(sbc.get_brightness())
Output:
100
50
75
The output can be a list or an integer depending on the number of detected monitors.
Example 3: How to Fade the Brightness
The fade_brightness() method gently fades the brightness to a value.
Syntax: fade_brightness(finish, start=None, interval=0.01, increment=1, blocking=True)
Parameters:
finish: The brightness value to fade to
start: The value to start from. If not specified it defaults to the current brightness
interval: The time interval between each step in brightness
increment: The amount to change the brightness by each step
blocking: If set to False it fades the brightness in a new thread
Python3
# importing the moduleimport screen_brightness_control as sbc # get current brightness valueprint(sbc.get_brightness()) # fade brightness from the current brightness to 50%sbc.fade_brightness(50)print(sbc.get_brightness()) # fade the brightness from 25% to 75%sbc.fade_brightness(75, start = 25)print(sbc.get_brightness()) # fade the brightness from the current# value to 100% in steps of 10%sbc.fade_brightness(100, increment = 10)print(sbc.get_brightness())
Output:
75
50
75
100
Example 4: How to list available monitors
The list_monitors() method returns a list the names of all detected monitors
Syntax: list_monitors(method=None)
Parameters:
method: the OS specific method to use. On Windows this can be “wmi” (for laptop displays) or “vcp” (for desktop monitors). On Linux this can be “light”, “xrandr”, “ddcutil” or “xbacklight”.
Python3
# import the libraryimport screen_brightness_control as sbc # get the monitor namesmonitors = sbc.list_monitors()print(monitors) # now use this to adjust specific screens by namesbc.set_brightness(25, display=monitors[0])
Output:
["BenQ GL2450H", "Dell U2211H"]
The names and quantity of monitors will vary depending on what is plugged into your computer.
captaincrozzers
rajeev0719singh
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Aug, 2021"
},
{
"code": null,
"e": 269,
"s": 54,
"text": "To control the brightness of the screen we are using the screen-brightness-control library. The screen-brightness-control library has only one class and few functions. The most useful functions are mentioned below:"
},
{
"code": null,
"e": 334,
"s": 269,
"text": "get_brightness()set_brightness()fade_brightness()list_monitors()"
},
{
"code": null,
"e": 351,
"s": 334,
"text": "get_brightness()"
},
{
"code": null,
"e": 368,
"s": 351,
"text": "set_brightness()"
},
{
"code": null,
"e": 386,
"s": 368,
"text": "fade_brightness()"
},
{
"code": null,
"e": 402,
"s": 386,
"text": "list_monitors()"
},
{
"code": null,
"e": 481,
"s": 402,
"text": "Installation: We can install the package by running the following pip command:"
},
{
"code": null,
"e": 519,
"s": 481,
"text": "pip install screen-brightness-control"
},
{
"code": null,
"e": 559,
"s": 519,
"text": "Example 1: How to Get Screen Brightness"
},
{
"code": null,
"e": 625,
"s": 559,
"text": "The get_brightness() method returns the current brightness level."
},
{
"code": null,
"e": 696,
"s": 625,
"text": "Syntax: get_brightness(display=None, method=None, verbose_error=False)"
},
{
"code": null,
"e": 708,
"s": 696,
"text": "Parameters:"
},
{
"code": null,
"e": 820,
"s": 708,
"text": "display -: the specific display you wish to adjust. This can be the name, model, serial or index of the display"
},
{
"code": null,
"e": 1012,
"s": 820,
"text": "method -: the OS specific method to use. On Windows this can be “wmi” (for laptop displays) or “vcp” (for desktop monitors). On Linux this can be “light”, “xrandr”, “ddcutil” or “xbacklight”."
},
{
"code": null,
"e": 1106,
"s": 1012,
"text": "verbose_error -: a boolean value to control how much detail any error messages should contain"
},
{
"code": null,
"e": 1140,
"s": 1106,
"text": "Returns: Current brightness level"
},
{
"code": null,
"e": 1148,
"s": 1140,
"text": "Python3"
},
{
"code": "# importing the moduleimport screen_brightness_control as sbc # get current brightness valuecurrent_brightness = sbc.get_brightness()print(current_brightness) # get the brightness of the primary displayprimary_brightness = sbc.get_brightness(display=0)print(primary_brightness)",
"e": 1427,
"s": 1148,
"text": null
},
{
"code": null,
"e": 1471,
"s": 1430,
"text": "Output: Suppose the brightness was this:"
},
{
"code": null,
"e": 1497,
"s": 1471,
"text": "Then the output will be: "
},
{
"code": null,
"e": 1503,
"s": 1497,
"text": "50\n50"
},
{
"code": null,
"e": 1589,
"s": 1503,
"text": "The output can be a list or an integer depending on the number of detected monitors. "
},
{
"code": null,
"e": 1629,
"s": 1589,
"text": "Example 2: How to Set Screen Brightness"
},
{
"code": null,
"e": 1695,
"s": 1629,
"text": "The set_brightness() method changes the brightness of the screen."
},
{
"code": null,
"e": 1803,
"s": 1695,
"text": "Syntax: set_brightness(value, display=None, method=None, force=False, verbose_error=False, no_return=False)"
},
{
"code": null,
"e": 1815,
"s": 1803,
"text": "Parameters:"
},
{
"code": null,
"e": 1896,
"s": 1815,
"text": "value: the level to set the brightness to. Can either be an integer or a string."
},
{
"code": null,
"e": 2007,
"s": 1896,
"text": "display: the specific display you wish to adjust. This can be the name, model, serial or index of the display"
},
{
"code": null,
"e": 2198,
"s": 2007,
"text": "method: the OS specific method to use. On Windows this can be “wmi” (for laptop displays) or “vcp” (for desktop monitors). On Linux this can be “light”, “xrandr”, “ddcutil” or “xbacklight”."
},
{
"code": null,
"e": 2378,
"s": 2198,
"text": "force (Linux only): If set to False then the brightness is never set to less than 1 because on Linux this often turns the screen off. If set to True then it will bypass this check"
},
{
"code": null,
"e": 2470,
"s": 2378,
"text": "verbose_error: A boolean value to control how much detail any error messages should contain"
},
{
"code": null,
"e": 2615,
"s": 2470,
"text": "no_return: if False, this function will return what the brightness was set to. If True, this function returns nothing, which is slightly quicker"
},
{
"code": null,
"e": 2623,
"s": 2615,
"text": "Python3"
},
{
"code": "# importing the moduleimport screen_brightness_control as sbc # get current brightness valueprint(sbc.get_brightness()) #set brightness to 50%sbc.set_brightness(50) print(sbc.get_brightness()) #set the brightness of the primary display to 75%sbc.set_brightness(75, display=0) print(sbc.get_brightness())",
"e": 2927,
"s": 2623,
"text": null
},
{
"code": null,
"e": 2939,
"s": 2927,
"text": " Output:"
},
{
"code": null,
"e": 2949,
"s": 2939,
"text": "100\n50\n75"
},
{
"code": null,
"e": 3035,
"s": 2949,
"text": "The output can be a list or an integer depending on the number of detected monitors. "
},
{
"code": null,
"e": 3075,
"s": 3035,
"text": " Example 3: How to Fade the Brightness"
},
{
"code": null,
"e": 3144,
"s": 3075,
"text": "The fade_brightness() method gently fades the brightness to a value."
},
{
"code": null,
"e": 3231,
"s": 3144,
"text": "Syntax: fade_brightness(finish, start=None, interval=0.01, increment=1, blocking=True)"
},
{
"code": null,
"e": 3243,
"s": 3231,
"text": "Parameters:"
},
{
"code": null,
"e": 3283,
"s": 3243,
"text": "finish: The brightness value to fade to"
},
{
"code": null,
"e": 3370,
"s": 3283,
"text": "start: The value to start from. If not specified it defaults to the current brightness"
},
{
"code": null,
"e": 3430,
"s": 3370,
"text": "interval: The time interval between each step in brightness"
},
{
"code": null,
"e": 3490,
"s": 3430,
"text": "increment: The amount to change the brightness by each step"
},
{
"code": null,
"e": 3556,
"s": 3490,
"text": "blocking: If set to False it fades the brightness in a new thread"
},
{
"code": null,
"e": 3564,
"s": 3556,
"text": "Python3"
},
{
"code": "# importing the moduleimport screen_brightness_control as sbc # get current brightness valueprint(sbc.get_brightness()) # fade brightness from the current brightness to 50%sbc.fade_brightness(50)print(sbc.get_brightness()) # fade the brightness from 25% to 75%sbc.fade_brightness(75, start = 25)print(sbc.get_brightness()) # fade the brightness from the current# value to 100% in steps of 10%sbc.fade_brightness(100, increment = 10)print(sbc.get_brightness())",
"e": 4024,
"s": 3564,
"text": null
},
{
"code": null,
"e": 4033,
"s": 4024,
"text": " Output:"
},
{
"code": null,
"e": 4046,
"s": 4033,
"text": "75\n50\n75\n100"
},
{
"code": null,
"e": 4089,
"s": 4046,
"text": " Example 4: How to list available monitors"
},
{
"code": null,
"e": 4166,
"s": 4089,
"text": "The list_monitors() method returns a list the names of all detected monitors"
},
{
"code": null,
"e": 4201,
"s": 4166,
"text": "Syntax: list_monitors(method=None)"
},
{
"code": null,
"e": 4213,
"s": 4201,
"text": "Parameters:"
},
{
"code": null,
"e": 4403,
"s": 4213,
"text": "method: the OS specific method to use. On Windows this can be “wmi” (for laptop displays) or “vcp” (for desktop monitors). On Linux this can be “light”, “xrandr”, “ddcutil” or “xbacklight”."
},
{
"code": null,
"e": 4411,
"s": 4403,
"text": "Python3"
},
{
"code": "# import the libraryimport screen_brightness_control as sbc # get the monitor namesmonitors = sbc.list_monitors()print(monitors) # now use this to adjust specific screens by namesbc.set_brightness(25, display=monitors[0])",
"e": 4633,
"s": 4411,
"text": null
},
{
"code": null,
"e": 4641,
"s": 4633,
"text": "Output:"
},
{
"code": null,
"e": 4673,
"s": 4641,
"text": "[\"BenQ GL2450H\", \"Dell U2211H\"]"
},
{
"code": null,
"e": 4767,
"s": 4673,
"text": "The names and quantity of monitors will vary depending on what is plugged into your computer."
},
{
"code": null,
"e": 4783,
"s": 4767,
"text": "captaincrozzers"
},
{
"code": null,
"e": 4799,
"s": 4783,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 4814,
"s": 4799,
"text": "python-utility"
},
{
"code": null,
"e": 4821,
"s": 4814,
"text": "Python"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.