title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Python – Rearrange dictionary for consecutive value-keys
|
10 Sep, 2021
Sometimes, while working with Python dictionaries, we can have a problem in which we need to rearrange dictionary keys so as a value is followed by same key in dictionary. This problem can have application in competitive programming algorithms and Graph problems. Let’s discuss certain ways in which this task can be performed.
Input : test_dict = {1 : 2, 3 : 2, 2 : 3} Output : {1: 2, 2: 3, 3: 2}Input : test_dict = {1 : 2} Output : {1 : 2}
Method #1 : Using loop + keys() The combination of above functions can be used to solve this problem. In this, we extract the dictionary keys using keys() and iterate till we find value succeeded by equal key.
Python3
# Python3 code to demonstrate working of# Rearrange dictionary for consecutive value-keys# Using loop + keys() # initializing dictionarytest_dict = {1 : 3, 4 : 5, 3 : 4, 5 : 6} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Rearrange dictionary for consecutive value-keys# Using loop + keys()temp = list(test_dict.keys())[0]res = {}while len(test_dict) > len(res): res[temp] = temp = test_dict[temp] # printing resultprint("The rearranged dictionary : " + str(res))
The original dictionary : {1: 3, 4: 5, 3: 4, 5: 6}
The rearranged dictionary : {1: 3, 3: 4, 4: 5, 5: 6}
Method #2 : Using dictionary comprehension + accumulate() The combination of above functions can be used to solve this problem. In this, we perform the task fo pairing using accumulate and rearrange new dictionary using dictionary comprehension.
Python3
# Python3 code to demonstrate working of# Rearrange dictionary for consecutive value-keys# Using dictionary comprehension + accumulate()from itertools import accumulate # initializing dictionarytest_dict = {1 : 3, 4 : 5, 3 : 4, 5 : 6} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Rearrange dictionary for consecutive value-keys# Using dictionary comprehension + accumulate()res = {key : test_dict[key] for key in accumulate(test_dict, lambda key, x :test_dict[key])} # printing resultprint("The rearranged dictionary : " + str(res))
The original dictionary : {1: 3, 4: 5, 3: 4, 5: 6}
The rearranged dictionary : {1: 3, 3: 4, 4: 5, 5: 6}
adnanirshad158
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Sep, 2021"
},
{
"code": null,
"e": 357,
"s": 28,
"text": "Sometimes, while working with Python dictionaries, we can have a problem in which we need to rearrange dictionary keys so as a value is followed by same key in dictionary. This problem can have application in competitive programming algorithms and Graph problems. Let’s discuss certain ways in which this task can be performed. "
},
{
"code": null,
"e": 473,
"s": 357,
"text": "Input : test_dict = {1 : 2, 3 : 2, 2 : 3} Output : {1: 2, 2: 3, 3: 2}Input : test_dict = {1 : 2} Output : {1 : 2} "
},
{
"code": null,
"e": 684,
"s": 473,
"text": "Method #1 : Using loop + keys() The combination of above functions can be used to solve this problem. In this, we extract the dictionary keys using keys() and iterate till we find value succeeded by equal key. "
},
{
"code": null,
"e": 692,
"s": 684,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Rearrange dictionary for consecutive value-keys# Using loop + keys() # initializing dictionarytest_dict = {1 : 3, 4 : 5, 3 : 4, 5 : 6} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Rearrange dictionary for consecutive value-keys# Using loop + keys()temp = list(test_dict.keys())[0]res = {}while len(test_dict) > len(res): res[temp] = temp = test_dict[temp] # printing resultprint(\"The rearranged dictionary : \" + str(res))",
"e": 1199,
"s": 692,
"text": null
},
{
"code": null,
"e": 1303,
"s": 1199,
"text": "The original dictionary : {1: 3, 4: 5, 3: 4, 5: 6}\nThe rearranged dictionary : {1: 3, 3: 4, 4: 5, 5: 6}"
},
{
"code": null,
"e": 1553,
"s": 1305,
"text": " Method #2 : Using dictionary comprehension + accumulate() The combination of above functions can be used to solve this problem. In this, we perform the task fo pairing using accumulate and rearrange new dictionary using dictionary comprehension. "
},
{
"code": null,
"e": 1561,
"s": 1553,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Rearrange dictionary for consecutive value-keys# Using dictionary comprehension + accumulate()from itertools import accumulate # initializing dictionarytest_dict = {1 : 3, 4 : 5, 3 : 4, 5 : 6} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Rearrange dictionary for consecutive value-keys# Using dictionary comprehension + accumulate()res = {key : test_dict[key] for key in accumulate(test_dict, lambda key, x :test_dict[key])} # printing resultprint(\"The rearranged dictionary : \" + str(res))",
"e": 2163,
"s": 1561,
"text": null
},
{
"code": null,
"e": 2267,
"s": 2163,
"text": "The original dictionary : {1: 3, 4: 5, 3: 4, 5: 6}\nThe rearranged dictionary : {1: 3, 3: 4, 4: 5, 5: 6}"
},
{
"code": null,
"e": 2284,
"s": 2269,
"text": "adnanirshad158"
},
{
"code": null,
"e": 2311,
"s": 2284,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2318,
"s": 2311,
"text": "Python"
},
{
"code": null,
"e": 2334,
"s": 2318,
"text": "Python Programs"
}
] |
Pattern pattern() method in Java with Examples
|
30 Jul, 2019
The pattern() method of the Pattern class in Java is used to get the regular expression which is compiled to create this pattern. We use a regular expression to create the pattern and this method used to get the same source expression.
Syntax:
public String pattern()
Parameters: This method does not accepts anything as parameter.
Return Value: This method returns the pattern’s source regular expression.
Below programs illustrate the pattern() method:Program 1:
// Java program to demonstrate// Pattern.pattern() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // create a REGEX String String REGEX = "(.*)(for)(.*)?"; // create the string // in which you want to search String actualString = "code of Machine"; // create pattern Pattern pattern1 = Pattern.compile(REGEX); // find the regular expressio of pattern String RegularExpression = pattern1.pattern(); System.out.println("Pattern's RegularExpression = " + RegularExpression); }}
Pattern's RegularExpression = (.*)(for)(.*)?
Program 2:
// Java program to demonstrate// Pattern.compile method import java.util.regex.*; public class GFG { public static void main(String[] args) { // create a REGEX String String REGEX = "(.*)(ee)(.*)?"; // create the string // in which you want to search String actualString = "geeks"; // create pattern Pattern pattern1 = Pattern.compile(REGEX); // find the regular expressio of pattern String RegularExpression = pattern1.pattern(); System.out.println("Pattern's RegularExpression = " + RegularExpression); }}
Pattern's RegularExpression = (.*)(ee)(.*)?
References:https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#pattern()
Akanksha_Rai
Java 8
Java-Functions
Java-Pattern
Java
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
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jul, 2019"
},
{
"code": null,
"e": 264,
"s": 28,
"text": "The pattern() method of the Pattern class in Java is used to get the regular expression which is compiled to create this pattern. We use a regular expression to create the pattern and this method used to get the same source expression."
},
{
"code": null,
"e": 272,
"s": 264,
"text": "Syntax:"
},
{
"code": null,
"e": 297,
"s": 272,
"text": "public String pattern()\n"
},
{
"code": null,
"e": 361,
"s": 297,
"text": "Parameters: This method does not accepts anything as parameter."
},
{
"code": null,
"e": 436,
"s": 361,
"text": "Return Value: This method returns the pattern’s source regular expression."
},
{
"code": null,
"e": 494,
"s": 436,
"text": "Below programs illustrate the pattern() method:Program 1:"
},
{
"code": "// Java program to demonstrate// Pattern.pattern() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // create a REGEX String String REGEX = \"(.*)(for)(.*)?\"; // create the string // in which you want to search String actualString = \"code of Machine\"; // create pattern Pattern pattern1 = Pattern.compile(REGEX); // find the regular expressio of pattern String RegularExpression = pattern1.pattern(); System.out.println(\"Pattern's RegularExpression = \" + RegularExpression); }}",
"e": 1143,
"s": 494,
"text": null
},
{
"code": null,
"e": 1189,
"s": 1143,
"text": "Pattern's RegularExpression = (.*)(for)(.*)?\n"
},
{
"code": null,
"e": 1200,
"s": 1189,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// Pattern.compile method import java.util.regex.*; public class GFG { public static void main(String[] args) { // create a REGEX String String REGEX = \"(.*)(ee)(.*)?\"; // create the string // in which you want to search String actualString = \"geeks\"; // create pattern Pattern pattern1 = Pattern.compile(REGEX); // find the regular expressio of pattern String RegularExpression = pattern1.pattern(); System.out.println(\"Pattern's RegularExpression = \" + RegularExpression); }}",
"e": 1836,
"s": 1200,
"text": null
},
{
"code": null,
"e": 1881,
"s": 1836,
"text": "Pattern's RegularExpression = (.*)(ee)(.*)?\n"
},
{
"code": null,
"e": 1974,
"s": 1881,
"text": "References:https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#pattern()"
},
{
"code": null,
"e": 1987,
"s": 1974,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 1994,
"s": 1987,
"text": "Java 8"
},
{
"code": null,
"e": 2009,
"s": 1994,
"text": "Java-Functions"
},
{
"code": null,
"e": 2022,
"s": 2009,
"text": "Java-Pattern"
},
{
"code": null,
"e": 2027,
"s": 2022,
"text": "Java"
},
{
"code": null,
"e": 2032,
"s": 2027,
"text": "Java"
},
{
"code": null,
"e": 2130,
"s": 2032,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2145,
"s": 2130,
"text": "Stream In Java"
},
{
"code": null,
"e": 2166,
"s": 2145,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2187,
"s": 2166,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2206,
"s": 2187,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 2223,
"s": 2206,
"text": "Generics in Java"
},
{
"code": null,
"e": 2253,
"s": 2223,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 2279,
"s": 2253,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2295,
"s": 2279,
"text": "Strings in Java"
},
{
"code": null,
"e": 2332,
"s": 2295,
"text": "Differences between JDK, JRE and JVM"
}
] |
LocalDate getDayOfWeek() method in Java
|
28 Nov, 2018
The getDayOfWeek() method of LocalDate class in Java gets the day-of-week field, which is an enum DayOfWeek.
Syntax:
public DayOfWeek getDayOfWeek()
Parameter: This method does not accepts any parameter.
Return Value: The function returns the day of the week and not null.
Below programs illustrate the getDayOfWeek() method of LocalDate in Java:
Program 1:
// Program to illustrate the getDayOfWeek() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDate dt = LocalDate.parse("2018-11-27"); // Prints the day System.out.println(dt.getDayOfWeek()); }}
TUESDAY
Program 2:
// Program to illustrate the getDayOfWeek() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDate dt = LocalDate.parse("2018-01-09"); // Prints the day System.out.println(dt.getDayOfWeek()); }}
TUESDAY
Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#getDayOfWeek()
Java-Functions
Java-LocalDate
Java-time package
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
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2018"
},
{
"code": null,
"e": 137,
"s": 28,
"text": "The getDayOfWeek() method of LocalDate class in Java gets the day-of-week field, which is an enum DayOfWeek."
},
{
"code": null,
"e": 145,
"s": 137,
"text": "Syntax:"
},
{
"code": null,
"e": 178,
"s": 145,
"text": "public DayOfWeek getDayOfWeek()\n"
},
{
"code": null,
"e": 233,
"s": 178,
"text": "Parameter: This method does not accepts any parameter."
},
{
"code": null,
"e": 302,
"s": 233,
"text": "Return Value: The function returns the day of the week and not null."
},
{
"code": null,
"e": 376,
"s": 302,
"text": "Below programs illustrate the getDayOfWeek() method of LocalDate in Java:"
},
{
"code": null,
"e": 387,
"s": 376,
"text": "Program 1:"
},
{
"code": "// Program to illustrate the getDayOfWeek() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDate dt = LocalDate.parse(\"2018-11-27\"); // Prints the day System.out.println(dt.getDayOfWeek()); }}",
"e": 703,
"s": 387,
"text": null
},
{
"code": null,
"e": 712,
"s": 703,
"text": "TUESDAY\n"
},
{
"code": null,
"e": 723,
"s": 712,
"text": "Program 2:"
},
{
"code": "// Program to illustrate the getDayOfWeek() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDate dt = LocalDate.parse(\"2018-01-09\"); // Prints the day System.out.println(dt.getDayOfWeek()); }}",
"e": 1039,
"s": 723,
"text": null
},
{
"code": null,
"e": 1048,
"s": 1039,
"text": "TUESDAY\n"
},
{
"code": null,
"e": 1142,
"s": 1048,
"text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#getDayOfWeek()"
},
{
"code": null,
"e": 1157,
"s": 1142,
"text": "Java-Functions"
},
{
"code": null,
"e": 1172,
"s": 1157,
"text": "Java-LocalDate"
},
{
"code": null,
"e": 1190,
"s": 1172,
"text": "Java-time package"
},
{
"code": null,
"e": 1195,
"s": 1190,
"text": "Java"
},
{
"code": null,
"e": 1200,
"s": 1195,
"text": "Java"
},
{
"code": null,
"e": 1298,
"s": 1200,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1349,
"s": 1298,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 1380,
"s": 1349,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 1399,
"s": 1380,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 1429,
"s": 1399,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 1447,
"s": 1429,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 1467,
"s": 1447,
"text": "Collections in Java"
},
{
"code": null,
"e": 1482,
"s": 1467,
"text": "Stream In Java"
},
{
"code": null,
"e": 1514,
"s": 1482,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 1538,
"s": 1514,
"text": "Singleton Class in Java"
}
] |
p5.js | Enqueue Operation in Queue
|
04 Oct, 2021
What is Queue? A Queue is a linear structure which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. It takes constant time to add or remove an element in a queue.
Queues should be used over arrays when we need to work with data in the FIFO form. Limitation of Queue: It can access only one element at a time.
In JavaScript, arrays have methods like pop and shift that defines the Queue class: Enqueue and Dequeue operations. With this, a queue can be easily implemented.Basic skeleton of queue: Below example run using “$node skeleton.js” command to get basic queue skeleton.
javascript
// Define Queue functionfunction Queue(array) { this.array = []; if (array) this.array = array;} // Add Get Buffer property to object// constructor which slices the arrayQueue.prototype.getBuffer = function() { return this.array.slice();} // Add isEmpty properties to object constructor// which returns the length of the arrayQueue.prototype.isEmpty = function() { return this.array.length == 0;} // Instance of the Queue classvar queue1 = new Queue(); //Queue { array: [] } console.log(queue1);
Example:
javascript
<!DOCTYPE html><html> <head> <title>Enqueue Operation</title> <meta charset="UTF-8"> <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js" type="text/javascript"></script> <style> body { padding: 0; margin: 0; } canvas { vertical-align: top; } </style></head> <body> <script> // Define Queue function function Queue(array) { this.array = []; if (array) this.array = array; } // Add Get Buffer property to object // constructor which slices the array Queue.prototype.getBuffer = function() { return this.array.slice(); } // Add isEmpty properties to object constructor // which returns the length of the array Queue.prototype.isEmpty = function() { return this.array.length == 0; } // Instance of the Queue class var queue1 = new Queue(); // Queue { array: [] } console.log(queue1); // Add Push property to object constructor // which push elements to the array Queue.prototype.enqueue = function(value) { this.array.push(value); } function setup() { // Create Canvas of size display width * 300 createCanvas(displayWidth, 300); } function draw() { // Set background color background("grey"); // Set stroke weight strokeWeight(3); textAlign(CENTER); textSize(24); text("Queue Implementation Using P5.js", windowWidth/2, 20); textAlign(LEFT); textSize(14); // Set stroke color stroke('green'); line(10, 45, 90, 45); rect(10, 30, 60, 30); noStroke(); text("FRONT", 20, 50); // Display queue for(var i = 0; i <= queue1['array'].length-1; i++) { var p = 10; translate(70, 0); strokeWeight(3); stroke('green'); line(10+p, 45, p+80, 45); rect(10+p, 30, 40+p, 30); noStroke(); text(queue1['array'][i], 40, 50); p += 10; } // Set stroke color stroke('green'); translate(70, 0); rect(10, 30, 60, 30); noStroke(); text("REAR", 20, 50); } // Peek Function Queue.prototype.peek = function() { return this.array[this.array.length-1]; } // Driver Code // Call to Enqueue operation queue1.enqueue(1); queue1.enqueue(2); queue1.enqueue(3); queue1.enqueue(19); queue1.enqueue(11); queue1.enqueue(15); queue1.enqueue(14); queue1.enqueue(18); </script></body> </html>
Output:
After Enqueuing ’25’ by calling queue1.enqueue(25) function of rear changes to 25.
anikaseth98
JavaScript-p5.js
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 369,
"s": 28,
"text": "What is Queue? A Queue is a linear structure which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. It takes constant time to add or remove an element in a queue. "
},
{
"code": null,
"e": 516,
"s": 369,
"text": "Queues should be used over arrays when we need to work with data in the FIFO form. Limitation of Queue: It can access only one element at a time. "
},
{
"code": null,
"e": 785,
"s": 516,
"text": "In JavaScript, arrays have methods like pop and shift that defines the Queue class: Enqueue and Dequeue operations. With this, a queue can be easily implemented.Basic skeleton of queue: Below example run using “$node skeleton.js” command to get basic queue skeleton. "
},
{
"code": null,
"e": 796,
"s": 785,
"text": "javascript"
},
{
"code": "// Define Queue functionfunction Queue(array) { this.array = []; if (array) this.array = array;} // Add Get Buffer property to object// constructor which slices the arrayQueue.prototype.getBuffer = function() { return this.array.slice();} // Add isEmpty properties to object constructor// which returns the length of the arrayQueue.prototype.isEmpty = function() { return this.array.length == 0;} // Instance of the Queue classvar queue1 = new Queue(); //Queue { array: [] } console.log(queue1);",
"e": 1304,
"s": 796,
"text": null
},
{
"code": null,
"e": 1315,
"s": 1304,
"text": "Example: "
},
{
"code": null,
"e": 1326,
"s": 1315,
"text": "javascript"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Enqueue Operation</title> <meta charset=\"UTF-8\"> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js\" type=\"text/javascript\"></script> <style> body { padding: 0; margin: 0; } canvas { vertical-align: top; } </style></head> <body> <script> // Define Queue function function Queue(array) { this.array = []; if (array) this.array = array; } // Add Get Buffer property to object // constructor which slices the array Queue.prototype.getBuffer = function() { return this.array.slice(); } // Add isEmpty properties to object constructor // which returns the length of the array Queue.prototype.isEmpty = function() { return this.array.length == 0; } // Instance of the Queue class var queue1 = new Queue(); // Queue { array: [] } console.log(queue1); // Add Push property to object constructor // which push elements to the array Queue.prototype.enqueue = function(value) { this.array.push(value); } function setup() { // Create Canvas of size display width * 300 createCanvas(displayWidth, 300); } function draw() { // Set background color background(\"grey\"); // Set stroke weight strokeWeight(3); textAlign(CENTER); textSize(24); text(\"Queue Implementation Using P5.js\", windowWidth/2, 20); textAlign(LEFT); textSize(14); // Set stroke color stroke('green'); line(10, 45, 90, 45); rect(10, 30, 60, 30); noStroke(); text(\"FRONT\", 20, 50); // Display queue for(var i = 0; i <= queue1['array'].length-1; i++) { var p = 10; translate(70, 0); strokeWeight(3); stroke('green'); line(10+p, 45, p+80, 45); rect(10+p, 30, 40+p, 30); noStroke(); text(queue1['array'][i], 40, 50); p += 10; } // Set stroke color stroke('green'); translate(70, 0); rect(10, 30, 60, 30); noStroke(); text(\"REAR\", 20, 50); } // Peek Function Queue.prototype.peek = function() { return this.array[this.array.length-1]; } // Driver Code // Call to Enqueue operation queue1.enqueue(1); queue1.enqueue(2); queue1.enqueue(3); queue1.enqueue(19); queue1.enqueue(11); queue1.enqueue(15); queue1.enqueue(14); queue1.enqueue(18); </script></body> </html> ",
"e": 4441,
"s": 1326,
"text": null
},
{
"code": null,
"e": 4451,
"s": 4441,
"text": "Output: "
},
{
"code": null,
"e": 4536,
"s": 4451,
"text": "After Enqueuing ’25’ by calling queue1.enqueue(25) function of rear changes to 25. "
},
{
"code": null,
"e": 4550,
"s": 4538,
"text": "anikaseth98"
},
{
"code": null,
"e": 4567,
"s": 4550,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 4578,
"s": 4567,
"text": "JavaScript"
},
{
"code": null,
"e": 4595,
"s": 4578,
"text": "Web Technologies"
},
{
"code": null,
"e": 4693,
"s": 4595,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4754,
"s": 4693,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4826,
"s": 4754,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 4866,
"s": 4826,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4907,
"s": 4866,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4953,
"s": 4907,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 4986,
"s": 4953,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5048,
"s": 4986,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5109,
"s": 5048,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5159,
"s": 5109,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Top Down Integration Testing
|
Top-down integration testing is an integration testing technique used in order to simulate the behaviour of the lower-level modules that are not yet integrated. Stubs are the modules that act as temporary replacement for a called module and give the same output as that of the actual product.
The replacement for the 'called' modules is known as 'Stubs' and is also used when the software needs to interact with an external system.
The above diagrams clearly states that Modules 1, 2 and 3 are available for integration, whereas, below modules are still under development that cannot be integrated at this point of time. Hence, Stubs are used to test the modules. The order of Integration will be:
1,2
1,3
2,Stub 1
2,Stub 2
3,Stub 3
3,Stub 4
+ Firstly, the integration between the modules 1,2 and 3
+ Test the integration between the module 2 and stub 1,stub 2
+ Test the integration between the module 3 and stub 3,stub 4
|
[
{
"code": null,
"e": 6172,
"s": 5879,
"text": "Top-down integration testing is an integration testing technique used in order to simulate the behaviour of the lower-level modules that are not yet integrated. Stubs are the modules that act as temporary replacement for a called module and give the same output as that of the actual product."
},
{
"code": null,
"e": 6311,
"s": 6172,
"text": "The replacement for the 'called' modules is known as 'Stubs' and is also used when the software needs to interact with an external system."
},
{
"code": null,
"e": 6577,
"s": 6311,
"text": "The above diagrams clearly states that Modules 1, 2 and 3 are available for integration, whereas, below modules are still under development that cannot be integrated at this point of time. Hence, Stubs are used to test the modules. The order of Integration will be:"
},
{
"code": null,
"e": 6621,
"s": 6577,
"text": "1,2\n1,3\n2,Stub 1\n2,Stub 2\n3,Stub 3\n3,Stub 4"
}
] |
Difference between ng-container and ng-template in AngularJS
|
03 Jun, 2020
Both ng-container and ng-template can be used to create responsive and dynamic components. Angular provides a set of structural directives that can be used with both ng-template and ng-container such as:
ng-if
ng-for
ng-switch.
These structural directives are used to alter the structure of the DOM by conditionally rendering the HTML elements.
Both ng-container and ng-template render the wrapped elements while hiding themselves but they both follow different mechanisms, these difference will be shown in the following article.
ng-template: Let’s try an example:
import { Component } from '@angular/core';@Component({ selector: 'app-root', template: ` <div style="text-align: center;"> <!--no directive is used with ng-template--> <ng-template> <h1> {{title}} </h1> </ng-template> </div> `, styleUrls: []})export class AppComponent { title = 'geeksforgeeks'; }
Yes, nothing will be rendered. When we check the HTML code, we will see:
It is because ng-template does not do anything on its own. It needs some rendering logic to render something.
Let’s try another example:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <div style="text-align: center;"> <!--this time we will add an ng-if directive to ng-template.--> <ng-template [ngIf]="datahide"> <p> {{ title }} </p> </ng-template> </div> `, styleUrls: []})export class AppComponent { title = 'geeksforgeeks'; datahide = true;}
This time output will be like this:
In both the example, we can see template comments itself out, rendering the wrapped content conditionally.
ng-container: The ‘ng-container’ indeed shares some similarities with ‘ng-template’, like they both render the wrapped content while omitting themselves. But ng-container, on the other hand, is used when we use multiple structural directives and have no suitable parent wrapper. It does not require a structural directive to render the child elements unlike ng-template were using a structural directive was necessary.
Let’s see an example:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <div style="text-align: center;"> <!--ng-container without any structural directive--> <ng-container> <p> {{ title }} </p> </ng-container> </div> `, styleUrls: []})export class AppComponent { title = 'geeksforgeeks'; datahide = true;}
Now in this case, HTML was rendered even without any structural directive:
Let’s see what will happen if we wrap a ng-template inside a ng-container:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <div style="text-align: center;"> <!--ng-container used as wrapper for ng-template--> <ng-container> <ng-template [ngIf]="datahide"> <p> {{ title }} </p> </ng-template> </ng-container> </div> `, styleUrls: []})export class AppComponent { title = 'geeksforgeeks'; datahide = true;}
ng-container successfully wraps a ng-template:
To conclude, we can say that both the ng-container and ng-template are used to wrap HTML elements. They differ in their mechanisms. Also, multiple structural directives are not possible inside ng-template but ng-container can be used to wrap multiple elements containing different structural directives so it is a perfect container.
AngularJS-Misc
Picked
AngularJS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jun, 2020"
},
{
"code": null,
"e": 232,
"s": 28,
"text": "Both ng-container and ng-template can be used to create responsive and dynamic components. Angular provides a set of structural directives that can be used with both ng-template and ng-container such as:"
},
{
"code": null,
"e": 238,
"s": 232,
"text": "ng-if"
},
{
"code": null,
"e": 245,
"s": 238,
"text": "ng-for"
},
{
"code": null,
"e": 256,
"s": 245,
"text": "ng-switch."
},
{
"code": null,
"e": 374,
"s": 256,
"text": "These structural directives are used to alter the structure of the DOM by conditionally rendering the HTML elements. "
},
{
"code": null,
"e": 560,
"s": 374,
"text": "Both ng-container and ng-template render the wrapped elements while hiding themselves but they both follow different mechanisms, these difference will be shown in the following article."
},
{
"code": null,
"e": 595,
"s": 560,
"text": "ng-template: Let’s try an example:"
},
{
"code": "import { Component } from '@angular/core';@Component({ selector: 'app-root', template: ` <div style=\"text-align: center;\"> <!--no directive is used with ng-template--> <ng-template> <h1> {{title}} </h1> </ng-template> </div> `, styleUrls: []})export class AppComponent { title = 'geeksforgeeks'; }",
"e": 923,
"s": 595,
"text": null
},
{
"code": null,
"e": 996,
"s": 923,
"text": "Yes, nothing will be rendered. When we check the HTML code, we will see:"
},
{
"code": null,
"e": 1106,
"s": 996,
"text": "It is because ng-template does not do anything on its own. It needs some rendering logic to render something."
},
{
"code": null,
"e": 1133,
"s": 1106,
"text": "Let’s try another example:"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <div style=\"text-align: center;\"> <!--this time we will add an ng-if directive to ng-template.--> <ng-template [ngIf]=\"datahide\"> <p> {{ title }} </p> </ng-template> </div> `, styleUrls: []})export class AppComponent { title = 'geeksforgeeks'; datahide = true;}",
"e": 1512,
"s": 1133,
"text": null
},
{
"code": null,
"e": 1548,
"s": 1512,
"text": "This time output will be like this:"
},
{
"code": null,
"e": 1655,
"s": 1548,
"text": "In both the example, we can see template comments itself out, rendering the wrapped content conditionally."
},
{
"code": null,
"e": 2074,
"s": 1655,
"text": "ng-container: The ‘ng-container’ indeed shares some similarities with ‘ng-template’, like they both render the wrapped content while omitting themselves. But ng-container, on the other hand, is used when we use multiple structural directives and have no suitable parent wrapper. It does not require a structural directive to render the child elements unlike ng-template were using a structural directive was necessary."
},
{
"code": null,
"e": 2096,
"s": 2074,
"text": "Let’s see an example:"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <div style=\"text-align: center;\"> <!--ng-container without any structural directive--> <ng-container> <p> {{ title }} </p> </ng-container> </div> `, styleUrls: []})export class AppComponent { title = 'geeksforgeeks'; datahide = true;}",
"e": 2448,
"s": 2096,
"text": null
},
{
"code": null,
"e": 2523,
"s": 2448,
"text": "Now in this case, HTML was rendered even without any structural directive:"
},
{
"code": null,
"e": 2598,
"s": 2523,
"text": "Let’s see what will happen if we wrap a ng-template inside a ng-container:"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <div style=\"text-align: center;\"> <!--ng-container used as wrapper for ng-template--> <ng-container> <ng-template [ngIf]=\"datahide\"> <p> {{ title }} </p> </ng-template> </ng-container> </div> `, styleUrls: []})export class AppComponent { title = 'geeksforgeeks'; datahide = true;}",
"e": 2998,
"s": 2598,
"text": null
},
{
"code": null,
"e": 3045,
"s": 2998,
"text": "ng-container successfully wraps a ng-template:"
},
{
"code": null,
"e": 3378,
"s": 3045,
"text": "To conclude, we can say that both the ng-container and ng-template are used to wrap HTML elements. They differ in their mechanisms. Also, multiple structural directives are not possible inside ng-template but ng-container can be used to wrap multiple elements containing different structural directives so it is a perfect container."
},
{
"code": null,
"e": 3393,
"s": 3378,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 3400,
"s": 3393,
"text": "Picked"
},
{
"code": null,
"e": 3410,
"s": 3400,
"text": "AngularJS"
},
{
"code": null,
"e": 3427,
"s": 3410,
"text": "Web Technologies"
},
{
"code": null,
"e": 3454,
"s": 3427,
"text": "Web technologies Questions"
}
] |
Angular 4 - Pipes
|
In this chapter, we will discuss what are Pipes in Angular 4. Pipes were earlier called filters in Angular1 and called pipes in Angular 2 and 4.
The | character is used to transform data. Following is the syntax for the same
{{ Welcome to Angular 4 | lowercase}}
It takes integers, strings, arrays, and date as input separated with | to be converted in the format as required and display the same in the browser.
Let us consider a few examples using pipes.
Here, we want to display the text given to uppercase. This can be done using pipes as follows −
In the app.component.ts file, we have defined the title variable −
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 4 Project!';
}
The following line of code goes into the app.component.html file.
<b>{{title | uppercase}}</b><br/>
<b>{{title | lowercase}}</b>
The browser appears as shown in the following screenshot −
Angular 4 provides some built-in pipes. The pipes are listed below −
Lowercasepipe
Uppercasepipe
Datepipe
Currencypipe
Jsonpipe
Percentpipe
Decimalpipe
Slicepipe
We have already seen the lowercase and uppercase pipes. Let us now see how the other pipes work.
The following line of code will help us define the required variables in app.component.ts file −
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 4 Project!';
todaydate = new Date();
jsonval = {name:'Rox', age:'25', address:{a1:'Mumbai', a2:'Karnataka'}};
months = ["Jan", "Feb", "Mar", "April", "May", "Jun",
"July", "Aug", "Sept", "Oct", "Nov", "Dec"];
}
We will use the pipes in the app.component.html file.
<!--The content below is only a placeholder and can be replaced.-->
<div style = "width:100%;">
<div style = "width:40%;float:left;border:solid 1px black;">
<h1>Uppercase Pipe</h1>
<b>{{title | uppercase}}</b><br/>
<h1>Lowercase Pipe</h1>
<b>{{title | lowercase}}</b>
<h1>Currency Pipe</h1>
<b>{{6589.23 | currency:"USD"}}</b><br/>
<b>{{6589.23 | currency:"USD":true}}</b> //Boolean true is used to get the sign of the currency.
<h1>Date pipe</h1>
<b>{{todaydate | date:'d/M/y'}}</b><br/>
<b>{{todaydate | date:'shortTime'}}</b>
<h1>Decimal Pipe</h1>
<b>{{ 454.78787814 | number: '3.4-4' }}</b> // 3 is for main integer, 4 -4 are for integers to be displayed.
</div>
<div style = "width:40%;float:left;border:solid 1px black;">
<h1>Json Pipe</h1>
<b>{{ jsonval | json }}</b>
<h1>Percent Pipe</h1>
<b>{{00.54565 | percent}}</b>
<h1>Slice Pipe</h1>
<b>{{months | slice:2:6}}</b>
// here 2 and 6 refers to the start and the end index
</div>
</div>
The following screenshots show the output for each pipe −
To create a custom pipe, we have created a new ts file. Here, we want to create the sqrt custom pipe. We have given the same name to the file and it looks as follows −
import {Pipe, PipeTransform} from '@angular/core';
@Pipe ({
name : 'sqrt'
})
export class SqrtPipe implements PipeTransform {
transform(val : number) : number {
return Math.sqrt(val);
}
}
To create a custom pipe, we have to import Pipe and Pipe Transform from Angular/core. In the @Pipe directive, we have to give the name to our pipe, which will be used in our .html file. Since, we are creating the sqrt pipe, we will name it sqrt.
As we proceed further, we have to create the class and the class name is SqrtPipe. This class will implement the PipeTransform.
The transform method defined in the class will take argument as the number and will return the number after taking the square root.
Since we have created a new file, we need to add the same in app.module.ts. This is done as follows −
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
@NgModule({
declarations: [
SqrtPipe,
AppComponent,
NewCmpComponent,
ChangeTextDirective
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
We have created the app.sqrt.ts class. We have to import the same in app.module.ts and specify the path of the file. It also has to be included in the declarations as shown above.
Let us now see the call made to the sqrt pipe in the app.component.html file.
<h1>Custom Pipe</h1>
<b>Square root of 25 is: {{25 | sqrt}}</b>
<br/>
<b>Square root of 729 is: {{729 | sqrt}}</b>
The output looks as follows −
|
[
{
"code": null,
"e": 2271,
"s": 2126,
"text": "In this chapter, we will discuss what are Pipes in Angular 4. Pipes were earlier called filters in Angular1 and called pipes in Angular 2 and 4."
},
{
"code": null,
"e": 2351,
"s": 2271,
"text": "The | character is used to transform data. Following is the syntax for the same"
},
{
"code": null,
"e": 2390,
"s": 2351,
"text": "{{ Welcome to Angular 4 | lowercase}}\n"
},
{
"code": null,
"e": 2540,
"s": 2390,
"text": "It takes integers, strings, arrays, and date as input separated with | to be converted in the format as required and display the same in the browser."
},
{
"code": null,
"e": 2584,
"s": 2540,
"text": "Let us consider a few examples using pipes."
},
{
"code": null,
"e": 2680,
"s": 2584,
"text": "Here, we want to display the text given to uppercase. This can be done using pipes as follows −"
},
{
"code": null,
"e": 2747,
"s": 2680,
"text": "In the app.component.ts file, we have defined the title variable −"
},
{
"code": null,
"e": 2974,
"s": 2747,
"text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n}\n"
},
{
"code": null,
"e": 3040,
"s": 2974,
"text": "The following line of code goes into the app.component.html file."
},
{
"code": null,
"e": 3104,
"s": 3040,
"text": "<b>{{title | uppercase}}</b><br/>\n<b>{{title | lowercase}}</b>\n"
},
{
"code": null,
"e": 3163,
"s": 3104,
"text": "The browser appears as shown in the following screenshot −"
},
{
"code": null,
"e": 3232,
"s": 3163,
"text": "Angular 4 provides some built-in pipes. The pipes are listed below −"
},
{
"code": null,
"e": 3246,
"s": 3232,
"text": "Lowercasepipe"
},
{
"code": null,
"e": 3260,
"s": 3246,
"text": "Uppercasepipe"
},
{
"code": null,
"e": 3269,
"s": 3260,
"text": "Datepipe"
},
{
"code": null,
"e": 3282,
"s": 3269,
"text": "Currencypipe"
},
{
"code": null,
"e": 3291,
"s": 3282,
"text": "Jsonpipe"
},
{
"code": null,
"e": 3303,
"s": 3291,
"text": "Percentpipe"
},
{
"code": null,
"e": 3315,
"s": 3303,
"text": "Decimalpipe"
},
{
"code": null,
"e": 3325,
"s": 3315,
"text": "Slicepipe"
},
{
"code": null,
"e": 3422,
"s": 3325,
"text": "We have already seen the lowercase and uppercase pipes. Let us now see how the other pipes work."
},
{
"code": null,
"e": 3519,
"s": 3422,
"text": "The following line of code will help us define the required variables in app.component.ts file −"
},
{
"code": null,
"e": 3964,
"s": 3519,
"text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n todaydate = new Date();\n jsonval = {name:'Rox', age:'25', address:{a1:'Mumbai', a2:'Karnataka'}};\n months = [\"Jan\", \"Feb\", \"Mar\", \"April\", \"May\", \"Jun\",\n \"July\", \"Aug\", \"Sept\", \"Oct\", \"Nov\", \"Dec\"];\n}"
},
{
"code": null,
"e": 4018,
"s": 3964,
"text": "We will use the pipes in the app.component.html file."
},
{
"code": null,
"e": 5122,
"s": 4018,
"text": "<!--The content below is only a placeholder and can be replaced.-->\n<div style = \"width:100%;\">\n <div style = \"width:40%;float:left;border:solid 1px black;\">\n <h1>Uppercase Pipe</h1>\n <b>{{title | uppercase}}</b><br/>\n \n <h1>Lowercase Pipe</h1>\n <b>{{title | lowercase}}</b>\n \n <h1>Currency Pipe</h1>\n <b>{{6589.23 | currency:\"USD\"}}</b><br/>\n <b>{{6589.23 | currency:\"USD\":true}}</b> //Boolean true is used to get the sign of the currency.\n \n <h1>Date pipe</h1>\n <b>{{todaydate | date:'d/M/y'}}</b><br/>\n <b>{{todaydate | date:'shortTime'}}</b>\n \n <h1>Decimal Pipe</h1>\n <b>{{ 454.78787814 | number: '3.4-4' }}</b> // 3 is for main integer, 4 -4 are for integers to be displayed.\n </div>\n \n <div style = \"width:40%;float:left;border:solid 1px black;\">\n <h1>Json Pipe</h1>\n <b>{{ jsonval | json }}</b>\n <h1>Percent Pipe</h1>\n <b>{{00.54565 | percent}}</b>\n <h1>Slice Pipe</h1>\n <b>{{months | slice:2:6}}</b> \n // here 2 and 6 refers to the start and the end index\n </div>\n</div>"
},
{
"code": null,
"e": 5180,
"s": 5122,
"text": "The following screenshots show the output for each pipe −"
},
{
"code": null,
"e": 5348,
"s": 5180,
"text": "To create a custom pipe, we have created a new ts file. Here, we want to create the sqrt custom pipe. We have given the same name to the file and it looks as follows −"
},
{
"code": null,
"e": 5552,
"s": 5348,
"text": "import {Pipe, PipeTransform} from '@angular/core';\n@Pipe ({\n name : 'sqrt'\n})\nexport class SqrtPipe implements PipeTransform {\n transform(val : number) : number {\n return Math.sqrt(val);\n }\n}\n"
},
{
"code": null,
"e": 5798,
"s": 5552,
"text": "To create a custom pipe, we have to import Pipe and Pipe Transform from Angular/core. In the @Pipe directive, we have to give the name to our pipe, which will be used in our .html file. Since, we are creating the sqrt pipe, we will name it sqrt."
},
{
"code": null,
"e": 5926,
"s": 5798,
"text": "As we proceed further, we have to create the class and the class name is SqrtPipe. This class will implement the PipeTransform."
},
{
"code": null,
"e": 6058,
"s": 5926,
"text": "The transform method defined in the class will take argument as the number and will return the number after taking the square root."
},
{
"code": null,
"e": 6160,
"s": 6058,
"text": "Since we have created a new file, we need to add the same in app.module.ts. This is done as follows −"
},
{
"code": null,
"e": 6717,
"s": 6160,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\n\nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\nimport { ChangeTextDirective } from './change-text.directive';\nimport { SqrtPipe } from './app.sqrt';\n\n@NgModule({\n declarations: [\n SqrtPipe,\n AppComponent,\n NewCmpComponent,\n ChangeTextDirective\n ],\n\n imports: [\n BrowserModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }\n"
},
{
"code": null,
"e": 6897,
"s": 6717,
"text": "We have created the app.sqrt.ts class. We have to import the same in app.module.ts and specify the path of the file. It also has to be included in the declarations as shown above."
},
{
"code": null,
"e": 6975,
"s": 6897,
"text": "Let us now see the call made to the sqrt pipe in the app.component.html file."
},
{
"code": null,
"e": 7091,
"s": 6975,
"text": "<h1>Custom Pipe</h1>\n<b>Square root of 25 is: {{25 | sqrt}}</b>\n<br/>\n<b>Square root of 729 is: {{729 | sqrt}}</b>\n"
}
] |
Python MySQL – Insert into Table
|
06 Mar, 2020
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command.
Note: Before we insert data into our database, we need to create a table. In order to do so, refer to Python: MySQL Create Table.
You can insert one row or multiple rows at once. The connector code is required to connect the commands to the particular database.
Connector query
# Enter the server name in host# followed by your user and# password along with the database # name provided by you. import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "password", database = "database_name") mycursor = mydb.cursor()
Now, the Insert into Query can be written as follows:
Example: Let’s suppose the record looks like this –
sql = "INSERT INTO Student (Name, Roll_no) VALUES (%s, %s)"val = ("Ram", "85") mycursor.execute(sql, val)mydb.commit() print(mycursor.rowcount, "details inserted") # disconnecting from servermydb.close()
Output:
1 details inserted
To insert multiple values at once, executemany() method is used. This method iterates through the sequence of parameters, passing the current parameter to the execute method.
Example:
sql = "INSERT INTO Student (Name, Roll_no) VALUES (%s, %s)"val = [("Akash", "98"), ("Neel", "23"), ("Rohan", "43"), ("Amit", "87"), ("Anil", "45"), ("Megha", "55"), ("Sita", "95")] mycursor.executemany(sql, val)mydb.commit() print(mycursor.rowcount, "details inserted") # disconnecting from servermydb.close()
Output:
7 details inserted
Note:
The cursor() is used in order to iterate through the rows.
Without the command mydb.commit() the changes will not be saved.
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
Read JSON file using Python
Python map() function
How to iterate through Excel rows in Python?
Enumerate() in Python
Adding new column to existing DataFrame in Pandas
Python OOPs Concepts
Different ways to create Pandas Dataframe
How to get column names in Pandas dataframe
Stack in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Mar, 2020"
},
{
"code": null,
"e": 346,
"s": 28,
"text": "MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command."
},
{
"code": null,
"e": 476,
"s": 346,
"text": "Note: Before we insert data into our database, we need to create a table. In order to do so, refer to Python: MySQL Create Table."
},
{
"code": null,
"e": 608,
"s": 476,
"text": "You can insert one row or multiple rows at once. The connector code is required to connect the commands to the particular database."
},
{
"code": null,
"e": 624,
"s": 608,
"text": "Connector query"
},
{
"code": "# Enter the server name in host# followed by your user and# password along with the database # name provided by you. import mysql.connector mydb = mysql.connector.connect( host = \"localhost\", user = \"username\", password = \"password\", database = \"database_name\") mycursor = mydb.cursor()",
"e": 921,
"s": 624,
"text": null
},
{
"code": null,
"e": 975,
"s": 921,
"text": "Now, the Insert into Query can be written as follows:"
},
{
"code": null,
"e": 1027,
"s": 975,
"text": "Example: Let’s suppose the record looks like this –"
},
{
"code": "sql = \"INSERT INTO Student (Name, Roll_no) VALUES (%s, %s)\"val = (\"Ram\", \"85\") mycursor.execute(sql, val)mydb.commit() print(mycursor.rowcount, \"details inserted\") # disconnecting from servermydb.close()",
"e": 1234,
"s": 1027,
"text": null
},
{
"code": null,
"e": 1242,
"s": 1234,
"text": "Output:"
},
{
"code": null,
"e": 1261,
"s": 1242,
"text": "1 details inserted"
},
{
"code": null,
"e": 1436,
"s": 1261,
"text": "To insert multiple values at once, executemany() method is used. This method iterates through the sequence of parameters, passing the current parameter to the execute method."
},
{
"code": null,
"e": 1445,
"s": 1436,
"text": "Example:"
},
{
"code": "sql = \"INSERT INTO Student (Name, Roll_no) VALUES (%s, %s)\"val = [(\"Akash\", \"98\"), (\"Neel\", \"23\"), (\"Rohan\", \"43\"), (\"Amit\", \"87\"), (\"Anil\", \"45\"), (\"Megha\", \"55\"), (\"Sita\", \"95\")] mycursor.executemany(sql, val)mydb.commit() print(mycursor.rowcount, \"details inserted\") # disconnecting from servermydb.close()",
"e": 1796,
"s": 1445,
"text": null
},
{
"code": null,
"e": 1804,
"s": 1796,
"text": "Output:"
},
{
"code": null,
"e": 1823,
"s": 1804,
"text": "7 details inserted"
},
{
"code": null,
"e": 1829,
"s": 1823,
"text": "Note:"
},
{
"code": null,
"e": 1888,
"s": 1829,
"text": "The cursor() is used in order to iterate through the rows."
},
{
"code": null,
"e": 1953,
"s": 1888,
"text": "Without the command mydb.commit() the changes will not be saved."
},
{
"code": null,
"e": 1966,
"s": 1953,
"text": "Python-mySQL"
},
{
"code": null,
"e": 1973,
"s": 1966,
"text": "Python"
},
{
"code": null,
"e": 2071,
"s": 1973,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2101,
"s": 2071,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2129,
"s": 2101,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 2151,
"s": 2129,
"text": "Python map() function"
},
{
"code": null,
"e": 2196,
"s": 2151,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 2218,
"s": 2196,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2268,
"s": 2218,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 2289,
"s": 2268,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2331,
"s": 2289,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2375,
"s": 2331,
"text": "How to get column names in Pandas dataframe"
}
] |
shred command in Linux with Examples
|
17 May, 2020
When you delete a file from Linux or from any os, then the file is not deleted permanently from the hard disk. When a file is deleted it first gets moved to the trash and as soon as you clear off the trash the files get deleted for the file system. But the file is still there in your hard drive and it could be recovered.
When you delete a file permanently or delete it from the trash, the pointer pointing to the file leaves the address of it and the data of the file is sent to a sector in hard disk and is considered as unallocated space and it can be recovered easily. The file gets permanently deleted when the OS writes over the sector of the file which was considered as unallocated. So, in order to delete a file completely from hard disk “shred” is used in Linux. This command overwrites the contents of a file multiple times, using patterns chosen to maximize the destruction of the residual data, making it harder for even very expensive hardware probing to recover it.
Syntax:
shred [OPTION]... FILE...
1. To overwrite the contents of the file multiple times to make it unrecoverable.
$shred filename.txt
It will change the file data in such a way that it would be really hard to get the old file back.
Note: In this case, The name of the file is filename.txt you may change it as per your need.
2. To change the number of times a file is to be overwritten.
$shred -n 10 filename.txt
This command will overwrite the file 10 times.
Note: In this case, the number of times the file is to be shredded is set to be 10 and the name of the file is filename.txt you may change these as per your need.
3. To overwrite and delete a file as well.
$shred -u filename.txt
This will overwrite the file many time and will delete it as well.
Note: In this case, The name of the file is filename.txt you may change it as per your need.
4. To overwrite some specific bytes of text only.
$shred -s 5 filename.txt
This will overwrite the first 5 bytes of the file.
Note: In this case, The name of the file is filename.txt and the number of bytes is 5, you may change these as per your need.
5. To run shred command with verbose mode or to get how many times the file is overwritten
$shred -v filename.txt
It will display every time it overwrites the file.
Note: In this case, The name of the file is filename.txt you may change it as per your need.
6. To change permissions to allow writing if necessary while using shred command.
$shred -f filename.txt
When you run shred command with -f option it will write the file even by changing the permissions if necessary.
Note: In this case, The name of the file is filename.txt you may change it as per your need.
7. To add a final overwrite with zeros to hide shredding.
$shred -z filename.txt`
After completing the shredding it will overwrite file with zeros to hide shredding.
Note: In this case, The name of the file is filename.txt you may change it as per your need.
8. To get basic details and version of shred command.
$shred --version
This will display the version of the shred command present in your system along with some copyright details.
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
Introduction to Linux Operating System
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
chmod command in Linux with examples
screen command in Linux with Examples
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 May, 2020"
},
{
"code": null,
"e": 376,
"s": 53,
"text": "When you delete a file from Linux or from any os, then the file is not deleted permanently from the hard disk. When a file is deleted it first gets moved to the trash and as soon as you clear off the trash the files get deleted for the file system. But the file is still there in your hard drive and it could be recovered."
},
{
"code": null,
"e": 1035,
"s": 376,
"text": "When you delete a file permanently or delete it from the trash, the pointer pointing to the file leaves the address of it and the data of the file is sent to a sector in hard disk and is considered as unallocated space and it can be recovered easily. The file gets permanently deleted when the OS writes over the sector of the file which was considered as unallocated. So, in order to delete a file completely from hard disk “shred” is used in Linux. This command overwrites the contents of a file multiple times, using patterns chosen to maximize the destruction of the residual data, making it harder for even very expensive hardware probing to recover it."
},
{
"code": null,
"e": 1043,
"s": 1035,
"text": "Syntax:"
},
{
"code": null,
"e": 1069,
"s": 1043,
"text": "shred [OPTION]... FILE..."
},
{
"code": null,
"e": 1151,
"s": 1069,
"text": "1. To overwrite the contents of the file multiple times to make it unrecoverable."
},
{
"code": null,
"e": 1172,
"s": 1151,
"text": "$shred filename.txt\n"
},
{
"code": null,
"e": 1270,
"s": 1172,
"text": "It will change the file data in such a way that it would be really hard to get the old file back."
},
{
"code": null,
"e": 1363,
"s": 1270,
"text": "Note: In this case, The name of the file is filename.txt you may change it as per your need."
},
{
"code": null,
"e": 1425,
"s": 1363,
"text": "2. To change the number of times a file is to be overwritten."
},
{
"code": null,
"e": 1452,
"s": 1425,
"text": "$shred -n 10 filename.txt\n"
},
{
"code": null,
"e": 1499,
"s": 1452,
"text": "This command will overwrite the file 10 times."
},
{
"code": null,
"e": 1662,
"s": 1499,
"text": "Note: In this case, the number of times the file is to be shredded is set to be 10 and the name of the file is filename.txt you may change these as per your need."
},
{
"code": null,
"e": 1705,
"s": 1662,
"text": "3. To overwrite and delete a file as well."
},
{
"code": null,
"e": 1729,
"s": 1705,
"text": "$shred -u filename.txt\n"
},
{
"code": null,
"e": 1796,
"s": 1729,
"text": "This will overwrite the file many time and will delete it as well."
},
{
"code": null,
"e": 1889,
"s": 1796,
"text": "Note: In this case, The name of the file is filename.txt you may change it as per your need."
},
{
"code": null,
"e": 1939,
"s": 1889,
"text": "4. To overwrite some specific bytes of text only."
},
{
"code": null,
"e": 1965,
"s": 1939,
"text": "$shred -s 5 filename.txt\n"
},
{
"code": null,
"e": 2016,
"s": 1965,
"text": "This will overwrite the first 5 bytes of the file."
},
{
"code": null,
"e": 2142,
"s": 2016,
"text": "Note: In this case, The name of the file is filename.txt and the number of bytes is 5, you may change these as per your need."
},
{
"code": null,
"e": 2233,
"s": 2142,
"text": "5. To run shred command with verbose mode or to get how many times the file is overwritten"
},
{
"code": null,
"e": 2257,
"s": 2233,
"text": "$shred -v filename.txt\n"
},
{
"code": null,
"e": 2308,
"s": 2257,
"text": "It will display every time it overwrites the file."
},
{
"code": null,
"e": 2401,
"s": 2308,
"text": "Note: In this case, The name of the file is filename.txt you may change it as per your need."
},
{
"code": null,
"e": 2483,
"s": 2401,
"text": "6. To change permissions to allow writing if necessary while using shred command."
},
{
"code": null,
"e": 2507,
"s": 2483,
"text": "$shred -f filename.txt\n"
},
{
"code": null,
"e": 2619,
"s": 2507,
"text": "When you run shred command with -f option it will write the file even by changing the permissions if necessary."
},
{
"code": null,
"e": 2712,
"s": 2619,
"text": "Note: In this case, The name of the file is filename.txt you may change it as per your need."
},
{
"code": null,
"e": 2770,
"s": 2712,
"text": "7. To add a final overwrite with zeros to hide shredding."
},
{
"code": null,
"e": 2795,
"s": 2770,
"text": "$shred -z filename.txt`\n"
},
{
"code": null,
"e": 2879,
"s": 2795,
"text": "After completing the shredding it will overwrite file with zeros to hide shredding."
},
{
"code": null,
"e": 2972,
"s": 2879,
"text": "Note: In this case, The name of the file is filename.txt you may change it as per your need."
},
{
"code": null,
"e": 3026,
"s": 2972,
"text": "8. To get basic details and version of shred command."
},
{
"code": null,
"e": 3044,
"s": 3026,
"text": "$shred --version\n"
},
{
"code": null,
"e": 3153,
"s": 3044,
"text": "This will display the version of the shred command present in your system along with some copyright details."
},
{
"code": null,
"e": 3167,
"s": 3153,
"text": "linux-command"
},
{
"code": null,
"e": 3189,
"s": 3167,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 3200,
"s": 3189,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3298,
"s": 3200,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3324,
"s": 3298,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3359,
"s": 3324,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 3396,
"s": 3359,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 3425,
"s": 3396,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 3464,
"s": 3425,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 3501,
"s": 3464,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 3541,
"s": 3501,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 3575,
"s": 3541,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 3612,
"s": 3575,
"text": "chmod command in Linux with examples"
}
] |
How to validate if input in input field has base64 encoded string using express-validator ?
|
27 Dec, 2021
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. If In a certain input field only base 64 encoded string are allowed i.e there not allowed any other form of string which not constitute base64 encoded string. We can also validate these input fields to accept only base 64 encoded string using express-validator middleware.
Command to install express-validator:
npm install express-validator
Steps to use express-validator to implement the logic:
Install express-validator middleware.
Create a validator.js file to code all the validation logic.
Validate input by validateInputField: check(input field name) and chain on the validation isBase64() with ‘ . ‘
Use the validation name(validateInputField) in the routes as a middleware as an array of validations.
Destructure ‘validationResult’ function from express-validator to use it to find any errors.
If error occurs redirect to the same page passing the error information.
If error list is empty, give access to the user for the subsequent request.
Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql.
Example: This example illustrates how to validate a input field to accept only base 64 encoded string.
Filename – index.js
javascript
const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateBase64Data } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/data', [validateBase64Data], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()){ return res.send(formTemplet({errors})) } const {name, base64data} = req.body await repo.create({ name, base64data }) res.send('<h2>Base 64 data decoded and ' + 'Stored successfully in the database</h2>')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})
Filename – repository.js: This file contains all the logic to create a local database and interact with it.
javascript
// Importing node.js file system moduleconst fs = require('fs')const { base64decode } = require('nodejs-base64'); class Repository { constructor(filename) { // The filename where datas are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ // Fetch all existing records const records = await this.getAll() // Decode base64 encoded data const data = base64decode(attrs.base64data) // New record const record = { name:attrs.name, data } // All the existing records with // new record push back to database records.push(record) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return record }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')
Filename – form.js: This file contains logic to show HTML form.
javascript
const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return ` <!DOCTYPE html> <html> <head> <link rel='stylesheet'href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns{ margin-top: 100px; } .button{ margin-top : 10px } </style> </head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/data' method='POST'> <div> <div> <label class='label' id='name'> Name </label> </div> <input class='input' type='text' name='name' placeholder='Submitted By' for='name'> </div> <div> <div> <label class='label' id='base64data'> Base 64 data </label> </div> <input class='input' type='text' name='base64data' placeholder='Base 64 Encode data' for='base64data'> <p class="help is-danger"> ${getError(errors, 'base64data')} </p> </div> <div> <button class='button is-primary'> Submit </button> </div> </form> </div> </div> </div> </body> </html> `}
Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to accept only base encoded 64 string)
javascript
const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateBase64Data : check('base64data') // To delete leading and trailing space .trim() // Validate input field to accept only base32 string .isBase64() // Custom message .withMessage('Must be a Base 64 encoded string')}
Filename – package.json
package.json file
Database:
Database
Online website that convert a normal string to base 64 string:
Online website that convert a normal string to base64 string(to show for which string we give base64 input)
Output:
Attempt to submit with invalid base64 string
Response when attempt to submit with invalid base 64 string
Attempt to submit with valid base64 string
Response when attempt to submit with valid base 64 string
Database after successful submission of form:
Database after successful submission of form
Note: We have used some Bulma classes(CSS framework) in the signup.js file to design the content.
sagartomar9927
kk9826225
Express.js
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Dec, 2021"
},
{
"code": null,
"e": 521,
"s": 28,
"text": "In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. If In a certain input field only base 64 encoded string are allowed i.e there not allowed any other form of string which not constitute base64 encoded string. We can also validate these input fields to accept only base 64 encoded string using express-validator middleware."
},
{
"code": null,
"e": 559,
"s": 521,
"text": "Command to install express-validator:"
},
{
"code": null,
"e": 589,
"s": 559,
"text": "npm install express-validator"
},
{
"code": null,
"e": 644,
"s": 589,
"text": "Steps to use express-validator to implement the logic:"
},
{
"code": null,
"e": 682,
"s": 644,
"text": "Install express-validator middleware."
},
{
"code": null,
"e": 743,
"s": 682,
"text": "Create a validator.js file to code all the validation logic."
},
{
"code": null,
"e": 855,
"s": 743,
"text": "Validate input by validateInputField: check(input field name) and chain on the validation isBase64() with ‘ . ‘"
},
{
"code": null,
"e": 957,
"s": 855,
"text": "Use the validation name(validateInputField) in the routes as a middleware as an array of validations."
},
{
"code": null,
"e": 1050,
"s": 957,
"text": "Destructure ‘validationResult’ function from express-validator to use it to find any errors."
},
{
"code": null,
"e": 1123,
"s": 1050,
"text": "If error occurs redirect to the same page passing the error information."
},
{
"code": null,
"e": 1199,
"s": 1123,
"text": "If error list is empty, give access to the user for the subsequent request."
},
{
"code": null,
"e": 1365,
"s": 1199,
"text": "Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql."
},
{
"code": null,
"e": 1468,
"s": 1365,
"text": "Example: This example illustrates how to validate a input field to accept only base 64 encoded string."
},
{
"code": null,
"e": 1488,
"s": 1468,
"text": "Filename – index.js"
},
{
"code": null,
"e": 1499,
"s": 1488,
"text": "javascript"
},
{
"code": "const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateBase64Data } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/data', [validateBase64Data], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()){ return res.send(formTemplet({errors})) } const {name, base64data} = req.body await repo.create({ name, base64data }) res.send('<h2>Base 64 data decoded and ' + 'Stored successfully in the database</h2>')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})",
"e": 2507,
"s": 1499,
"text": null
},
{
"code": null,
"e": 2615,
"s": 2507,
"text": "Filename – repository.js: This file contains all the logic to create a local database and interact with it."
},
{
"code": null,
"e": 2626,
"s": 2615,
"text": "javascript"
},
{
"code": "// Importing node.js file system moduleconst fs = require('fs')const { base64decode } = require('nodejs-base64'); class Repository { constructor(filename) { // The filename where datas are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ // Fetch all existing records const records = await this.getAll() // Decode base64 encoded data const data = base64decode(attrs.base64data) // New record const record = { name:attrs.name, data } // All the existing records with // new record push back to database records.push(record) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return record }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')",
"e": 3970,
"s": 2626,
"text": null
},
{
"code": null,
"e": 4034,
"s": 3970,
"text": "Filename – form.js: This file contains logic to show HTML form."
},
{
"code": null,
"e": 4045,
"s": 4034,
"text": "javascript"
},
{
"code": "const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return ` <!DOCTYPE html> <html> <head> <link rel='stylesheet'href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns{ margin-top: 100px; } .button{ margin-top : 10px } </style> </head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/data' method='POST'> <div> <div> <label class='label' id='name'> Name </label> </div> <input class='input' type='text' name='name' placeholder='Submitted By' for='name'> </div> <div> <div> <label class='label' id='base64data'> Base 64 data </label> </div> <input class='input' type='text' name='base64data' placeholder='Base 64 Encode data' for='base64data'> <p class=\"help is-danger\"> ${getError(errors, 'base64data')} </p> </div> <div> <button class='button is-primary'> Submit </button> </div> </form> </div> </div> </div> </body> </html> `}",
"e": 5837,
"s": 4045,
"text": null
},
{
"code": null,
"e": 5976,
"s": 5837,
"text": "Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to accept only base encoded 64 string)"
},
{
"code": null,
"e": 5987,
"s": 5976,
"text": "javascript"
},
{
"code": "const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateBase64Data : check('base64data') // To delete leading and trailing space .trim() // Validate input field to accept only base32 string .isBase64() // Custom message .withMessage('Must be a Base 64 encoded string')}",
"e": 6330,
"s": 5987,
"text": null
},
{
"code": null,
"e": 6354,
"s": 6330,
"text": "Filename – package.json"
},
{
"code": null,
"e": 6372,
"s": 6354,
"text": "package.json file"
},
{
"code": null,
"e": 6382,
"s": 6372,
"text": "Database:"
},
{
"code": null,
"e": 6391,
"s": 6382,
"text": "Database"
},
{
"code": null,
"e": 6454,
"s": 6391,
"text": "Online website that convert a normal string to base 64 string:"
},
{
"code": null,
"e": 6562,
"s": 6454,
"text": "Online website that convert a normal string to base64 string(to show for which string we give base64 input)"
},
{
"code": null,
"e": 6570,
"s": 6562,
"text": "Output:"
},
{
"code": null,
"e": 6615,
"s": 6570,
"text": "Attempt to submit with invalid base64 string"
},
{
"code": null,
"e": 6675,
"s": 6615,
"text": "Response when attempt to submit with invalid base 64 string"
},
{
"code": null,
"e": 6718,
"s": 6675,
"text": "Attempt to submit with valid base64 string"
},
{
"code": null,
"e": 6776,
"s": 6718,
"text": "Response when attempt to submit with valid base 64 string"
},
{
"code": null,
"e": 6822,
"s": 6776,
"text": "Database after successful submission of form:"
},
{
"code": null,
"e": 6867,
"s": 6822,
"text": "Database after successful submission of form"
},
{
"code": null,
"e": 6965,
"s": 6867,
"text": "Note: We have used some Bulma classes(CSS framework) in the signup.js file to design the content."
},
{
"code": null,
"e": 6980,
"s": 6965,
"text": "sagartomar9927"
},
{
"code": null,
"e": 6990,
"s": 6980,
"text": "kk9826225"
},
{
"code": null,
"e": 7001,
"s": 6990,
"text": "Express.js"
},
{
"code": null,
"e": 7014,
"s": 7001,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 7022,
"s": 7014,
"text": "Node.js"
},
{
"code": null,
"e": 7039,
"s": 7022,
"text": "Web Technologies"
}
] |
Global Variables in MATLAB
|
04 Jul, 2021
Variables in programming are generally storage spaces to store a certain type of data. There are many types of variables, but two commonly used types are local and Global variables. Generally, each MATLAB function has its own local variables. But sometimes for the sake of programming, we need to change the value of the local variable in another function. Sometimes it becomes a tedious task to perform. Here, comes the need for the global variables. If we declare any variable as global, we can access that variable from any function. Basically, all functions share the same copy of the variable. Any change of value to that variable, in any function, is visible to all the functions that declare it as global.
A variable in MATLAB is set as global by writing a global command before the variable name(s). While declaring any variable as global for the first time, the variable is initialized to an empty 0X0 matrix. If any variable with the same name as a global variable is declared while the global variable exists in the current workspace MATLAB creates a warning and changes that variable and its scope to match with the global variable. We have to write the global command in every function where we want to use that global variable. Some useful tips are given below.
If we want to clear a global variable from all workplaces, we can use the command: clear global variable.
On the other hand, the command “clear variable” will only clear the variable from the current workspace, not from the other workspaces.
Syntax: global variable_name1 ... variable_nameN
Note: Here we have declared N global variables where the name of the ith global variable is variable_namei. Generally, for the name of global variables uppercase letters are used so that, we can easily differentiate between the local and the global variables.
Suppose, we declare a global variable following the above syntax with the name global variable_name inside function A. Now, we want to modify that global variable in function B. In that case, we need to write the global command before variable_name again inside function B. Otherwise, it will not work. Following are the examples.
We take one script A.m and one function named function B is used for example.
Share global variables between two functions
In this case, we will declare the global variable X in script A.m and will modify it inside function B and try to see the output.
Example:
Matlab
% MATLAB code for function B % and save as MATLAB script name B.m function B() global X % global command used % as we want to modify the global % variable declared in A.m X = X*5;end
MATLAB Script A.m
Matlab
% MATLAB code for main script A.mglobal X; % declaring global functionX = 3;disp("value of X before modification:");XB(); % calling B function written above.disp("value of X after modification:");X
Output:
Sharing global variable between function and command line
Here we will declare the global variable in the command window and will modify it inside function B and try to see the output.
Matlab
% MATLAB Code for global variable in the % command window and will modify it inside % function B for this again we use script B.Mfunction B()global X % global command used % as we want to modify the global% variable declared in A.mX = X*5;end
Output:
If the global command is not used in every function:
Here we will declare the global variable in script A.m and will try to modify the variable inside function B without using the command ‘global’. But in the output, we will see that the variable will not be modified as we haven’t use the command ‘global’ inside function B.
Matlab
% MATLAB code for declare the global % variable in script A.m and will try to% modify the variable inside function B without% using the command 'global'function B() function B() X = 3*5; end
Matlab
% MATLAB code declare the global variable in % script A.m and will try to modify the variable% inside function B without using the command 'global'global X; X = 3; disp("value of X before modification:");X B(); % calling B function written above.disp("value of X after modification:");X
Output:
MATLAB-Basic
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?
How to Solve Histogram Equalization Numerical Problem in MATLAB?
Adaptive Histogram Equalization in Image Processing Using MATLAB
MRI Image Segmentation in MATLAB
How to detect duplicate values and its indices within an array in MATLAB?
Double Integral in MATLAB
How to Normalize a Histogram in MATLAB?
Classes and Object in MATLAB
How to remove space in a string in MATLAB?
Forward and Inverse Fourier Transform of an Image in MATLAB
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jul, 2021"
},
{
"code": null,
"e": 741,
"s": 28,
"text": "Variables in programming are generally storage spaces to store a certain type of data. There are many types of variables, but two commonly used types are local and Global variables. Generally, each MATLAB function has its own local variables. But sometimes for the sake of programming, we need to change the value of the local variable in another function. Sometimes it becomes a tedious task to perform. Here, comes the need for the global variables. If we declare any variable as global, we can access that variable from any function. Basically, all functions share the same copy of the variable. Any change of value to that variable, in any function, is visible to all the functions that declare it as global."
},
{
"code": null,
"e": 1304,
"s": 741,
"text": "A variable in MATLAB is set as global by writing a global command before the variable name(s). While declaring any variable as global for the first time, the variable is initialized to an empty 0X0 matrix. If any variable with the same name as a global variable is declared while the global variable exists in the current workspace MATLAB creates a warning and changes that variable and its scope to match with the global variable. We have to write the global command in every function where we want to use that global variable. Some useful tips are given below."
},
{
"code": null,
"e": 1410,
"s": 1304,
"text": "If we want to clear a global variable from all workplaces, we can use the command: clear global variable."
},
{
"code": null,
"e": 1546,
"s": 1410,
"text": "On the other hand, the command “clear variable” will only clear the variable from the current workspace, not from the other workspaces."
},
{
"code": null,
"e": 1595,
"s": 1546,
"text": "Syntax: global variable_name1 ... variable_nameN"
},
{
"code": null,
"e": 1855,
"s": 1595,
"text": "Note: Here we have declared N global variables where the name of the ith global variable is variable_namei. Generally, for the name of global variables uppercase letters are used so that, we can easily differentiate between the local and the global variables."
},
{
"code": null,
"e": 2186,
"s": 1855,
"text": "Suppose, we declare a global variable following the above syntax with the name global variable_name inside function A. Now, we want to modify that global variable in function B. In that case, we need to write the global command before variable_name again inside function B. Otherwise, it will not work. Following are the examples."
},
{
"code": null,
"e": 2264,
"s": 2186,
"text": "We take one script A.m and one function named function B is used for example."
},
{
"code": null,
"e": 2309,
"s": 2264,
"text": "Share global variables between two functions"
},
{
"code": null,
"e": 2439,
"s": 2309,
"text": "In this case, we will declare the global variable X in script A.m and will modify it inside function B and try to see the output."
},
{
"code": null,
"e": 2448,
"s": 2439,
"text": "Example:"
},
{
"code": null,
"e": 2455,
"s": 2448,
"text": "Matlab"
},
{
"code": "% MATLAB code for function B % and save as MATLAB script name B.m function B() global X % global command used % as we want to modify the global % variable declared in A.m X = X*5;end",
"e": 2655,
"s": 2455,
"text": null
},
{
"code": null,
"e": 2673,
"s": 2655,
"text": "MATLAB Script A.m"
},
{
"code": null,
"e": 2680,
"s": 2673,
"text": "Matlab"
},
{
"code": "% MATLAB code for main script A.mglobal X; % declaring global functionX = 3;disp(\"value of X before modification:\");XB(); % calling B function written above.disp(\"value of X after modification:\");X",
"e": 2878,
"s": 2680,
"text": null
},
{
"code": null,
"e": 2886,
"s": 2878,
"text": "Output:"
},
{
"code": null,
"e": 2944,
"s": 2886,
"text": "Sharing global variable between function and command line"
},
{
"code": null,
"e": 3071,
"s": 2944,
"text": "Here we will declare the global variable in the command window and will modify it inside function B and try to see the output."
},
{
"code": null,
"e": 3078,
"s": 3071,
"text": "Matlab"
},
{
"code": "% MATLAB Code for global variable in the % command window and will modify it inside % function B for this again we use script B.Mfunction B()global X % global command used % as we want to modify the global% variable declared in A.mX = X*5;end",
"e": 3325,
"s": 3078,
"text": null
},
{
"code": null,
"e": 3333,
"s": 3325,
"text": "Output:"
},
{
"code": null,
"e": 3386,
"s": 3333,
"text": "If the global command is not used in every function:"
},
{
"code": null,
"e": 3659,
"s": 3386,
"text": "Here we will declare the global variable in script A.m and will try to modify the variable inside function B without using the command ‘global’. But in the output, we will see that the variable will not be modified as we haven’t use the command ‘global’ inside function B."
},
{
"code": null,
"e": 3666,
"s": 3659,
"text": "Matlab"
},
{
"code": "% MATLAB code for declare the global % variable in script A.m and will try to% modify the variable inside function B without% using the command 'global'function B() function B() X = 3*5; end",
"e": 3861,
"s": 3666,
"text": null
},
{
"code": null,
"e": 3868,
"s": 3861,
"text": "Matlab"
},
{
"code": "% MATLAB code declare the global variable in % script A.m and will try to modify the variable% inside function B without using the command 'global'global X; X = 3; disp(\"value of X before modification:\");X B(); % calling B function written above.disp(\"value of X after modification:\");X",
"e": 4157,
"s": 3868,
"text": null
},
{
"code": null,
"e": 4165,
"s": 4157,
"text": "Output:"
},
{
"code": null,
"e": 4178,
"s": 4165,
"text": "MATLAB-Basic"
},
{
"code": null,
"e": 4185,
"s": 4178,
"text": "Picked"
},
{
"code": null,
"e": 4192,
"s": 4185,
"text": "MATLAB"
},
{
"code": null,
"e": 4290,
"s": 4192,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4369,
"s": 4290,
"text": "How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?"
},
{
"code": null,
"e": 4434,
"s": 4369,
"text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?"
},
{
"code": null,
"e": 4499,
"s": 4434,
"text": "Adaptive Histogram Equalization in Image Processing Using MATLAB"
},
{
"code": null,
"e": 4532,
"s": 4499,
"text": "MRI Image Segmentation in MATLAB"
},
{
"code": null,
"e": 4606,
"s": 4532,
"text": "How to detect duplicate values and its indices within an array in MATLAB?"
},
{
"code": null,
"e": 4632,
"s": 4606,
"text": "Double Integral in MATLAB"
},
{
"code": null,
"e": 4672,
"s": 4632,
"text": "How to Normalize a Histogram in MATLAB?"
},
{
"code": null,
"e": 4701,
"s": 4672,
"text": "Classes and Object in MATLAB"
},
{
"code": null,
"e": 4744,
"s": 4701,
"text": "How to remove space in a string in MATLAB?"
}
] |
How to catch FloatingPointError Exception in Python?
|
FloatingPointError is raised by floating point operations that result in errors, when floating point exception control (fpectl) is turned on. Enabling fpectl requires an interpreter compiled with the --with-fpectl flag.
The given code is rewritten as follows to handle the exception and find its type.
import sys
import math
import fpectl
try:
print 'Control off:', math.exp(700)
fpectl.turnon_sigfpe()
print 'Control on:', math.exp(1000)
except Exception as e:
print e
print sys.exc_type
Control off: 1.01423205474e+304
Control on: in math_1
<type 'exceptions.FloatingPointError'>
|
[
{
"code": null,
"e": 1407,
"s": 1187,
"text": "FloatingPointError is raised by floating point operations that result in errors, when floating point exception control (fpectl) is turned on. Enabling fpectl requires an interpreter compiled with the --with-fpectl flag."
},
{
"code": null,
"e": 1489,
"s": 1407,
"text": "The given code is rewritten as follows to handle the exception and find its type."
},
{
"code": null,
"e": 1677,
"s": 1489,
"text": "import sys\nimport math\nimport fpectl\ntry:\nprint 'Control off:', math.exp(700)\nfpectl.turnon_sigfpe()\nprint 'Control on:', math.exp(1000)\nexcept Exception as e:\nprint e\nprint sys.exc_type\n"
},
{
"code": null,
"e": 1772,
"s": 1677,
"text": "Control off: 1.01423205474e+304\nControl on: in math_1\n<type 'exceptions.FloatingPointError'>\n\n"
}
] |
Graph and its representations
|
07 May, 2022
A graph is a data structure that consists of the following two components: 1. A finite set of vertices also called as nodes. 2. A finite set of ordered pair of the form (u, v) called as edge. The pair is ordered because (u, v) is not the same as (v, u) in case of a directed graph(di-graph). The pair of the form (u, v) indicates that there is an edge from vertex u to vertex v. The edges may contain weight/value/cost.Graphs are used to represent many real-life applications: Graphs are used to represent networks. The networks may include paths in a city or telephone network or circuit network. Graphs are also used in social networks like linkedIn, Facebook. For example, in Facebook, each person is represented with a vertex(or node). Each node is a structure and contains information like person id, name, gender, and locale. See this for more applications of graph. Following is an example of an undirected graph with 5 vertices.
The following two are the most commonly used representations of a graph. 1. Adjacency Matrix 2. Adjacency List There are other representations also like, Incidence Matrix and Incidence List. The choice of graph representation is situation-specific. It totally depends on the type of operations to be performed and ease of use. Adjacency Matrix: Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j. Adjacency matrix for undirected graph is always symmetric. Adjacency Matrix is also used to represent weighted graphs. If adj[i][j] = w, then there is an edge from vertex i to vertex j with weight w.
The adjacency matrix for the above example graph is:
Pros: Representation is easier to implement and follow. Removing an edge takes O(1) time. Queries like whether there is an edge from vertex ‘u’ to vertex ‘v’ are efficient and can be done O(1).Cons: Consumes more space O(V^2). Even if the graph is sparse(contains less number of edges), it consumes the same space. Adding a vertex is O(V^2) time. Computing all neighbors of a vertex takes O(V) time (Not efficient).Please see this for a sample Python implementation of adjacency matrix.
Implementation of taking input for adjacency matrix
C++
#include <iostream>using namespace std; int main(){ // n is the number of vertices // m is the number of edges int n, m; cin >> n >> m ; int adjMat[n + 1][n + 1]; for(int i = 0; i < m; i++){ int u , v ; cin >> u >> v ; adjMat[u][v] = 1 ; adjMat[v][u] = 1 ; } return 0;}
Adjacency List: An array of lists is used. The size of the array is equal to the number of vertices. Let the array be an array[]. An entry array[i] represents the list of vertices adjacent to the ith vertex. This representation can also be used to represent a weighted graph. The weights of edges can be represented as lists of pairs. Following is the adjacency list representation of the above graph.
Note that in the below implementation, we use dynamic arrays (vector in C++/ArrayList in Java) to represent adjacency lists instead of the linked list. The vector implementation has advantages of cache friendliness.
C++
C
Java
Python3
C#
Javascript
// A simple representation of graph using STL#include <bits/stdc++.h>using namespace std; // A utility function to add an edge in an// undirected graph.void addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // A utility function to print the adjacency list// representation of graphvoid printGraph(vector<int> adj[], int V){ for (int v = 0; v < V; ++v) { cout << "\n Adjacency list of vertex " << v << "\n head "; for (auto x : adj[v]) cout << "-> " << x; printf("\n"); }} // Driver codeint main(){ int V = 5; vector<int> adj[V]; addEdge(adj, 0, 1); addEdge(adj, 0, 4); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 3); addEdge(adj, 3, 4); printGraph(adj, V); return 0;}
// A C Program to demonstrate adjacency list// representation of graphs#include <stdio.h>#include <stdlib.h> // A structure to represent an adjacency list nodestruct AdjListNode { int dest; struct AdjListNode* next;}; // A structure to represent an adjacency liststruct AdjList { struct AdjListNode* head;}; // A structure to represent a graph. A graph// is an array of adjacency lists.// Size of array will be V (number of vertices// in graph)struct Graph { int V; struct AdjList* array;}; // A utility function to create a new adjacency list nodestruct AdjListNode* newAdjListNode(int dest){ struct AdjListNode* newNode = (struct AdjListNode*)malloc( sizeof(struct AdjListNode)); newNode->dest = dest; newNode->next = NULL; return newNode;} // A utility function that creates a graph of V verticesstruct Graph* createGraph(int V){ struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph)); graph->V = V; // Create an array of adjacency lists. Size of // array will be V graph->array = (struct AdjList*)malloc( V * sizeof(struct AdjList)); // Initialize each adjacency list as empty by // making head as NULL int i; for (i = 0; i < V; ++i) graph->array[i].head = NULL; return graph;} // Adds an edge to an undirected graphvoid addEdge(struct Graph* graph, int src, int dest){ // Add an edge from src to dest. A new node is // added to the adjacency list of src. The node // is added at the beginning struct AdjListNode* check = NULL; struct AdjListNode* newNode = newAdjListNode(dest); if (graph->array[src].head == NULL) { newNode->next = graph->array[src].head; graph->array[src].head = newNode; } else { check = graph->array[src].head; while (check->next != NULL) { check = check->next; } // graph->array[src].head = newNode; check->next = newNode; } // Since graph is undirected, add an edge from // dest to src also newNode = newAdjListNode(src); if (graph->array[dest].head == NULL) { newNode->next = graph->array[dest].head; graph->array[dest].head = newNode; } else { check = graph->array[dest].head; while (check->next != NULL) { check = check->next; } check->next = newNode; } // newNode = newAdjListNode(src); // newNode->next = graph->array[dest].head; // graph->array[dest].head = newNode;} // A utility function to print the adjacency list// representation of graphvoid printGraph(struct Graph* graph){ int v; for (v = 0; v < graph->V; ++v) { struct AdjListNode* pCrawl = graph->array[v].head; printf("\n Adjacency list of vertex %d\n head ", v); while (pCrawl) { printf("-> %d", pCrawl->dest); pCrawl = pCrawl->next; } printf("\n"); }} // Driver program to test above functionsint main(){ // create the graph given in above fugure int V = 5; struct Graph* graph = createGraph(V); addEdge(graph, 0, 1); addEdge(graph, 0, 4); addEdge(graph, 1, 2); addEdge(graph, 1, 3); addEdge(graph, 1, 4); addEdge(graph, 2, 3); addEdge(graph, 3, 4); // print the adjacency list representation of the above // graph printGraph(graph); return 0;}
// Java code to demonstrate Graph representation// using ArrayList in Java import java.util.*; class Graph { // A utility function to add an edge in an // undirected graph static void addEdge(ArrayList<ArrayList<Integer> > adj, int u, int v) { adj.get(u).add(v); adj.get(v).add(u); } // A utility function to print the adjacency list // representation of graph static void printGraph(ArrayList<ArrayList<Integer> > adj) { for (int i = 0; i < adj.size(); i++) { System.out.println("\nAdjacency list of vertex" + i); System.out.print("head"); for (int j = 0; j < adj.get(i).size(); j++) { System.out.print(" -> " + adj.get(i).get(j)); } System.out.println(); } } // Driver Code public static void main(String[] args) { // Creating a graph with 5 vertices int V = 5; ArrayList<ArrayList<Integer> > adj = new ArrayList<ArrayList<Integer> >(V); for (int i = 0; i < V; i++) adj.add(new ArrayList<Integer>()); // Adding edges one by one addEdge(adj, 0, 1); addEdge(adj, 0, 4); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 3); addEdge(adj, 3, 4); printGraph(adj); }}
"""A Python program to demonstrate the adjacencylist representation of the graph""" # A class to represent the adjacency list of the node class AdjNode: def __init__(self, data): self.vertex = data self.next = None # A class to represent a graph. A graph# is the list of the adjacency lists.# Size of the array will be the no. of the# vertices "V"class Graph: def __init__(self, vertices): self.V = vertices self.graph = [None] * self.V # Function to add an edge in an undirected graph def add_edge(self, src, dest): # Adding the node to the source node node = AdjNode(dest) node.next = self.graph[src] self.graph[src] = node # Adding the source node to the destination as # it is the undirected graph node = AdjNode(src) node.next = self.graph[dest] self.graph[dest] = node # Function to print the graph def print_graph(self): for i in range(self.V): print("Adjacency list of vertex {}\n head".format(i), end="") temp = self.graph[i] while temp: print(" -> {}".format(temp.vertex), end="") temp = temp.next print(" \n") # Driver program to the above graph classif __name__ == "__main__": V = 5 graph = Graph(V) graph.add_edge(0, 1) graph.add_edge(0, 4) graph.add_edge(1, 2) graph.add_edge(1, 3) graph.add_edge(1, 4) graph.add_edge(2, 3) graph.add_edge(3, 4) graph.print_graph() # This code is contributed by Kanav Malhotra
// C# code to demonstrate Graph representation// using LinkedList in C#using System;using System.Collections.Generic; class Graph { // A utility function to add an edge in an // undirected graph static void addEdge(LinkedList<int>[] adj, int u, int v) { adj[u].AddLast(v); adj[v].AddLast(u); } // A utility function to print the adjacency list // representation of graph static void printGraph(LinkedList<int>[] adj) { for (int i = 0; i < adj.Length; i++) { Console.WriteLine("\nAdjacency list of vertex " + i); Console.Write("head"); foreach(var item in adj[i]) { Console.Write(" -> " + item); } Console.WriteLine(); } } // Driver Code public static void Main(String[] args) { // Creating a graph with 5 vertices int V = 5; LinkedList<int>[] adj = new LinkedList<int>[ V ]; for (int i = 0; i < V; i++) adj[i] = new LinkedList<int>(); // Adding edges one by one addEdge(adj, 0, 1); addEdge(adj, 0, 4); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 3); addEdge(adj, 3, 4); printGraph(adj); Console.ReadKey(); }} // This code is contributed by techno2mahi
<script>// Javascript code to demonstrate Graph representation// using ArrayList in Java // A utility function to add an edge in an // undirected graphfunction addEdge(adj,u,v){ adj[u].push(v); adj[v].push(u);} // A utility function to print the adjacency list // representation of graphfunction printGraph(adj){ for (let i = 0; i < adj.length; i++) { document.write("<br>Adjacency list of vertex" + i+"<br>"); document.write("head"); for (let j = 0; j < adj[i].length; j++) { document.write(" -> "+adj[i][j]); } document.write("<br>"); }} // Driver Code// Creating a graph with 5 vertices let V = 5; let adj= []; for (let i = 0; i < V; i++) adj.push([]); // Adding edges one by one addEdge(adj, 0, 1); addEdge(adj, 0, 4); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 3); addEdge(adj, 3, 4); printGraph(adj); // This code is contributed by avanitrachhadiya2155</script>
Adjacency list of vertex 0
head -> 1-> 4
Adjacency list of vertex 1
head -> 0-> 2-> 3-> 4
Adjacency list of vertex 2
head -> 1-> 3
Adjacency list of vertex 3
head -> 1-> 2-> 4
Adjacency list of vertex 4
head -> 0-> 1-> 3
Pros: Saves space O(|V|+|E|) . In the worst case, there can be C(V, 2) number of edges in a graph thus consuming O(V^2) space. Adding a vertex is easier. Computing all neighbors of a vertex takes optimal time.Cons: Queries like whether there is an edge from vertex u to vertex v are not efficient and can be done O(V). In Real-life problems, graphs are sparse(|E| <<|V|2). That’s why adjacency lists Data structure is commonly used for storing graphs. Adjacency matrix will enforce (|V|2) bound on time complexity for such algorithms.
Graph and its representations | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersGraph and its representations | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 10:41•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=1n5XPFcvxds" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Reference: http://en.wikipedia.org/wiki/Graph_%28abstract_data_type%29Related Post: Graph representation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected) Graph implementation using STL for competitive programming | Set 2 (Weighted graph)This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
RajatSinghal
kanavMalhotra
avsharma
Viru_UIC
techno2mahi
nailwalhimanshu
Akanksha_Rai
shariulakab1
avanitrachhadiya2155
shubamkoul009
manojtomer0709
prasanna1995
harendrakumar123
kapilag
graph-basics
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 May, 2022"
},
{
"code": null,
"e": 991,
"s": 52,
"text": "A graph is a data structure that consists of the following two components: 1. A finite set of vertices also called as nodes. 2. A finite set of ordered pair of the form (u, v) called as edge. The pair is ordered because (u, v) is not the same as (v, u) in case of a directed graph(di-graph). The pair of the form (u, v) indicates that there is an edge from vertex u to vertex v. The edges may contain weight/value/cost.Graphs are used to represent many real-life applications: Graphs are used to represent networks. The networks may include paths in a city or telephone network or circuit network. Graphs are also used in social networks like linkedIn, Facebook. For example, in Facebook, each person is represented with a vertex(or node). Each node is a structure and contains information like person id, name, gender, and locale. See this for more applications of graph. Following is an example of an undirected graph with 5 vertices. "
},
{
"code": null,
"e": 1737,
"s": 991,
"text": "The following two are the most commonly used representations of a graph. 1. Adjacency Matrix 2. Adjacency List There are other representations also like, Incidence Matrix and Incidence List. The choice of graph representation is situation-specific. It totally depends on the type of operations to be performed and ease of use. Adjacency Matrix: Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j. Adjacency matrix for undirected graph is always symmetric. Adjacency Matrix is also used to represent weighted graphs. If adj[i][j] = w, then there is an edge from vertex i to vertex j with weight w. "
},
{
"code": null,
"e": 1792,
"s": 1737,
"text": "The adjacency matrix for the above example graph is: "
},
{
"code": null,
"e": 2280,
"s": 1792,
"text": "Pros: Representation is easier to implement and follow. Removing an edge takes O(1) time. Queries like whether there is an edge from vertex ‘u’ to vertex ‘v’ are efficient and can be done O(1).Cons: Consumes more space O(V^2). Even if the graph is sparse(contains less number of edges), it consumes the same space. Adding a vertex is O(V^2) time. Computing all neighbors of a vertex takes O(V) time (Not efficient).Please see this for a sample Python implementation of adjacency matrix."
},
{
"code": null,
"e": 2332,
"s": 2280,
"text": "Implementation of taking input for adjacency matrix"
},
{
"code": null,
"e": 2336,
"s": 2332,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; int main(){ // n is the number of vertices // m is the number of edges int n, m; cin >> n >> m ; int adjMat[n + 1][n + 1]; for(int i = 0; i < m; i++){ int u , v ; cin >> u >> v ; adjMat[u][v] = 1 ; adjMat[v][u] = 1 ; } return 0;}",
"e": 2670,
"s": 2336,
"text": null
},
{
"code": null,
"e": 3074,
"s": 2670,
"text": "Adjacency List: An array of lists is used. The size of the array is equal to the number of vertices. Let the array be an array[]. An entry array[i] represents the list of vertices adjacent to the ith vertex. This representation can also be used to represent a weighted graph. The weights of edges can be represented as lists of pairs. Following is the adjacency list representation of the above graph. "
},
{
"code": null,
"e": 3294,
"s": 3076,
"text": "Note that in the below implementation, we use dynamic arrays (vector in C++/ArrayList in Java) to represent adjacency lists instead of the linked list. The vector implementation has advantages of cache friendliness. "
},
{
"code": null,
"e": 3298,
"s": 3294,
"text": "C++"
},
{
"code": null,
"e": 3300,
"s": 3298,
"text": "C"
},
{
"code": null,
"e": 3305,
"s": 3300,
"text": "Java"
},
{
"code": null,
"e": 3313,
"s": 3305,
"text": "Python3"
},
{
"code": null,
"e": 3316,
"s": 3313,
"text": "C#"
},
{
"code": null,
"e": 3327,
"s": 3316,
"text": "Javascript"
},
{
"code": "// A simple representation of graph using STL#include <bits/stdc++.h>using namespace std; // A utility function to add an edge in an// undirected graph.void addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // A utility function to print the adjacency list// representation of graphvoid printGraph(vector<int> adj[], int V){ for (int v = 0; v < V; ++v) { cout << \"\\n Adjacency list of vertex \" << v << \"\\n head \"; for (auto x : adj[v]) cout << \"-> \" << x; printf(\"\\n\"); }} // Driver codeint main(){ int V = 5; vector<int> adj[V]; addEdge(adj, 0, 1); addEdge(adj, 0, 4); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 3); addEdge(adj, 3, 4); printGraph(adj, V); return 0;}",
"e": 4152,
"s": 3327,
"text": null
},
{
"code": "// A C Program to demonstrate adjacency list// representation of graphs#include <stdio.h>#include <stdlib.h> // A structure to represent an adjacency list nodestruct AdjListNode { int dest; struct AdjListNode* next;}; // A structure to represent an adjacency liststruct AdjList { struct AdjListNode* head;}; // A structure to represent a graph. A graph// is an array of adjacency lists.// Size of array will be V (number of vertices// in graph)struct Graph { int V; struct AdjList* array;}; // A utility function to create a new adjacency list nodestruct AdjListNode* newAdjListNode(int dest){ struct AdjListNode* newNode = (struct AdjListNode*)malloc( sizeof(struct AdjListNode)); newNode->dest = dest; newNode->next = NULL; return newNode;} // A utility function that creates a graph of V verticesstruct Graph* createGraph(int V){ struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph)); graph->V = V; // Create an array of adjacency lists. Size of // array will be V graph->array = (struct AdjList*)malloc( V * sizeof(struct AdjList)); // Initialize each adjacency list as empty by // making head as NULL int i; for (i = 0; i < V; ++i) graph->array[i].head = NULL; return graph;} // Adds an edge to an undirected graphvoid addEdge(struct Graph* graph, int src, int dest){ // Add an edge from src to dest. A new node is // added to the adjacency list of src. The node // is added at the beginning struct AdjListNode* check = NULL; struct AdjListNode* newNode = newAdjListNode(dest); if (graph->array[src].head == NULL) { newNode->next = graph->array[src].head; graph->array[src].head = newNode; } else { check = graph->array[src].head; while (check->next != NULL) { check = check->next; } // graph->array[src].head = newNode; check->next = newNode; } // Since graph is undirected, add an edge from // dest to src also newNode = newAdjListNode(src); if (graph->array[dest].head == NULL) { newNode->next = graph->array[dest].head; graph->array[dest].head = newNode; } else { check = graph->array[dest].head; while (check->next != NULL) { check = check->next; } check->next = newNode; } // newNode = newAdjListNode(src); // newNode->next = graph->array[dest].head; // graph->array[dest].head = newNode;} // A utility function to print the adjacency list// representation of graphvoid printGraph(struct Graph* graph){ int v; for (v = 0; v < graph->V; ++v) { struct AdjListNode* pCrawl = graph->array[v].head; printf(\"\\n Adjacency list of vertex %d\\n head \", v); while (pCrawl) { printf(\"-> %d\", pCrawl->dest); pCrawl = pCrawl->next; } printf(\"\\n\"); }} // Driver program to test above functionsint main(){ // create the graph given in above fugure int V = 5; struct Graph* graph = createGraph(V); addEdge(graph, 0, 1); addEdge(graph, 0, 4); addEdge(graph, 1, 2); addEdge(graph, 1, 3); addEdge(graph, 1, 4); addEdge(graph, 2, 3); addEdge(graph, 3, 4); // print the adjacency list representation of the above // graph printGraph(graph); return 0;}",
"e": 7491,
"s": 4152,
"text": null
},
{
"code": "// Java code to demonstrate Graph representation// using ArrayList in Java import java.util.*; class Graph { // A utility function to add an edge in an // undirected graph static void addEdge(ArrayList<ArrayList<Integer> > adj, int u, int v) { adj.get(u).add(v); adj.get(v).add(u); } // A utility function to print the adjacency list // representation of graph static void printGraph(ArrayList<ArrayList<Integer> > adj) { for (int i = 0; i < adj.size(); i++) { System.out.println(\"\\nAdjacency list of vertex\" + i); System.out.print(\"head\"); for (int j = 0; j < adj.get(i).size(); j++) { System.out.print(\" -> \" + adj.get(i).get(j)); } System.out.println(); } } // Driver Code public static void main(String[] args) { // Creating a graph with 5 vertices int V = 5; ArrayList<ArrayList<Integer> > adj = new ArrayList<ArrayList<Integer> >(V); for (int i = 0; i < V; i++) adj.add(new ArrayList<Integer>()); // Adding edges one by one addEdge(adj, 0, 1); addEdge(adj, 0, 4); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 3); addEdge(adj, 3, 4); printGraph(adj); }}",
"e": 8928,
"s": 7491,
"text": null
},
{
"code": "\"\"\"A Python program to demonstrate the adjacencylist representation of the graph\"\"\" # A class to represent the adjacency list of the node class AdjNode: def __init__(self, data): self.vertex = data self.next = None # A class to represent a graph. A graph# is the list of the adjacency lists.# Size of the array will be the no. of the# vertices \"V\"class Graph: def __init__(self, vertices): self.V = vertices self.graph = [None] * self.V # Function to add an edge in an undirected graph def add_edge(self, src, dest): # Adding the node to the source node node = AdjNode(dest) node.next = self.graph[src] self.graph[src] = node # Adding the source node to the destination as # it is the undirected graph node = AdjNode(src) node.next = self.graph[dest] self.graph[dest] = node # Function to print the graph def print_graph(self): for i in range(self.V): print(\"Adjacency list of vertex {}\\n head\".format(i), end=\"\") temp = self.graph[i] while temp: print(\" -> {}\".format(temp.vertex), end=\"\") temp = temp.next print(\" \\n\") # Driver program to the above graph classif __name__ == \"__main__\": V = 5 graph = Graph(V) graph.add_edge(0, 1) graph.add_edge(0, 4) graph.add_edge(1, 2) graph.add_edge(1, 3) graph.add_edge(1, 4) graph.add_edge(2, 3) graph.add_edge(3, 4) graph.print_graph() # This code is contributed by Kanav Malhotra",
"e": 10479,
"s": 8928,
"text": null
},
{
"code": "// C# code to demonstrate Graph representation// using LinkedList in C#using System;using System.Collections.Generic; class Graph { // A utility function to add an edge in an // undirected graph static void addEdge(LinkedList<int>[] adj, int u, int v) { adj[u].AddLast(v); adj[v].AddLast(u); } // A utility function to print the adjacency list // representation of graph static void printGraph(LinkedList<int>[] adj) { for (int i = 0; i < adj.Length; i++) { Console.WriteLine(\"\\nAdjacency list of vertex \" + i); Console.Write(\"head\"); foreach(var item in adj[i]) { Console.Write(\" -> \" + item); } Console.WriteLine(); } } // Driver Code public static void Main(String[] args) { // Creating a graph with 5 vertices int V = 5; LinkedList<int>[] adj = new LinkedList<int>[ V ]; for (int i = 0; i < V; i++) adj[i] = new LinkedList<int>(); // Adding edges one by one addEdge(adj, 0, 1); addEdge(adj, 0, 4); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 3); addEdge(adj, 3, 4); printGraph(adj); Console.ReadKey(); }} // This code is contributed by techno2mahi",
"e": 11859,
"s": 10479,
"text": null
},
{
"code": "<script>// Javascript code to demonstrate Graph representation// using ArrayList in Java // A utility function to add an edge in an // undirected graphfunction addEdge(adj,u,v){ adj[u].push(v); adj[v].push(u);} // A utility function to print the adjacency list // representation of graphfunction printGraph(adj){ for (let i = 0; i < adj.length; i++) { document.write(\"<br>Adjacency list of vertex\" + i+\"<br>\"); document.write(\"head\"); for (let j = 0; j < adj[i].length; j++) { document.write(\" -> \"+adj[i][j]); } document.write(\"<br>\"); }} // Driver Code// Creating a graph with 5 vertices let V = 5; let adj= []; for (let i = 0; i < V; i++) adj.push([]); // Adding edges one by one addEdge(adj, 0, 1); addEdge(adj, 0, 4); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 3); addEdge(adj, 3, 4); printGraph(adj); // This code is contributed by avanitrachhadiya2155</script>",
"e": 12974,
"s": 11859,
"text": null
},
{
"code": null,
"e": 13209,
"s": 12974,
"text": " Adjacency list of vertex 0\n head -> 1-> 4\n\n Adjacency list of vertex 1\n head -> 0-> 2-> 3-> 4\n\n Adjacency list of vertex 2\n head -> 1-> 3\n\n Adjacency list of vertex 3\n head -> 1-> 2-> 4\n\n Adjacency list of vertex 4\n head -> 0-> 1-> 3"
},
{
"code": null,
"e": 13746,
"s": 13209,
"text": "Pros: Saves space O(|V|+|E|) . In the worst case, there can be C(V, 2) number of edges in a graph thus consuming O(V^2) space. Adding a vertex is easier. Computing all neighbors of a vertex takes optimal time.Cons: Queries like whether there is an edge from vertex u to vertex v are not efficient and can be done O(V). In Real-life problems, graphs are sparse(|E| <<|V|2). That’s why adjacency lists Data structure is commonly used for storing graphs. Adjacency matrix will enforce (|V|2) bound on time complexity for such algorithms. "
},
{
"code": null,
"e": 14623,
"s": 13746,
"text": "Graph and its representations | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersGraph and its representations | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 10:41•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=1n5XPFcvxds\" 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": 15098,
"s": 14623,
"text": "Reference: http://en.wikipedia.org/wiki/Graph_%28abstract_data_type%29Related Post: Graph representation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected) Graph implementation using STL for competitive programming | Set 2 (Weighted graph)This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 15111,
"s": 15098,
"text": "RajatSinghal"
},
{
"code": null,
"e": 15125,
"s": 15111,
"text": "kanavMalhotra"
},
{
"code": null,
"e": 15134,
"s": 15125,
"text": "avsharma"
},
{
"code": null,
"e": 15143,
"s": 15134,
"text": "Viru_UIC"
},
{
"code": null,
"e": 15155,
"s": 15143,
"text": "techno2mahi"
},
{
"code": null,
"e": 15171,
"s": 15155,
"text": "nailwalhimanshu"
},
{
"code": null,
"e": 15184,
"s": 15171,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 15197,
"s": 15184,
"text": "shariulakab1"
},
{
"code": null,
"e": 15218,
"s": 15197,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 15232,
"s": 15218,
"text": "shubamkoul009"
},
{
"code": null,
"e": 15247,
"s": 15232,
"text": "manojtomer0709"
},
{
"code": null,
"e": 15260,
"s": 15247,
"text": "prasanna1995"
},
{
"code": null,
"e": 15277,
"s": 15260,
"text": "harendrakumar123"
},
{
"code": null,
"e": 15285,
"s": 15277,
"text": "kapilag"
},
{
"code": null,
"e": 15298,
"s": 15285,
"text": "graph-basics"
},
{
"code": null,
"e": 15304,
"s": 15298,
"text": "Graph"
},
{
"code": null,
"e": 15310,
"s": 15304,
"text": "Graph"
}
] |
Number of ways to insert two pairs of parentheses into a string of N characters - GeeksforGeeks
|
10 Mar, 2022
Given a string str of length N, the task is to find the number of ways to insert only 2 pairs of parentheses into the given string such that the resultant string is still valid.Examples:
Input: str = “ab” Output: 6 ((a))b, ((a)b), ((ab)), (a)(b), (a(b)), a((b)) which are a total of 6 ways.Input: str = “aab” Output: 20
Approach: it can be observed that for the lengths of the string 1, 2, 3, ..., N a series will be formed as 1, 6, 20, 50, 105, 196, 336, 540, ... whose Nth term is (N + 1)2 * ((N + 1)2 – 1) / 12.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of ways// to insert the bracket pairsint cntWays(string str, int n){ int x = n + 1; int ways = x * x * (x * x - 1) / 12; return ways;} // Driver codeint main(){ string str = "ab"; int n = str.length(); cout << cntWays(str, n); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the number of ways// to insert the bracket pairsstatic int cntWays(String str, int n){ int x = n + 1; int ways = x * x * (x * x - 1) / 12; return ways;} // Driver codepublic static void main(String []args){ String str = "ab"; int n = str.length(); System.out.println(cntWays(str, n));}} // This code is contributed by Rajput-Ji
# Python3 implementation of the approach # Function to return the number of ways# to insert the bracket pairsdef cntWays(string, n) : x = n + 1; ways = x * x * (x * x - 1) // 12; return ways; # Driver codeif __name__ == "__main__" : string = "ab"; n = len(string); print(cntWays(string, n)); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{ // Function to return the number of ways// to insert the bracket pairsstatic int cntWays(String str, int n){ int x = n + 1; int ways = x * x * (x * x - 1) / 12; return ways;} // Driver codepublic static void Main(String []args){ String str = "ab"; int n = str.Length; Console.WriteLine(cntWays(str, n));}} // This code is contributed by Rajput-Ji
<script> // Javascript implementation of the approach // Function to return the number of ways// to insert the bracket pairsfunction cntWays(str, n){ var x = n + 1; var ways = x * x * (x * x - 1) / 12; return ways;} // Driver codevar str = "ab";var n = str.length;document.write(cntWays(str, n)); // This code is contributed by rutvik_56.</script>
6
Time Complexity: O(1)
Auxiliary Space: O(1)
ankthon
Rajput-Ji
rutvik_56
subhammahato348
Parentheses-Problems
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Program to add two binary strings
Fizz Buzz Implementation
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 24301,
"s": 24273,
"text": "\n10 Mar, 2022"
},
{
"code": null,
"e": 24490,
"s": 24301,
"text": "Given a string str of length N, the task is to find the number of ways to insert only 2 pairs of parentheses into the given string such that the resultant string is still valid.Examples: "
},
{
"code": null,
"e": 24625,
"s": 24490,
"text": "Input: str = “ab” Output: 6 ((a))b, ((a)b), ((ab)), (a)(b), (a(b)), a((b)) which are a total of 6 ways.Input: str = “aab” Output: 20 "
},
{
"code": null,
"e": 24874,
"s": 24627,
"text": "Approach: it can be observed that for the lengths of the string 1, 2, 3, ..., N a series will be formed as 1, 6, 20, 50, 105, 196, 336, 540, ... whose Nth term is (N + 1)2 * ((N + 1)2 – 1) / 12.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 24878,
"s": 24874,
"text": "C++"
},
{
"code": null,
"e": 24883,
"s": 24878,
"text": "Java"
},
{
"code": null,
"e": 24891,
"s": 24883,
"text": "Python3"
},
{
"code": null,
"e": 24894,
"s": 24891,
"text": "C#"
},
{
"code": null,
"e": 24905,
"s": 24894,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of ways// to insert the bracket pairsint cntWays(string str, int n){ int x = n + 1; int ways = x * x * (x * x - 1) / 12; return ways;} // Driver codeint main(){ string str = \"ab\"; int n = str.length(); cout << cntWays(str, n); return 0;}",
"e": 25281,
"s": 24905,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the number of ways// to insert the bracket pairsstatic int cntWays(String str, int n){ int x = n + 1; int ways = x * x * (x * x - 1) / 12; return ways;} // Driver codepublic static void main(String []args){ String str = \"ab\"; int n = str.length(); System.out.println(cntWays(str, n));}} // This code is contributed by Rajput-Ji",
"e": 25719,
"s": 25281,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the number of ways# to insert the bracket pairsdef cntWays(string, n) : x = n + 1; ways = x * x * (x * x - 1) // 12; return ways; # Driver codeif __name__ == \"__main__\" : string = \"ab\"; n = len(string); print(cntWays(string, n)); # This code is contributed by AnkitRai01",
"e": 26073,
"s": 25719,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the number of ways// to insert the bracket pairsstatic int cntWays(String str, int n){ int x = n + 1; int ways = x * x * (x * x - 1) / 12; return ways;} // Driver codepublic static void Main(String []args){ String str = \"ab\"; int n = str.Length; Console.WriteLine(cntWays(str, n));}} // This code is contributed by Rajput-Ji",
"e": 26504,
"s": 26073,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the number of ways// to insert the bracket pairsfunction cntWays(str, n){ var x = n + 1; var ways = x * x * (x * x - 1) / 12; return ways;} // Driver codevar str = \"ab\";var n = str.length;document.write(cntWays(str, n)); // This code is contributed by rutvik_56.</script>",
"e": 26861,
"s": 26504,
"text": null
},
{
"code": null,
"e": 26863,
"s": 26861,
"text": "6"
},
{
"code": null,
"e": 26887,
"s": 26865,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 26909,
"s": 26887,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 26917,
"s": 26909,
"text": "ankthon"
},
{
"code": null,
"e": 26927,
"s": 26917,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 26937,
"s": 26927,
"text": "rutvik_56"
},
{
"code": null,
"e": 26953,
"s": 26937,
"text": "subhammahato348"
},
{
"code": null,
"e": 26974,
"s": 26953,
"text": "Parentheses-Problems"
},
{
"code": null,
"e": 26987,
"s": 26974,
"text": "Mathematical"
},
{
"code": null,
"e": 26995,
"s": 26987,
"text": "Strings"
},
{
"code": null,
"e": 27003,
"s": 26995,
"text": "Strings"
},
{
"code": null,
"e": 27016,
"s": 27003,
"text": "Mathematical"
},
{
"code": null,
"e": 27114,
"s": 27016,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27123,
"s": 27114,
"text": "Comments"
},
{
"code": null,
"e": 27136,
"s": 27123,
"text": "Old Comments"
},
{
"code": null,
"e": 27181,
"s": 27136,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 27213,
"s": 27181,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 27257,
"s": 27213,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 27291,
"s": 27257,
"text": "Program to add two binary strings"
},
{
"code": null,
"e": 27316,
"s": 27291,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 27341,
"s": 27316,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 27387,
"s": 27341,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 27421,
"s": 27387,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 27478,
"s": 27421,
"text": "Python program to check if a string is palindrome or not"
}
] |
Python Program to Flatten a Nested List using Recursion
|
When it is required to flatten a given nested list using recursion technique, simple indexing, and the ‘isinstance’ method can be used along with recursion.
The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem.
Below is a demonstration for the same −
Live Demo
def flatten_list(my_list):
if my_list == []:
return my_list
if isinstance(my_list[0], list):
return flatten_list(my_list[0]) + flatten_list(my_list[1:])
return my_list[:1] + flatten_list(my_list[1:])
my_list = [[1,2],[3,4], [90, 11], [56, 78], [[34,56]]]
print("The list is :")
print(my_list)
print("The list after flattening is : ")
print(flatten_list(my_list))
The list is :
[[1, 2], [3, 4], [90, 11], [56, 78], [[34, 56]]]
The list after flattening is :
[1, 2, 3, 4, 90, 11, 56, 78, 34, 56]
A method named ‘flatten_list’ is defined, that takes a list as parameter.
It checks to see the data type of the first element in the list.
If it matches to a list, then, the first element along with the second element to last element is concatenated and displayed.
This results in a nested list being flattened.
Otherwise, the first element is left out, and the list is first reversed and the normal list is combined, and returned as output.
Outside the function, a nested list is defined, and is displayed on the console.
The method is called by passing the list as parameter.
The output is displayed on the console.
|
[
{
"code": null,
"e": 1219,
"s": 1062,
"text": "When it is required to flatten a given nested list using recursion technique, simple indexing, and the ‘isinstance’ method can be used along with recursion."
},
{
"code": null,
"e": 1354,
"s": 1219,
"text": "The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem."
},
{
"code": null,
"e": 1394,
"s": 1354,
"text": "Below is a demonstration for the same −"
},
{
"code": null,
"e": 1405,
"s": 1394,
"text": " Live Demo"
},
{
"code": null,
"e": 1789,
"s": 1405,
"text": "def flatten_list(my_list):\n if my_list == []:\n return my_list\n if isinstance(my_list[0], list):\n return flatten_list(my_list[0]) + flatten_list(my_list[1:])\n return my_list[:1] + flatten_list(my_list[1:])\nmy_list = [[1,2],[3,4], [90, 11], [56, 78], [[34,56]]]\nprint(\"The list is :\")\nprint(my_list)\nprint(\"The list after flattening is : \")\nprint(flatten_list(my_list))"
},
{
"code": null,
"e": 1920,
"s": 1789,
"text": "The list is :\n[[1, 2], [3, 4], [90, 11], [56, 78], [[34, 56]]]\nThe list after flattening is :\n[1, 2, 3, 4, 90, 11, 56, 78, 34, 56]"
},
{
"code": null,
"e": 1994,
"s": 1920,
"text": "A method named ‘flatten_list’ is defined, that takes a list as parameter."
},
{
"code": null,
"e": 2059,
"s": 1994,
"text": "It checks to see the data type of the first element in the list."
},
{
"code": null,
"e": 2185,
"s": 2059,
"text": "If it matches to a list, then, the first element along with the second element to last element is concatenated and displayed."
},
{
"code": null,
"e": 2232,
"s": 2185,
"text": "This results in a nested list being flattened."
},
{
"code": null,
"e": 2362,
"s": 2232,
"text": "Otherwise, the first element is left out, and the list is first reversed and the normal list is combined, and returned as output."
},
{
"code": null,
"e": 2443,
"s": 2362,
"text": "Outside the function, a nested list is defined, and is displayed on the console."
},
{
"code": null,
"e": 2498,
"s": 2443,
"text": "The method is called by passing the list as parameter."
},
{
"code": null,
"e": 2538,
"s": 2498,
"text": "The output is displayed on the console."
}
] |
How to deal with reusable components in Selenium Java?
|
We can deal with reusable components in Selenium Java with the help of inheritance concept. It is a parent child relationship where the child class inherits the properties and methods of the parent class.
For Parent class.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Baseclass {
public void login() throws IOException {
Properties prop = new Properties();
//Reading values from property file
FileInputStream ips = new FileInputStream(
"C:\\Users\\ghs6kor\\eclipse- workspace\\Inheritance\\config.properties");
prop.load(ips);
System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get(prop.getProperty("url"));
}
}
For Child class.
import java.io.IOException;
public class Child extends Baseclass {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Child c = new Child();
c.login();
c.testinheritance();
}
public void testinheritance() {
// parent class method used in child class
login();
System.out.println("Test Inheritance");
}
}
|
[
{
"code": null,
"e": 1267,
"s": 1062,
"text": "We can deal with reusable components in Selenium Java with the help of inheritance concept. It is a parent child relationship where the child class inherits the properties and methods of the parent class."
},
{
"code": null,
"e": 1285,
"s": 1267,
"text": "For Parent class."
},
{
"code": null,
"e": 2052,
"s": 1285,
"text": "import java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.Properties;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.firefox.FirefoxDriver;\npublic class Baseclass {\n public void login() throws IOException {\n Properties prop = new Properties();\n //Reading values from property file\n FileInputStream ips = new FileInputStream(\n \"C:\\\\Users\\\\ghs6kor\\\\eclipse- workspace\\\\Inheritance\\\\config.properties\");\n prop.load(ips);\n System.setProperty(\"webdriver.gecko.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n driver.get(prop.getProperty(\"url\"));\n }\n}"
},
{
"code": null,
"e": 2069,
"s": 2052,
"text": "For Child class."
},
{
"code": null,
"e": 2470,
"s": 2069,
"text": "import java.io.IOException;\npublic class Child extends Baseclass {\n public static void main(String[] args) throws IOException {\n // TODO Auto-generated method stub\n Child c = new Child();\n c.login();\n c.testinheritance();\n }\n public void testinheritance() {\n // parent class method used in child class\n login();\n System.out.println(\"Test Inheritance\");\n }\n}"
}
] |
Predicting video game hits with Machine Learning | by Ignacio Chavarria | Towards Data Science
|
The following four heatmaps show how game sales vary according to critic scores, which are split into six scoring groups. Additionally, each heatmap segments the data further by one of the following features: genre, developer, publisher, and platform (in order of appearance).
Under each heatmap, we identify the categories where games sell best. This is done for okay, good, and great games, as defined by games with scores in the 70s, 80s, and 90s, respectively.
Genres where great games sell best: Racing, Action
Genres where good games sell best: Platform, Action/Shooter
Genres where okay games sell best: Fighting, Misc
Developers whose great games sell best: Nintendo, Electronic Arts
Developers whose good games sell best: Nintendo, Namco
Developers whose okay games sell best: Nintendo, Traveller’s Tales
Interpretation: In the great scores column (last), Nintendo has the highest median sales (in millions of units) per game, at 4.6M. Interestingly, Nintendo also has the highest median sales per game in both the good and okay scoring columns.
Publishers who sell great games best: Microsoft Game Studios, Warner Bros. Interactive Entertainment
Publishers who sell good games best: Nintendo / Warner Bros. Interactive Entertainment
Publishers who sell okay games best: Nintendo, Microsoft Game Studios
Platforms where great games sell/sold best: PS, X360
Platforms where good games sell/sold best: PS3, XOne
Platforms where okay games sell/sold best: PS3, X360
It’s interesting how sensitive game sales in the whole PlayStation line seem to be to high critic scores, especially when sales in the mid-score ranges look relatively on par with other consoles (or at least exhibit a narrower spread).
(By platform, developer, publisher and genre)
Platforms with most games in dataset:
PS2DSPS3
PS2
DS
PS3
Developers with most games in dataset:
UbisoftEA SportsEA Canada
Ubisoft
EA Sports
EA Canada
Publishers with most games in dataset:
Electronic ArtsActivisionNamco Bandai Games
Electronic Arts
Activision
Namco Bandai Games
Genres with most games in dataset:
ActionSportsMisc
Action
Sports
Misc
(For numeric and categorical variables)
Strongest correlations:
Critic score-to-global sales: We’ll take a closer look at this in the next two sections.
Year of release-to-platform: This makes sense since new platforms are released periodically.
Note: Categorical columns (platform, genre, publisher) were converted to numeric in order of game count, as seen in previous section. The slightly negative correlations they have to global sales can be interpreted as “the higher the ID number, the smaller the [platform, genre, publisher], and thus the slightly lower the sales figure”.
(For all years in the dataset)
Kinda messy, right?
We’ll go ahead and use bins to get a better feel for the relationship...
The relationship looks much clearer now. It’s interesting how the slope gets steeper in the 80’s. It seems once a video game gets a high critic score, every additional point has a higher impact. For example, in this 2014–16 subset, an 8-point increase in critic score seems to have a positive effect on sales of about 250k when starting from a score of 65, but ~1M when starting from 77. Go big or go home, right?
This will be the target in our prediction model, where we’ll predict if a game will be a hit or not. The target is binary: 1 if Hit, else 0.
Here’s the relationship between critic scores and VG hits using a 5% sample:
As expected, it seems hits are mostly found near high critic scores, while non-hits can vary in scores but begin to lose presence in the high score ranges (as interpreted by the steepening regression curve near the 70's).
(For predicting the likelihood of a given game to reach sales of 1 million units or higher, referred to as “hit” games. Classification approach is applied to separate hits from non-hits.)
Feature ranking (top 10):1. Critic_Score (0.323090)2. Year_of_Release (0.158740)3. Publisher_Nintendo (0.030405)4. Genre_Action (0.024856)5. Publisher_Activision (0.018035)6. Genre_Sports (0.016918)7. Publisher_Electronic Arts (0.016917)8. Genre_Shooter (0.015722)9. Platform_PS3 (0.015634)10. Publisher_Ubisoft (0.014164)
Kaggle notebook (Python) can be found here and feel free to hit me up on Twitter or LinkedIn.
If you enjoyed reading this article, I would appreciate it if you hit the “Recommend” button and/or share it.
|
[
{
"code": null,
"e": 448,
"s": 171,
"text": "The following four heatmaps show how game sales vary according to critic scores, which are split into six scoring groups. Additionally, each heatmap segments the data further by one of the following features: genre, developer, publisher, and platform (in order of appearance)."
},
{
"code": null,
"e": 636,
"s": 448,
"text": "Under each heatmap, we identify the categories where games sell best. This is done for okay, good, and great games, as defined by games with scores in the 70s, 80s, and 90s, respectively."
},
{
"code": null,
"e": 687,
"s": 636,
"text": "Genres where great games sell best: Racing, Action"
},
{
"code": null,
"e": 747,
"s": 687,
"text": "Genres where good games sell best: Platform, Action/Shooter"
},
{
"code": null,
"e": 797,
"s": 747,
"text": "Genres where okay games sell best: Fighting, Misc"
},
{
"code": null,
"e": 863,
"s": 797,
"text": "Developers whose great games sell best: Nintendo, Electronic Arts"
},
{
"code": null,
"e": 918,
"s": 863,
"text": "Developers whose good games sell best: Nintendo, Namco"
},
{
"code": null,
"e": 985,
"s": 918,
"text": "Developers whose okay games sell best: Nintendo, Traveller’s Tales"
},
{
"code": null,
"e": 1226,
"s": 985,
"text": "Interpretation: In the great scores column (last), Nintendo has the highest median sales (in millions of units) per game, at 4.6M. Interestingly, Nintendo also has the highest median sales per game in both the good and okay scoring columns."
},
{
"code": null,
"e": 1327,
"s": 1226,
"text": "Publishers who sell great games best: Microsoft Game Studios, Warner Bros. Interactive Entertainment"
},
{
"code": null,
"e": 1414,
"s": 1327,
"text": "Publishers who sell good games best: Nintendo / Warner Bros. Interactive Entertainment"
},
{
"code": null,
"e": 1484,
"s": 1414,
"text": "Publishers who sell okay games best: Nintendo, Microsoft Game Studios"
},
{
"code": null,
"e": 1537,
"s": 1484,
"text": "Platforms where great games sell/sold best: PS, X360"
},
{
"code": null,
"e": 1590,
"s": 1537,
"text": "Platforms where good games sell/sold best: PS3, XOne"
},
{
"code": null,
"e": 1643,
"s": 1590,
"text": "Platforms where okay games sell/sold best: PS3, X360"
},
{
"code": null,
"e": 1879,
"s": 1643,
"text": "It’s interesting how sensitive game sales in the whole PlayStation line seem to be to high critic scores, especially when sales in the mid-score ranges look relatively on par with other consoles (or at least exhibit a narrower spread)."
},
{
"code": null,
"e": 1925,
"s": 1879,
"text": "(By platform, developer, publisher and genre)"
},
{
"code": null,
"e": 1963,
"s": 1925,
"text": "Platforms with most games in dataset:"
},
{
"code": null,
"e": 1972,
"s": 1963,
"text": "PS2DSPS3"
},
{
"code": null,
"e": 1976,
"s": 1972,
"text": "PS2"
},
{
"code": null,
"e": 1979,
"s": 1976,
"text": "DS"
},
{
"code": null,
"e": 1983,
"s": 1979,
"text": "PS3"
},
{
"code": null,
"e": 2022,
"s": 1983,
"text": "Developers with most games in dataset:"
},
{
"code": null,
"e": 2048,
"s": 2022,
"text": "UbisoftEA SportsEA Canada"
},
{
"code": null,
"e": 2056,
"s": 2048,
"text": "Ubisoft"
},
{
"code": null,
"e": 2066,
"s": 2056,
"text": "EA Sports"
},
{
"code": null,
"e": 2076,
"s": 2066,
"text": "EA Canada"
},
{
"code": null,
"e": 2115,
"s": 2076,
"text": "Publishers with most games in dataset:"
},
{
"code": null,
"e": 2159,
"s": 2115,
"text": "Electronic ArtsActivisionNamco Bandai Games"
},
{
"code": null,
"e": 2175,
"s": 2159,
"text": "Electronic Arts"
},
{
"code": null,
"e": 2186,
"s": 2175,
"text": "Activision"
},
{
"code": null,
"e": 2205,
"s": 2186,
"text": "Namco Bandai Games"
},
{
"code": null,
"e": 2240,
"s": 2205,
"text": "Genres with most games in dataset:"
},
{
"code": null,
"e": 2257,
"s": 2240,
"text": "ActionSportsMisc"
},
{
"code": null,
"e": 2264,
"s": 2257,
"text": "Action"
},
{
"code": null,
"e": 2271,
"s": 2264,
"text": "Sports"
},
{
"code": null,
"e": 2276,
"s": 2271,
"text": "Misc"
},
{
"code": null,
"e": 2316,
"s": 2276,
"text": "(For numeric and categorical variables)"
},
{
"code": null,
"e": 2340,
"s": 2316,
"text": "Strongest correlations:"
},
{
"code": null,
"e": 2429,
"s": 2340,
"text": "Critic score-to-global sales: We’ll take a closer look at this in the next two sections."
},
{
"code": null,
"e": 2522,
"s": 2429,
"text": "Year of release-to-platform: This makes sense since new platforms are released periodically."
},
{
"code": null,
"e": 2859,
"s": 2522,
"text": "Note: Categorical columns (platform, genre, publisher) were converted to numeric in order of game count, as seen in previous section. The slightly negative correlations they have to global sales can be interpreted as “the higher the ID number, the smaller the [platform, genre, publisher], and thus the slightly lower the sales figure”."
},
{
"code": null,
"e": 2890,
"s": 2859,
"text": "(For all years in the dataset)"
},
{
"code": null,
"e": 2910,
"s": 2890,
"text": "Kinda messy, right?"
},
{
"code": null,
"e": 2983,
"s": 2910,
"text": "We’ll go ahead and use bins to get a better feel for the relationship..."
},
{
"code": null,
"e": 3397,
"s": 2983,
"text": "The relationship looks much clearer now. It’s interesting how the slope gets steeper in the 80’s. It seems once a video game gets a high critic score, every additional point has a higher impact. For example, in this 2014–16 subset, an 8-point increase in critic score seems to have a positive effect on sales of about 250k when starting from a score of 65, but ~1M when starting from 77. Go big or go home, right?"
},
{
"code": null,
"e": 3538,
"s": 3397,
"text": "This will be the target in our prediction model, where we’ll predict if a game will be a hit or not. The target is binary: 1 if Hit, else 0."
},
{
"code": null,
"e": 3615,
"s": 3538,
"text": "Here’s the relationship between critic scores and VG hits using a 5% sample:"
},
{
"code": null,
"e": 3837,
"s": 3615,
"text": "As expected, it seems hits are mostly found near high critic scores, while non-hits can vary in scores but begin to lose presence in the high score ranges (as interpreted by the steepening regression curve near the 70's)."
},
{
"code": null,
"e": 4025,
"s": 3837,
"text": "(For predicting the likelihood of a given game to reach sales of 1 million units or higher, referred to as “hit” games. Classification approach is applied to separate hits from non-hits.)"
},
{
"code": null,
"e": 4357,
"s": 4025,
"text": "Feature ranking (top 10):1. Critic_Score (0.323090)2. Year_of_Release (0.158740)3. Publisher_Nintendo (0.030405)4. Genre_Action (0.024856)5. Publisher_Activision (0.018035)6. Genre_Sports (0.016918)7. Publisher_Electronic Arts (0.016917)8. Genre_Shooter (0.015722)9. Platform_PS3 (0.015634)10. Publisher_Ubisoft (0.014164)"
},
{
"code": null,
"e": 4451,
"s": 4357,
"text": "Kaggle notebook (Python) can be found here and feel free to hit me up on Twitter or LinkedIn."
}
] |
Python - Calculate the count of column values of a Pandas DataFrame
|
To calculate the count of column values, use the count() method. At first, import the required Pandas library −
import pandas as pd
Create a DataFrame with two columns −
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90]
}
)
Finding count of "Units" column values using the count() function −
print"Count of values of Units column from DataFrame1 = ",dataFrame1['Units'].count()
In the same way, we have calculated the count from the 2nd DataFrame.
Following is the complete code −
import pandas as pd
# Create DataFrame1
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90]
}
)
print"DataFrame1 ...\n",dataFrame1
# Finding count of values of a specific column
print"Count of values of Units column from DataFrame1 = ",dataFrame1['Units'].count()
# Create DataFrame2
dataFrame2 = pd.DataFrame(
{
"Product": ['TV', 'PenDrive', 'HeadPhone', 'EarPhone', 'HDD'],
"Price": [8000, 500, 3000, 1500, 3000]
}
)
print"\nDataFrame2 ...\n",dataFrame2
# Finding count of values of all the column
print"\nCount of column values from DataFrame2 = \n",dataFrame2.count()
This will produce the following output −
DataFrame1 ...
Car Units
0 BMW 100
1 Lexus 150
2 Audi 110
3 Tesla 80
4 Bentley 110
5 Jaguar 90
Count of values of Units column from DataFrame1 = 6
DataFrame2 ...
Price Product
0 8000 TV
1 500 PenDrive
2 3000 HeadPhone
3 1500 EarPhone
4 3000 HDD
Count of column values from DataFrame2 =
Price 5
Product 5
dtype: int64
|
[
{
"code": null,
"e": 1174,
"s": 1062,
"text": "To calculate the count of column values, use the count() method. At first, import the required Pandas library −"
},
{
"code": null,
"e": 1194,
"s": 1174,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1232,
"s": 1194,
"text": "Create a DataFrame with two columns −"
},
{
"code": null,
"e": 1384,
"s": 1232,
"text": "dataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],\n \"Units\": [100, 150, 110, 80, 110, 90]\n }\n)"
},
{
"code": null,
"e": 1452,
"s": 1384,
"text": "Finding count of \"Units\" column values using the count() function −"
},
{
"code": null,
"e": 1539,
"s": 1452,
"text": "print\"Count of values of Units column from DataFrame1 = \",dataFrame1['Units'].count()\n"
},
{
"code": null,
"e": 1609,
"s": 1539,
"text": "In the same way, we have calculated the count from the 2nd DataFrame."
},
{
"code": null,
"e": 1642,
"s": 1609,
"text": "Following is the complete code −"
},
{
"code": null,
"e": 2336,
"s": 1642,
"text": "import pandas as pd\n\n# Create DataFrame1\ndataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],\n \"Units\": [100, 150, 110, 80, 110, 90]\n }\n)\n\nprint\"DataFrame1 ...\\n\",dataFrame1\n\n# Finding count of values of a specific column\nprint\"Count of values of Units column from DataFrame1 = \",dataFrame1['Units'].count()\n\n# Create DataFrame2\ndataFrame2 = pd.DataFrame(\n {\n \"Product\": ['TV', 'PenDrive', 'HeadPhone', 'EarPhone', 'HDD'],\n \"Price\": [8000, 500, 3000, 1500, 3000]\n }\n)\n\nprint\"\\nDataFrame2 ...\\n\",dataFrame2\n\n# Finding count of values of all the column\nprint\"\\nCount of column values from DataFrame2 = \\n\",dataFrame2.count()\n\n"
},
{
"code": null,
"e": 2377,
"s": 2336,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2781,
"s": 2377,
"text": "DataFrame1 ...\n Car Units\n0 BMW 100\n1 Lexus 150\n2 Audi 110\n3 Tesla 80\n4 Bentley 110\n5 Jaguar 90\nCount of values of Units column from DataFrame1 = 6\n\nDataFrame2 ...\n Price Product\n0 8000 TV\n1 500 PenDrive\n2 3000 HeadPhone\n3 1500 EarPhone\n4 3000 HDD\n\nCount of column values from DataFrame2 =\nPrice 5\nProduct 5\ndtype: int64"
}
] |
Bootstrap table-condensed class
|
Using the .table-condensed class, row padding is cut in half to condense the table. as seen in the following example. This is useful if you want any denser information.
You can try to run the following code to implement table-condensed class in Bootstrap −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Table</title>
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<table class = "table table-condensed table-hover table-bordered table-striped">
<caption>Footballer Rank</caption>
<thead>
<tr>
<th>Footballer</th>
<th>Rank</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>Messi</td>
<td>1</td>
<td>Argentina</td>
</tr>
<tr>
<td>Neymar</td>
<td>2</td>
<td>Brazil</td>
</tr>
<tr>
<td>Ronaldo</td>
<td>3</td>
<td>Portugal</td>
</tr>
</tbody>
</table>
</body>
</html>
|
[
{
"code": null,
"e": 1231,
"s": 1062,
"text": "Using the .table-condensed class, row padding is cut in half to condense the table. as seen in the following example. This is useful if you want any denser information."
},
{
"code": null,
"e": 1319,
"s": 1231,
"text": "You can try to run the following code to implement table-condensed class in Bootstrap −"
},
{
"code": null,
"e": 1329,
"s": 1319,
"text": "Live Demo"
},
{
"code": null,
"e": 2557,
"s": 1329,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Table</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <table class = \"table table-condensed table-hover table-bordered table-striped\">\n <caption>Footballer Rank</caption>\n <thead>\n <tr>\n <th>Footballer</th>\n <th>Rank</th>\n <th>Country</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>Messi</td>\n <td>1</td>\n <td>Argentina</td>\n </tr>\n <tr>\n <td>Neymar</td>\n <td>2</td>\n <td>Brazil</td>\n </tr>\n <tr>\n <td>Ronaldo</td>\n <td>3</td>\n <td>Portugal</td>\n </tr>\n </tbody>\n </table>\n </body>\n</html>"
}
] |
How to define character constants in C#?
|
Character literals are enclosed in single quotes. For example, 'x' and can be stored in a simple variable of char type. A character literal can be a plain character (such as 'x'), an escape sequence (such as '\t'), or a universal character (such as '\u02C0').
Let us see an example how to define a character constant in C# −
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
Console.WriteLine("Welcome!\t\n\n");
Console.WriteLine("This is it!");
Console.ReadLine();
}
}
}
Above, we have used the \n and \t constants that are new-line and horizontal tab constants −
Console.WriteLine("Welcome!\t\n\n");
Console.WriteLine("This is it!");
|
[
{
"code": null,
"e": 1322,
"s": 1062,
"text": "Character literals are enclosed in single quotes. For example, 'x' and can be stored in a simple variable of char type. A character literal can be a plain character (such as 'x'), an escape sequence (such as '\\t'), or a universal character (such as '\\u02C0')."
},
{
"code": null,
"e": 1387,
"s": 1322,
"text": "Let us see an example how to define a character constant in C# −"
},
{
"code": null,
"e": 1611,
"s": 1387,
"text": "using System;\n\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n Console.WriteLine(\"Welcome!\\t\\n\\n\");\n Console.WriteLine(\"This is it!\");\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 1704,
"s": 1611,
"text": "Above, we have used the \\n and \\t constants that are new-line and horizontal tab constants −"
},
{
"code": null,
"e": 1775,
"s": 1704,
"text": "Console.WriteLine(\"Welcome!\\t\\n\\n\");\nConsole.WriteLine(\"This is it!\");"
}
] |
How to match pattern over multiple lines in Python?
|
The re.DOTALL flag tells python to make the ‘.’ special character match all characters, including newline characters.
import re
paragraph = \
'''
This is a paragraph.
It has multiple lines.
'''
match = re.search(r'<p>.*</p>', paragraph, re.DOTALL)
print match.group(0)
Output
This is a paragraph.
It has multiple lines.
|
[
{
"code": null,
"e": 1180,
"s": 1062,
"text": "The re.DOTALL flag tells python to make the ‘.’ special character match all characters, including newline characters."
},
{
"code": null,
"e": 1337,
"s": 1180,
"text": "import re\nparagraph = \\\n'''\n This is a paragraph.\n It has multiple lines.\n'''\nmatch = re.search(r'<p>.*</p>', paragraph, re.DOTALL)\nprint match.group(0)"
},
{
"code": null,
"e": 1344,
"s": 1337,
"text": "Output"
},
{
"code": null,
"e": 1389,
"s": 1344,
"text": "This is a paragraph.\nIt has multiple lines.\n"
}
] |
CSS | Scroll Padding top - GeeksforGeeks
|
31 Oct, 2019
The Scroll Padding top is an inbuilt property in Scroll Snap module. This property set the scroll padding top longhand. This property acts as a magnet on the top of the sliding element that stick to the top of the view-port and stop the scrolling(forcefully) in that place.
The Scroll Padding property is optional, this property is used when the Scroll Snap type property is set to none.
Syntax:
scroll-padding-top: [ length percentage | auto ]
Property Values: This property accept two property mentioned above and described below:
length-percentage: This property works same as other padding property contains the length in any specific unit for padding.
auto: This property leaves some spaces for padding determined by browsers.
Example: Below example illustrates the Scroll Padding top property:
<!DOCTYPE html> <html> <head> <title> CSS Scroll Padding top </title> <style> h1 { color: green; } .element{ border:2px solid black; } .container { width: 500px; height: 200px; margin-left: auto; margin-right: auto; border: 2px solid black; overflow: scroll; position: relative; } .element { width: 480px; height: 180px; scroll-snap-align: start; scroll-snap-stop: normal; color: white; font-size: 50px; display: flex; justify-content: center; align-items: center; } .y-mandatory { scroll-snap-type: y mandatory; /* scroll-padding: top right bottom left */ scroll-padding-top: 50px; } .element:nth-child(1) { background: url("https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png"); } .element:nth-child(2) { background: url("https://www.geeksforgeeks.org/wp-content/uploads/CSS-768x256.png"); } .element:nth-child(3) { background: url("https://www.geeksforgeeks.org/wp-content/uploads/javascript-768x256.png"); } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h4>CSS Scroll Padding top</h4> <div class="container y-scroll y-mandatory"> <div class="wrapper"> <div class="element"></div> <div class="element"></div> <div class="element"></div> </div> </div> </center> </body> </html>
Output:
Supported Browsers: The browsers supported by CSS Scroll Padding top are listed below:
Google Chrome 69
Internet Explorer 11
Firefox 68
Safari 11
CSS-Properties
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Design a web page using HTML and CSS
Create a Responsive Navbar using ReactJS
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": 24330,
"s": 24302,
"text": "\n31 Oct, 2019"
},
{
"code": null,
"e": 24604,
"s": 24330,
"text": "The Scroll Padding top is an inbuilt property in Scroll Snap module. This property set the scroll padding top longhand. This property acts as a magnet on the top of the sliding element that stick to the top of the view-port and stop the scrolling(forcefully) in that place."
},
{
"code": null,
"e": 24718,
"s": 24604,
"text": "The Scroll Padding property is optional, this property is used when the Scroll Snap type property is set to none."
},
{
"code": null,
"e": 24726,
"s": 24718,
"text": "Syntax:"
},
{
"code": null,
"e": 24776,
"s": 24726,
"text": "scroll-padding-top: [ length percentage | auto ]"
},
{
"code": null,
"e": 24864,
"s": 24776,
"text": "Property Values: This property accept two property mentioned above and described below:"
},
{
"code": null,
"e": 24988,
"s": 24864,
"text": "length-percentage: This property works same as other padding property contains the length in any specific unit for padding."
},
{
"code": null,
"e": 25063,
"s": 24988,
"text": "auto: This property leaves some spaces for padding determined by browsers."
},
{
"code": null,
"e": 25131,
"s": 25063,
"text": "Example: Below example illustrates the Scroll Padding top property:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> CSS Scroll Padding top </title> <style> h1 { color: green; } .element{ border:2px solid black; } .container { width: 500px; height: 200px; margin-left: auto; margin-right: auto; border: 2px solid black; overflow: scroll; position: relative; } .element { width: 480px; height: 180px; scroll-snap-align: start; scroll-snap-stop: normal; color: white; font-size: 50px; display: flex; justify-content: center; align-items: center; } .y-mandatory { scroll-snap-type: y mandatory; /* scroll-padding: top right bottom left */ scroll-padding-top: 50px; } .element:nth-child(1) { background: url(\"https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png\"); } .element:nth-child(2) { background: url(\"https://www.geeksforgeeks.org/wp-content/uploads/CSS-768x256.png\"); } .element:nth-child(3) { background: url(\"https://www.geeksforgeeks.org/wp-content/uploads/javascript-768x256.png\"); } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <h4>CSS Scroll Padding top</h4> <div class=\"container y-scroll y-mandatory\"> <div class=\"wrapper\"> <div class=\"element\"></div> <div class=\"element\"></div> <div class=\"element\"></div> </div> </div> </center> </body> </html> ",
"e": 26998,
"s": 25131,
"text": null
},
{
"code": null,
"e": 27006,
"s": 26998,
"text": "Output:"
},
{
"code": null,
"e": 27093,
"s": 27006,
"text": "Supported Browsers: The browsers supported by CSS Scroll Padding top are listed below:"
},
{
"code": null,
"e": 27110,
"s": 27093,
"text": "Google Chrome 69"
},
{
"code": null,
"e": 27131,
"s": 27110,
"text": "Internet Explorer 11"
},
{
"code": null,
"e": 27142,
"s": 27131,
"text": "Firefox 68"
},
{
"code": null,
"e": 27152,
"s": 27142,
"text": "Safari 11"
},
{
"code": null,
"e": 27167,
"s": 27152,
"text": "CSS-Properties"
},
{
"code": null,
"e": 27171,
"s": 27167,
"text": "CSS"
},
{
"code": null,
"e": 27188,
"s": 27171,
"text": "Web Technologies"
},
{
"code": null,
"e": 27286,
"s": 27188,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27344,
"s": 27286,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 27381,
"s": 27344,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 27445,
"s": 27381,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 27482,
"s": 27445,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 27523,
"s": 27482,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 27565,
"s": 27523,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27598,
"s": 27565,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27641,
"s": 27598,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27686,
"s": 27641,
"text": "Convert a string to an integer in JavaScript"
}
] |
Extracting colours from an image using k-means clustering | by Xander Lewis | Towards Data Science
|
I wanted to write some software that would allow me to extract a set of colours from an image, and do it in a way that seems natural and takes human perception into consideration. A colour scheme can often sum up the ‘vibe’ of an entire image, and so I thought it would be a useful thing to be able to do.
So... I spent some time thinking of some ways that I could do this. I devised some fairly simple algorithms that would, for example, chop the image regularly into chunks and output the mean colour of each of these parts. Maybe extra layers could be added where the chunks are compared to each other and joined into groups, and maybe each colour could be recursively combined with another until the desired number of colours is reached. I quickly realised, though, that this problem had already been solved in the general case, and in a way that will work quite nicely.
K-means clustering is a method through which a set of data points can be partitioned into several disjoint subsets where the points in each subset are deemed to be ‘close’ to each other (according to some metric). A common metric, at least when the points can be geometrically represented, is your bog standard euclidean distance function. The ‘k’ just refers to the number of subsets desired in the final output. It turns out that this approach is exactly what we need to divide our image into a set of colours.
In our case, the ‘data points’ are colours, and the distance function is some measure of ‘how different’ two colours are. Our task is to group these colours into a given number of sets, and then calculate the mean colour of each set. Using the mean seems like a fairly sensible choice because you can imagine blurring your eyes whilst looking at the different colour clusters, and seeing a mean colour for each. However, we could instead use any other statistical measure (mode, median, or anything else!) and possibly get a better result.
Let’s write this in JavaScript! ✨
Each data point is a colour and can be represented as a point in an RGB colour space.
In JavaScript, a single data point could look something like this:
// An array if we want to be generallet colour = [100,168,92];// Or an object if we want to be more explicitlet colour = {red: 100, green: 168, blue: 92};
Since we want to be able to calculate how similar two colours are, we need a function. This is another point where we have many choices, but a straightforward one is just to calculate the euclidean distance using the component values of each colour.
Our distance function could look like this:
// Distance functionfunction euclideanDistance(a, b) { let sum = 0; for (let i = 0; i < a.length; i++) { sum += Math.pow(b[i] — a[i], 2); } return Math.sqrt(sum);}
Since we haven’t specified a fixed number of components in our function, it will work for n-dimensional data points (with n components). This is useful in case we want to represent colour in a different way later on.
The most common algorithm used for k-means clustering is called Lloyd’s algorithm (although it is often known simply as the k-means algorithm). We’re going to use that algorithm here.
We’re going to create a set of objects called ‘centroids’, each of which defines a single, unique cluster.
A centroid has two things associated with it:
a point within the range of the data set (the centroid’s position)
a set of data points from the data set (the points in the centroid’s cluster)
There are three main steps to the algorithm:
1. Initialisation. Choose initial values for the centroids. In this case, we’ll just choose a random point for each one.
2. Assignment. Assign each data point to the cluster whose mean (the centroid) is the least distance away.
3. Update. Set the new mean of each centroid to be the mean of all of data points associated with it (in the centroid’s cluster).
The algorithm will perform initialisation once, and then perform assignment and update in order, repeatedly, until the algorithm converges.
The algorithm is said to have ‘converged’ when nothing changes between assignments. Basically, when the points make their mind up about which cluster they’re a part of, we can stop looping.
Let’s get some helper functions defined: one for calculating the range of a given dataset, and one for generating a random integer within a given range. The ‘range’ of an n-dimensional data set is just a set of ranges — one for each dimension.
// Calculate range of a one-dimensional data setfunction rangeOf(data) { return {min: Math.min(data), max: Math.max(data)};}// Calculate range of an n-dimensional data setfunction rangesOf(data) { let ranges = []; for (let i = 0; i < data[0].length; i++) { ranges.push(rangeOf(data.map(x => x[i]))); } return ranges;}// Generate random integer in a given closed intervalfunction randomIntBetween(a, b) { return Math.floor(Math.random() * (b - a + 1)) + a;}
Assuming we’ve got those two, we can now write the code for the three steps of the algorithm.
For the number of centroids desired (k), we generate a random integer-valued point in the range of the data set provided and append it to an array. Each point in the array represents the position of a centroid. The centroids, of course, have the same number of dimensions as the data.
function initialiseCentroidsRandomly(data, k) { let ranges = rangesOf(data); let centroids = []; for (let i = 0; i < k; i++) { let centroid = []; for (let r in ranges) { centroid.push( randomIntBetween(ranges[r].min, ranges[r].max)); } centroids.push(centroid); } return centroids;}
This is where we assign data points to clusters. For each point, we choose the centroid that is the minimum distance away and we append the point to the associated cluster.
I’m using the Array’s map function along with an arrow function here, so have a quick look at those if you’re not quite sure what’s going on.
function clusterDataPoints(data, centroids) { let clusters = []; centroids.forEach(function() { clusters.push([]); }); data.forEach(function(point) { let nearestCentroid = Math.min( centroids.map(x => euclideanDistance(point, x))); clusters[centroids.indexOf(nearestCentroid)].push(point); }); return clusters;}
For each cluster, we calculate the mean of its enclosing data points and set it as the associated centroid’s position. We then return the new set of centroids.
There’s actually another function being used here called meanPoint. I won’t go into to detail because it’s fairly obvious to implement yourself. It returns a point whose components are the means of the corresponding component values in each of the passed points.
function getNewCentroids(clusters) { let centroids = []; clusters.forEach(function(cluster) { centroids.push(meanPoint(cluster)); });return centroids;}
There is one issue with this algorithm, and it’s that sometimes the clusters become empty. There isn’t much of a consensus on what to do when this happens, but some possible approaches are to:
Remove the cluster (a bit silly)
Assign a random data point to the cluster
Assign the closest data point to the cluster
Restart the algorithm and hope it doesn’t happen again
Although the last option seems like a bit of a bodge, the algorithm (with the random initialisation) is non-deterministic and so simply restarting does work quite well. After all, this method is pretty much a heuristic and heuristics by definition are ‘a bit of a bodge’ ... at least compared to a solid algorithm.
Now that we’ve got the basic functionality defined, all that’s left is to write some code to call each function when required as defined by the algorithm.
I’ll leave that to you as an exercise, but, if you really want to, you can see my implementation of it as a web app here. 🌈
|
[
{
"code": null,
"e": 477,
"s": 171,
"text": "I wanted to write some software that would allow me to extract a set of colours from an image, and do it in a way that seems natural and takes human perception into consideration. A colour scheme can often sum up the ‘vibe’ of an entire image, and so I thought it would be a useful thing to be able to do."
},
{
"code": null,
"e": 1046,
"s": 477,
"text": "So... I spent some time thinking of some ways that I could do this. I devised some fairly simple algorithms that would, for example, chop the image regularly into chunks and output the mean colour of each of these parts. Maybe extra layers could be added where the chunks are compared to each other and joined into groups, and maybe each colour could be recursively combined with another until the desired number of colours is reached. I quickly realised, though, that this problem had already been solved in the general case, and in a way that will work quite nicely."
},
{
"code": null,
"e": 1559,
"s": 1046,
"text": "K-means clustering is a method through which a set of data points can be partitioned into several disjoint subsets where the points in each subset are deemed to be ‘close’ to each other (according to some metric). A common metric, at least when the points can be geometrically represented, is your bog standard euclidean distance function. The ‘k’ just refers to the number of subsets desired in the final output. It turns out that this approach is exactly what we need to divide our image into a set of colours."
},
{
"code": null,
"e": 2099,
"s": 1559,
"text": "In our case, the ‘data points’ are colours, and the distance function is some measure of ‘how different’ two colours are. Our task is to group these colours into a given number of sets, and then calculate the mean colour of each set. Using the mean seems like a fairly sensible choice because you can imagine blurring your eyes whilst looking at the different colour clusters, and seeing a mean colour for each. However, we could instead use any other statistical measure (mode, median, or anything else!) and possibly get a better result."
},
{
"code": null,
"e": 2133,
"s": 2099,
"text": "Let’s write this in JavaScript! ✨"
},
{
"code": null,
"e": 2219,
"s": 2133,
"text": "Each data point is a colour and can be represented as a point in an RGB colour space."
},
{
"code": null,
"e": 2286,
"s": 2219,
"text": "In JavaScript, a single data point could look something like this:"
},
{
"code": null,
"e": 2441,
"s": 2286,
"text": "// An array if we want to be generallet colour = [100,168,92];// Or an object if we want to be more explicitlet colour = {red: 100, green: 168, blue: 92};"
},
{
"code": null,
"e": 2691,
"s": 2441,
"text": "Since we want to be able to calculate how similar two colours are, we need a function. This is another point where we have many choices, but a straightforward one is just to calculate the euclidean distance using the component values of each colour."
},
{
"code": null,
"e": 2735,
"s": 2691,
"text": "Our distance function could look like this:"
},
{
"code": null,
"e": 2918,
"s": 2735,
"text": "// Distance functionfunction euclideanDistance(a, b) { let sum = 0; for (let i = 0; i < a.length; i++) { sum += Math.pow(b[i] — a[i], 2); } return Math.sqrt(sum);}"
},
{
"code": null,
"e": 3135,
"s": 2918,
"text": "Since we haven’t specified a fixed number of components in our function, it will work for n-dimensional data points (with n components). This is useful in case we want to represent colour in a different way later on."
},
{
"code": null,
"e": 3319,
"s": 3135,
"text": "The most common algorithm used for k-means clustering is called Lloyd’s algorithm (although it is often known simply as the k-means algorithm). We’re going to use that algorithm here."
},
{
"code": null,
"e": 3426,
"s": 3319,
"text": "We’re going to create a set of objects called ‘centroids’, each of which defines a single, unique cluster."
},
{
"code": null,
"e": 3472,
"s": 3426,
"text": "A centroid has two things associated with it:"
},
{
"code": null,
"e": 3539,
"s": 3472,
"text": "a point within the range of the data set (the centroid’s position)"
},
{
"code": null,
"e": 3617,
"s": 3539,
"text": "a set of data points from the data set (the points in the centroid’s cluster)"
},
{
"code": null,
"e": 3662,
"s": 3617,
"text": "There are three main steps to the algorithm:"
},
{
"code": null,
"e": 3783,
"s": 3662,
"text": "1. Initialisation. Choose initial values for the centroids. In this case, we’ll just choose a random point for each one."
},
{
"code": null,
"e": 3890,
"s": 3783,
"text": "2. Assignment. Assign each data point to the cluster whose mean (the centroid) is the least distance away."
},
{
"code": null,
"e": 4020,
"s": 3890,
"text": "3. Update. Set the new mean of each centroid to be the mean of all of data points associated with it (in the centroid’s cluster)."
},
{
"code": null,
"e": 4160,
"s": 4020,
"text": "The algorithm will perform initialisation once, and then perform assignment and update in order, repeatedly, until the algorithm converges."
},
{
"code": null,
"e": 4350,
"s": 4160,
"text": "The algorithm is said to have ‘converged’ when nothing changes between assignments. Basically, when the points make their mind up about which cluster they’re a part of, we can stop looping."
},
{
"code": null,
"e": 4594,
"s": 4350,
"text": "Let’s get some helper functions defined: one for calculating the range of a given dataset, and one for generating a random integer within a given range. The ‘range’ of an n-dimensional data set is just a set of ranges — one for each dimension."
},
{
"code": null,
"e": 5076,
"s": 4594,
"text": "// Calculate range of a one-dimensional data setfunction rangeOf(data) { return {min: Math.min(data), max: Math.max(data)};}// Calculate range of an n-dimensional data setfunction rangesOf(data) { let ranges = []; for (let i = 0; i < data[0].length; i++) { ranges.push(rangeOf(data.map(x => x[i]))); } return ranges;}// Generate random integer in a given closed intervalfunction randomIntBetween(a, b) { return Math.floor(Math.random() * (b - a + 1)) + a;}"
},
{
"code": null,
"e": 5170,
"s": 5076,
"text": "Assuming we’ve got those two, we can now write the code for the three steps of the algorithm."
},
{
"code": null,
"e": 5455,
"s": 5170,
"text": "For the number of centroids desired (k), we generate a random integer-valued point in the range of the data set provided and append it to an array. Each point in the array represents the position of a centroid. The centroids, of course, have the same number of dimensions as the data."
},
{
"code": null,
"e": 5803,
"s": 5455,
"text": "function initialiseCentroidsRandomly(data, k) { let ranges = rangesOf(data); let centroids = []; for (let i = 0; i < k; i++) { let centroid = []; for (let r in ranges) { centroid.push( randomIntBetween(ranges[r].min, ranges[r].max)); } centroids.push(centroid); } return centroids;}"
},
{
"code": null,
"e": 5976,
"s": 5803,
"text": "This is where we assign data points to clusters. For each point, we choose the centroid that is the minimum distance away and we append the point to the associated cluster."
},
{
"code": null,
"e": 6118,
"s": 5976,
"text": "I’m using the Array’s map function along with an arrow function here, so have a quick look at those if you’re not quite sure what’s going on."
},
{
"code": null,
"e": 6464,
"s": 6118,
"text": "function clusterDataPoints(data, centroids) { let clusters = []; centroids.forEach(function() { clusters.push([]); }); data.forEach(function(point) { let nearestCentroid = Math.min( centroids.map(x => euclideanDistance(point, x))); clusters[centroids.indexOf(nearestCentroid)].push(point); }); return clusters;}"
},
{
"code": null,
"e": 6624,
"s": 6464,
"text": "For each cluster, we calculate the mean of its enclosing data points and set it as the associated centroid’s position. We then return the new set of centroids."
},
{
"code": null,
"e": 6887,
"s": 6624,
"text": "There’s actually another function being used here called meanPoint. I won’t go into to detail because it’s fairly obvious to implement yourself. It returns a point whose components are the means of the corresponding component values in each of the passed points."
},
{
"code": null,
"e": 7055,
"s": 6887,
"text": "function getNewCentroids(clusters) { let centroids = []; clusters.forEach(function(cluster) { centroids.push(meanPoint(cluster)); });return centroids;}"
},
{
"code": null,
"e": 7248,
"s": 7055,
"text": "There is one issue with this algorithm, and it’s that sometimes the clusters become empty. There isn’t much of a consensus on what to do when this happens, but some possible approaches are to:"
},
{
"code": null,
"e": 7281,
"s": 7248,
"text": "Remove the cluster (a bit silly)"
},
{
"code": null,
"e": 7323,
"s": 7281,
"text": "Assign a random data point to the cluster"
},
{
"code": null,
"e": 7368,
"s": 7323,
"text": "Assign the closest data point to the cluster"
},
{
"code": null,
"e": 7423,
"s": 7368,
"text": "Restart the algorithm and hope it doesn’t happen again"
},
{
"code": null,
"e": 7738,
"s": 7423,
"text": "Although the last option seems like a bit of a bodge, the algorithm (with the random initialisation) is non-deterministic and so simply restarting does work quite well. After all, this method is pretty much a heuristic and heuristics by definition are ‘a bit of a bodge’ ... at least compared to a solid algorithm."
},
{
"code": null,
"e": 7893,
"s": 7738,
"text": "Now that we’ve got the basic functionality defined, all that’s left is to write some code to call each function when required as defined by the algorithm."
}
] |
Sum of even numbers up to using recursive function in JavaScript
|
We have to write a recursive function that takes in a number n and returns the sum of all even
numbers up to n.
Let’s write the code for this function −
const recursiveEvenSum = (num, sum = 0) => {
num = num % 2 === 0 ? num : num - 1;
if(num){
return recursiveEvenSum(num - 2, sum+num);
}
return sum;
};
console.log(recursiveEvenSum(12));
console.log(recursiveEvenSum(122));
console.log(recursiveEvenSum(23));
console.log(recursiveEvenSum(10));
console.log(recursiveEvenSum(19));
The output in the console will be −
42
3782
132
30
90
|
[
{
"code": null,
"e": 1174,
"s": 1062,
"text": "We have to write a recursive function that takes in a number n and returns the sum of all even\nnumbers up to n."
},
{
"code": null,
"e": 1215,
"s": 1174,
"text": "Let’s write the code for this function −"
},
{
"code": null,
"e": 1560,
"s": 1215,
"text": "const recursiveEvenSum = (num, sum = 0) => {\n num = num % 2 === 0 ? num : num - 1;\n if(num){\n return recursiveEvenSum(num - 2, sum+num);\n }\n return sum;\n};\nconsole.log(recursiveEvenSum(12));\nconsole.log(recursiveEvenSum(122));\nconsole.log(recursiveEvenSum(23));\nconsole.log(recursiveEvenSum(10));\nconsole.log(recursiveEvenSum(19));"
},
{
"code": null,
"e": 1596,
"s": 1560,
"text": "The output in the console will be −"
},
{
"code": null,
"e": 1614,
"s": 1596,
"text": "42\n3782\n132\n30\n90"
}
] |
How to change the Title of the console using PowerShell command?
|
For various reasons, you need to change the title of the PowerShell console. Like the title to describe the script. For example, System Information or Service Information.
To change the PowerShell Console Title use the “WindowsTitle” property in RawUI. It is just a temporary change. When you close the console and open it again, the title will be set to the default.
$host.UI.RawUI.WindowTitle = "System Information"
Now the title of the PowerShell console is changed to “System Information”.
You can also supply variable value to this parameter.
$Title = "System Information"
$host.UI.RawUI.WindowTitle = $Title
|
[
{
"code": null,
"e": 1234,
"s": 1062,
"text": "For various reasons, you need to change the title of the PowerShell console. Like the title to describe the script. For example, System Information or Service Information."
},
{
"code": null,
"e": 1430,
"s": 1234,
"text": "To change the PowerShell Console Title use the “WindowsTitle” property in RawUI. It is just a temporary change. When you close the console and open it again, the title will be set to the default."
},
{
"code": null,
"e": 1480,
"s": 1430,
"text": "$host.UI.RawUI.WindowTitle = \"System Information\""
},
{
"code": null,
"e": 1556,
"s": 1480,
"text": "Now the title of the PowerShell console is changed to “System Information”."
},
{
"code": null,
"e": 1610,
"s": 1556,
"text": "You can also supply variable value to this parameter."
},
{
"code": null,
"e": 1676,
"s": 1610,
"text": "$Title = \"System Information\"\n$host.UI.RawUI.WindowTitle = $Title"
}
] |
Place k elements such that minimum distance is maximized in C++
|
In this problem, we are given an array of n points that lie on the same line. Our task is to place k elements of the array in such a way that the minimum distance between them is maximized.
Let’s take an example to understand the problem,
Input − array = {}
Output −
To solve this problem, we will find have to find the maximum possible minimum distance. For such a problem first, we need to sort the given array and then do a binary search until we get the solution at mid.
Program to show the implementation of our solution,
Live Demo
#include <bits/stdc++.h>
using namespace std;
bool canGenerateResult(int mid, int arr[], int n, int k) {
int pos = arr[0];
int elements = 1;
for (int i=1; i<n; i++){
if (arr[i] - pos >= mid){
pos = arr[i];
elements++;
if (elements == k)
return true;
}
}
return 0;
}
int maxMinDist(int arr[], int n, int k) {
sort(arr,arr+n);
int res = -1;
int left = arr[0], right = arr[n-1];
while (left < right){
int mid = (left + right)/2;
if (canGenerateResult(mid, arr, n, k)){
res = max(res, mid);
left = mid + 1;
}
else
right = mid;
}
return res;
}
int main() {
int arr[] = {3, 5, 6, 9, 1, 8};
int n = sizeof(arr)/sizeof(arr[0]);
int k = 3;
cout<<"The maximized minimum distance is : "<<maxMinDist(arr, n, k);
return 0;
}
The maximized minimum distance is : 4
|
[
{
"code": null,
"e": 1252,
"s": 1062,
"text": "In this problem, we are given an array of n points that lie on the same line. Our task is to place k elements of the array in such a way that the minimum distance between them is maximized."
},
{
"code": null,
"e": 1301,
"s": 1252,
"text": "Let’s take an example to understand the problem,"
},
{
"code": null,
"e": 1320,
"s": 1301,
"text": "Input − array = {}"
},
{
"code": null,
"e": 1329,
"s": 1320,
"text": "Output −"
},
{
"code": null,
"e": 1537,
"s": 1329,
"text": "To solve this problem, we will find have to find the maximum possible minimum distance. For such a problem first, we need to sort the given array and then do a binary search until we get the solution at mid."
},
{
"code": null,
"e": 1589,
"s": 1537,
"text": "Program to show the implementation of our solution,"
},
{
"code": null,
"e": 1600,
"s": 1589,
"text": " Live Demo"
},
{
"code": null,
"e": 2459,
"s": 1600,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nbool canGenerateResult(int mid, int arr[], int n, int k) {\n int pos = arr[0];\n int elements = 1;\n for (int i=1; i<n; i++){\n if (arr[i] - pos >= mid){\n pos = arr[i];\n elements++;\n if (elements == k)\n return true;\n }\n }\n return 0;\n}\nint maxMinDist(int arr[], int n, int k) {\n sort(arr,arr+n);\n int res = -1;\n int left = arr[0], right = arr[n-1];\n while (left < right){\n int mid = (left + right)/2;\n if (canGenerateResult(mid, arr, n, k)){\n res = max(res, mid);\n left = mid + 1;\n }\n else\n right = mid;\n }\n return res;\n}\nint main() {\n int arr[] = {3, 5, 6, 9, 1, 8};\n int n = sizeof(arr)/sizeof(arr[0]);\n int k = 3;\n cout<<\"The maximized minimum distance is : \"<<maxMinDist(arr, n, k);\n return 0;\n}"
},
{
"code": null,
"e": 2497,
"s": 2459,
"text": "The maximized minimum distance is : 4"
}
] |
Importance of clone() method in Java?
|
The clone() method is used to create a copy of an object of a class which implements Cloneable interface. By default, it does field-by-field copy as the Object class doesn't have any idea about the members of the particular class whose objects call this method. So, if the class has only primitive data type members then a new copy of the object will be created and the reference to the new object copy will be returned. But, if the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.
We will get a CloneNotSupportedException if we try to call the clone() method on an object of a class that doesn't implement the Cloneable interface. This interface is a marker interface and the implementation of this interface simply indicates that the Object.clone() method can be called on the objects of the implementing class.
protected Object clone() throws CloneNotSupportedException
We can implement the clone() method in two ways
This is a result of the default cloning functionality provided by the Object.clone() method if the class has non-primitive data type members as well. In the case of Shallow Copy, the cloned object also refers to the same object to which the original object refers as only the object references get copied and not the referred objects.
public class ShallowCopyTest {
public static void main(String args[]) {
A a1 = new A();
A a2 = (A) a1.clone();
a1.sb.append("Tutorialspoint!");
System.out.println(a1);
System.out.println(a2);
}
}
class A implements Cloneable {
public StringBuffer sb = new StringBuffer("Welcome to ");
public String toString() {
return sb.toString();
}
public Object clone() {
try {
return super.clone();
} catch(CloneNotSupportedException e) {
}
return null;
}
}
Welcome to Tutorialspoint!
Welcome to Tutorialspoint!
We need to override the clone() method for the classes having non-primitive type members to achieve Deep Copy as it requires the member objects to be cloned as well, which is not done by the default cloning mechanism.
public class DeepCopyTest {
public static void main(String args[]) {
A a1 = new A();
A a2 = (A) a1.clone();
a1.sb.append(" TutorialsPoint!");
System.out.println(a1);
System.out.println(a2);
}
}
class A implements Cloneable {
public StringBuffer sb = new StringBuffer("Welcome to ");
public String toString() {
return sb.toString();
}
public Object clone() {
try {
A a = (A) super.clone();
a.sb = new StringBuffer(sb.toString());
return a;
}
catch(CloneNotSupportedException e) {
}
return null;
}
}
Welcome to TutorialsPoint!
Welcome to
|
[
{
"code": null,
"e": 1711,
"s": 1062,
"text": "The clone() method is used to create a copy of an object of a class which implements Cloneable interface. By default, it does field-by-field copy as the Object class doesn't have any idea about the members of the particular class whose objects call this method. So, if the class has only primitive data type members then a new copy of the object will be created and the reference to the new object copy will be returned. But, if the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object."
},
{
"code": null,
"e": 2043,
"s": 1711,
"text": "We will get a CloneNotSupportedException if we try to call the clone() method on an object of a class that doesn't implement the Cloneable interface. This interface is a marker interface and the implementation of this interface simply indicates that the Object.clone() method can be called on the objects of the implementing class."
},
{
"code": null,
"e": 2102,
"s": 2043,
"text": "protected Object clone() throws CloneNotSupportedException"
},
{
"code": null,
"e": 2150,
"s": 2102,
"text": "We can implement the clone() method in two ways"
},
{
"code": null,
"e": 2485,
"s": 2150,
"text": "This is a result of the default cloning functionality provided by the Object.clone() method if the class has non-primitive data type members as well. In the case of Shallow Copy, the cloned object also refers to the same object to which the original object refers as only the object references get copied and not the referred objects."
},
{
"code": null,
"e": 3031,
"s": 2485,
"text": "public class ShallowCopyTest {\n public static void main(String args[]) {\n A a1 = new A();\n A a2 = (A) a1.clone();\n a1.sb.append(\"Tutorialspoint!\");\n System.out.println(a1);\n System.out.println(a2);\n }\n}\nclass A implements Cloneable {\n public StringBuffer sb = new StringBuffer(\"Welcome to \");\n public String toString() {\n return sb.toString();\n }\n public Object clone() {\n try {\n return super.clone();\n } catch(CloneNotSupportedException e) {\n }\n return null;\n }\n}"
},
{
"code": null,
"e": 3085,
"s": 3031,
"text": "Welcome to Tutorialspoint!\nWelcome to Tutorialspoint!"
},
{
"code": null,
"e": 3303,
"s": 3085,
"text": "We need to override the clone() method for the classes having non-primitive type members to achieve Deep Copy as it requires the member objects to be cloned as well, which is not done by the default cloning mechanism."
},
{
"code": null,
"e": 3915,
"s": 3303,
"text": "public class DeepCopyTest {\n public static void main(String args[]) {\n A a1 = new A();\n A a2 = (A) a1.clone();\n a1.sb.append(\" TutorialsPoint!\");\n System.out.println(a1);\n System.out.println(a2);\n }\n}\nclass A implements Cloneable {\n public StringBuffer sb = new StringBuffer(\"Welcome to \");\n public String toString() {\n return sb.toString();\n }\n public Object clone() {\n try {\n A a = (A) super.clone();\n a.sb = new StringBuffer(sb.toString());\n return a;\n }\n catch(CloneNotSupportedException e) {\n }\n return null;\n }\n}"
},
{
"code": null,
"e": 3953,
"s": 3915,
"text": "Welcome to TutorialsPoint!\nWelcome to"
}
] |
How can we remove a selected row from a JTable in Java?
|
A JTable is a subclass of JComponent class for displaying complex data structures. A JTable component can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener and RowSorterListener interfaces. We can remove a selected row from a JTable using the removeRow() method of the DefaultTableModel class.
public void removeRow(int row)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class RemoveSelectedRowTest extends JFrame {
private JTable table;
private DefaultTableModel model;
private Object[][] data;
private String[] columnNames;
private JButton button;
public RemoveSelectedRowTest() {
setTitle("RemoveSelectedRow Test");
data = new Object[][] {{"101", "Ramesh"}, {"102", "Adithya"}, {"103", "Jai"}, {"104", "Sai"}};
columnNames = new String[] {"ID", "Name"};
model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
button = new JButton("Remove");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
// check for selected row first
if(table.getSelectedRow() != -1) {
// remove selected row from the model
model.removeRow(table.getSelectedRow());
JOptionPane.showMessageDialog(null, "Selected row deleted successfully");
}
}
});
add(new JScrollPane(table), BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) {
new RemoveSelectedRowTest();
}
}
|
[
{
"code": null,
"e": 1515,
"s": 1062,
"text": "A JTable is a subclass of JComponent class for displaying complex data structures. A JTable component can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener and RowSorterListener interfaces. We can remove a selected row from a JTable using the removeRow() method of the DefaultTableModel class."
},
{
"code": null,
"e": 1546,
"s": 1515,
"text": "public void removeRow(int row)"
},
{
"code": null,
"e": 3051,
"s": 1546,
"text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport javax.swing.table.*;\npublic class RemoveSelectedRowTest extends JFrame {\n private JTable table;\n private DefaultTableModel model;\n private Object[][] data;\n private String[] columnNames;\n private JButton button;\n public RemoveSelectedRowTest() {\n setTitle(\"RemoveSelectedRow Test\");\n data = new Object[][] {{\"101\", \"Ramesh\"}, {\"102\", \"Adithya\"}, {\"103\", \"Jai\"}, {\"104\", \"Sai\"}};\n columnNames = new String[] {\"ID\", \"Name\"};\n model = new DefaultTableModel(data, columnNames);\n table = new JTable(model);\n table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);\n button = new JButton(\"Remove\");\n button.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent ae) {\n // check for selected row first\n if(table.getSelectedRow() != -1) {\n // remove selected row from the model\n model.removeRow(table.getSelectedRow());\n JOptionPane.showMessageDialog(null, \"Selected row deleted successfully\");\n }\n }\n });\n add(new JScrollPane(table), BorderLayout.CENTER);\n add(button, BorderLayout.SOUTH);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setSize(400, 300);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String args[]) {\n new RemoveSelectedRowTest();\n }\n}"
}
] |
Install Anaconda on MacOS Big Sur | by Alice Zhao | Towards Data Science
|
I got a new MacBook Pro today and one of the first things I installed was Anaconda, which currently comes with Python 3.8. Unforutantely, I ran into issues when I tried to use conda commands in the Terminal. This post walks through how to resolve those issues and start using Anaconda on Big Sur.
Anaconda Installation StepsThe Problem (zsh: command not found: conda)The Solution
Anaconda Installation Steps
The Problem (zsh: command not found: conda)
The Solution
You can skip this section if you’ve already installed Anaconda on your laptop.
Go to the Anaconda installation page. Scroll down to the Anaconda Installers section and click on the Graphical Installer under MacOS.
Once you finish downloading the installer onto your laptop, double click on the icon and keep on clicking Continue until you reach the end. If you’ve successfully installed Anaconda, you should see the Anaconda Navigator icon in your Applications.
After the install, I went to the Terminal, typed conda list and got my first error on my new laptop. 😭
zsh: command not found: conda
You would think that with a successful installation, conda commands should work in the Terminal. However, zsh is the new default shell on MacOS and you need to run two extra lines of code to make things work.
Here’s what my Terminal looked like when I got the error:
alice@Alices-MacBook-Pro ~ % conda listzsh: command not found: conda
Here’s what I typed in the Terminal to resolve the error (line 1 of 2):
source /opt/anaconda3/bin/activate
NOTE: I did the Graphical Installation of Anaconda and it put the anaconda3 folder within the /opt folder. If your anaconda3 folder happens to be somewhere else after your install, like the home directory for example, you would type source ~/anaconda3/bin/activate instead, with ~ meaning home directory.
Here’s the second line I typed in the Terminal (line 2 of 2):
conda init zsh
Close the Terminal window. When you open it back up again, you should see the little (base) prefix to tell you that you’re in the default base environment in Anaconda and you are all set! 🎉
(base) alice@Alices-MacBook-Pro ~ %
NOTE: I found many articles online saying to update the PATH variable, but Anaconda actually recommends against doing so and running the two commands above instead, which they state in their documentation.
|
[
{
"code": null,
"e": 469,
"s": 172,
"text": "I got a new MacBook Pro today and one of the first things I installed was Anaconda, which currently comes with Python 3.8. Unforutantely, I ran into issues when I tried to use conda commands in the Terminal. This post walks through how to resolve those issues and start using Anaconda on Big Sur."
},
{
"code": null,
"e": 552,
"s": 469,
"text": "Anaconda Installation StepsThe Problem (zsh: command not found: conda)The Solution"
},
{
"code": null,
"e": 580,
"s": 552,
"text": "Anaconda Installation Steps"
},
{
"code": null,
"e": 624,
"s": 580,
"text": "The Problem (zsh: command not found: conda)"
},
{
"code": null,
"e": 637,
"s": 624,
"text": "The Solution"
},
{
"code": null,
"e": 716,
"s": 637,
"text": "You can skip this section if you’ve already installed Anaconda on your laptop."
},
{
"code": null,
"e": 851,
"s": 716,
"text": "Go to the Anaconda installation page. Scroll down to the Anaconda Installers section and click on the Graphical Installer under MacOS."
},
{
"code": null,
"e": 1099,
"s": 851,
"text": "Once you finish downloading the installer onto your laptop, double click on the icon and keep on clicking Continue until you reach the end. If you’ve successfully installed Anaconda, you should see the Anaconda Navigator icon in your Applications."
},
{
"code": null,
"e": 1202,
"s": 1099,
"text": "After the install, I went to the Terminal, typed conda list and got my first error on my new laptop. 😭"
},
{
"code": null,
"e": 1232,
"s": 1202,
"text": "zsh: command not found: conda"
},
{
"code": null,
"e": 1441,
"s": 1232,
"text": "You would think that with a successful installation, conda commands should work in the Terminal. However, zsh is the new default shell on MacOS and you need to run two extra lines of code to make things work."
},
{
"code": null,
"e": 1499,
"s": 1441,
"text": "Here’s what my Terminal looked like when I got the error:"
},
{
"code": null,
"e": 1568,
"s": 1499,
"text": "alice@Alices-MacBook-Pro ~ % conda listzsh: command not found: conda"
},
{
"code": null,
"e": 1640,
"s": 1568,
"text": "Here’s what I typed in the Terminal to resolve the error (line 1 of 2):"
},
{
"code": null,
"e": 1675,
"s": 1640,
"text": "source /opt/anaconda3/bin/activate"
},
{
"code": null,
"e": 1980,
"s": 1675,
"text": "NOTE: I did the Graphical Installation of Anaconda and it put the anaconda3 folder within the /opt folder. If your anaconda3 folder happens to be somewhere else after your install, like the home directory for example, you would type source ~/anaconda3/bin/activate instead, with ~ meaning home directory."
},
{
"code": null,
"e": 2042,
"s": 1980,
"text": "Here’s the second line I typed in the Terminal (line 2 of 2):"
},
{
"code": null,
"e": 2057,
"s": 2042,
"text": "conda init zsh"
},
{
"code": null,
"e": 2247,
"s": 2057,
"text": "Close the Terminal window. When you open it back up again, you should see the little (base) prefix to tell you that you’re in the default base environment in Anaconda and you are all set! 🎉"
},
{
"code": null,
"e": 2283,
"s": 2247,
"text": "(base) alice@Alices-MacBook-Pro ~ %"
}
] |
Rexx - XML
|
XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of the operating system and/or developmental language. This is one of the most common languages used for exchanging data between applications.
The Extensible Markup Language XML is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard. XML is extremely useful for keeping track of small to medium amounts of data without requiring a SQL-based backbone.
For all our XML code examples, let's use the following simple XML file movies.xml for construction of the XML file and reading the file subsequently.
<collection shelf = "New Arrivals">
<movie title = "Enemy Behind">
<type>War, Thriller</type>
<format>DVD</format>
<year>2003</year>
<rating>PG</rating>
<stars>10</stars>
<description>Talk about a US-Japan war</description>
</movie>
<movie title = "Transformers">
<type>Anime, Science Fiction</type>
<format>DVD</format>
<year>1989</year>
<rating>R</rating>
<stars>8</stars>
<description>A schientific fiction</description>
</movie>
<movie title = "Trigun">
<type>Anime, Action</type>
<format>DVD</format>
<year>1986</year>
<rating>PG</rating>
<stars>10</stars>
<description>Vash the Stam pede!</description>
</movie>
<movie title = "Ishtar">
<type>Comedy</type>
<format>VHS</format>
<year>1987</year>
<rating>PG</rating>
<stars>2</stars>
<description>Viewable boredom </description>
</movie>
</collection>
By default, the xml functionality is not included in the Rexx interpreter. In order to work with XML in Rexx, the following steps need to be followed.
Download the following files −
Rexxxml − www.interlog.com/~ptjm/
Libxml2 − www.ctindustries.net/libxml/
iconv-1.9.2.win32 − www.xmlsoft.org/sources/win32/oldreleases/
libxslt-1.1.26.win32 − www.xmlsoft.org/sources/win32/oldreleases/
Download the following files −
Rexxxml − www.interlog.com/~ptjm/
Rexxxml − www.interlog.com/~ptjm/
Libxml2 − www.ctindustries.net/libxml/
Libxml2 − www.ctindustries.net/libxml/
iconv-1.9.2.win32 − www.xmlsoft.org/sources/win32/oldreleases/
iconv-1.9.2.win32 − www.xmlsoft.org/sources/win32/oldreleases/
libxslt-1.1.26.win32 − www.xmlsoft.org/sources/win32/oldreleases/
libxslt-1.1.26.win32 − www.xmlsoft.org/sources/win32/oldreleases/
Extract all of the files and ensure they are included in the system path.
Extract all of the files and ensure they are included in the system path.
Once all the files in the above section have been downloaded and successfully registered, the next step is to write the code to load the Rexx XML functions. This is done with the following code.
rcc = rxfuncadd('XMLLoadFuncs', 'rexxxml', 'xmlloadfuncs')
if rcc then do
say rxfuncerrmsg()
exit 1
end
call xmlloadfuncs
The following things can be noted about the above program −
The function rxfuncadd is used to load external libraries. The xmlloadfuncs function is used to load all the libraries in the rexxxml file into memory.
The function rxfuncadd is used to load external libraries. The xmlloadfuncs function is used to load all the libraries in the rexxxml file into memory.
If the value of rcc<>0, then it would result in an error. For this , we can call the rxfuncerrmsg to give us more details on the error message.
If the value of rcc<>0, then it would result in an error. For this , we can call the rxfuncerrmsg to give us more details on the error message.
We finally make a call to xmlloadfuncs, so that all xml related functionality can now be enabled in the Rexx program.
We finally make a call to xmlloadfuncs, so that all xml related functionality can now be enabled in the Rexx program.
Let’s look at the various methods available for XML in Rexx.
This method returns the version of the XML and XSLT libraries used on the system.
xmlVersion()
None
This method returns the version of the XML and XSLT libraries used on the system.
rcc = rxfuncadd('XMLLoadFuncs', 'rexxxml', 'xmlloadfuncs')
if rcc then do
say rxfuncerrmsg()
exit 1
end
call xmlloadfuncs
say xmlVersion()
When we run above program we will get the following result. This again depends on the version of the XML libraries being used on the system.
1.0.0 20631 10126
This function is used to parse the XML data sent to the function. The document tree is returned by the function.
xmlParseXML(filename)
Filename − This is the name of the XML file which needs to be parsed.
Filename − This is the name of the XML file which needs to be parsed.
The document tree is returned by the function. Else returns 0, if there is an error.
rcc = rxfuncadd('XMLLoadFuncs', 'rexxxml', 'xmlloadfuncs')
if rcc then do
say rxfuncerrmsg()
exit 1
end
call xmlloadfuncs
say xmlVersion()
sw = xmlParseXML('test.xml')
No general output.
This method evaluates the XPath expression passed to it. This is used for parsing the document tree to result a nodeset which can be processed further.
xmlParseXML(XPath,document)
XPath − This is the path of the node in the xml file.
XPath − This is the path of the node in the xml file.
document − This the XML document
document − This the XML document
Evaluates XPath expression and returns result as a nodeset which can be used later on.
rcc = rxfuncadd('XMLLoadFuncs', 'rexxxml', 'xmlloadfuncs')
if rcc then do
say rxfuncerrmsg()
exit 1
end
call xmlloadfuncs
say xmlVersion()
document = xmlParseXML('test.xml')
nodeset = xmlFindNode('//movie', document)
say xmlNodesetCount(nodeset)
When we run above program we will get the following result.
4
The output shows the number of movie nodes in our xml list
The below method is used to Evaluate an XPath expression and return a string as a result.
xmlParseXML(XPath,Node)
XPath − This is the path of the node in the xml file.
XPath − This is the path of the node in the xml file.
document − The specific node element.
document − The specific node element.
A string is returned based on the XPath expression sent to it.
rcc = rxfuncadd('XMLLoadFuncs', 'rexxxml', 'xmlloadfuncs')
if rcc then do
say rxfuncerrmsg()
exit 1
end
call xmlloadfuncs
document = xmlParseXML('test.xml')
nodeset = xmlFindNode('//movie', document)
do j = 1 to xmlNodesetCount(nodeset)
value = xmlEvalExpression('type', xmlNodesetItem(nodeset, j))
say value
end
When we run above program we will get the following result.
War, Thriller
Anime, Science Fiction
Anime, Action
Comedy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2621,
"s": 2339,
"text": "XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of the operating system and/or developmental language. This is one of the most common languages used for exchanging data between applications."
},
{
"code": null,
"e": 2906,
"s": 2621,
"text": "The Extensible Markup Language XML is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard. XML is extremely useful for keeping track of small to medium amounts of data without requiring a SQL-based backbone."
},
{
"code": null,
"e": 3056,
"s": 2906,
"text": "For all our XML code examples, let's use the following simple XML file movies.xml for construction of the XML file and reading the file subsequently."
},
{
"code": null,
"e": 4076,
"s": 3056,
"text": "<collection shelf = \"New Arrivals\"> \n <movie title = \"Enemy Behind\"> \n <type>War, Thriller</type> \n <format>DVD</format> \n <year>2003</year> \n <rating>PG</rating> \n <stars>10</stars> \n <description>Talk about a US-Japan war</description> \n </movie> \n \n <movie title = \"Transformers\"> \n <type>Anime, Science Fiction</type> \n <format>DVD</format> \n <year>1989</year> \n <rating>R</rating> \n <stars>8</stars> \n <description>A schientific fiction</description> \n </movie> \n \n <movie title = \"Trigun\"> \n <type>Anime, Action</type> \n <format>DVD</format> \n <year>1986</year> \n <rating>PG</rating> \n <stars>10</stars> \n <description>Vash the Stam pede!</description> \n </movie> \n \n <movie title = \"Ishtar\"> \n <type>Comedy</type> \n <format>VHS</format> \n <year>1987</year> \n <rating>PG</rating> \n <stars>2</stars> \n <description>Viewable boredom </description> \n </movie> \n</collection>"
},
{
"code": null,
"e": 4227,
"s": 4076,
"text": "By default, the xml functionality is not included in the Rexx interpreter. In order to work with XML in Rexx, the following steps need to be followed."
},
{
"code": null,
"e": 4463,
"s": 4227,
"text": "Download the following files −\n\nRexxxml − www.interlog.com/~ptjm/\nLibxml2 − www.ctindustries.net/libxml/\niconv-1.9.2.win32 − www.xmlsoft.org/sources/win32/oldreleases/\nlibxslt-1.1.26.win32 − www.xmlsoft.org/sources/win32/oldreleases/\n\n"
},
{
"code": null,
"e": 4494,
"s": 4463,
"text": "Download the following files −"
},
{
"code": null,
"e": 4528,
"s": 4494,
"text": "Rexxxml − www.interlog.com/~ptjm/"
},
{
"code": null,
"e": 4562,
"s": 4528,
"text": "Rexxxml − www.interlog.com/~ptjm/"
},
{
"code": null,
"e": 4601,
"s": 4562,
"text": "Libxml2 − www.ctindustries.net/libxml/"
},
{
"code": null,
"e": 4640,
"s": 4601,
"text": "Libxml2 − www.ctindustries.net/libxml/"
},
{
"code": null,
"e": 4703,
"s": 4640,
"text": "iconv-1.9.2.win32 − www.xmlsoft.org/sources/win32/oldreleases/"
},
{
"code": null,
"e": 4766,
"s": 4703,
"text": "iconv-1.9.2.win32 − www.xmlsoft.org/sources/win32/oldreleases/"
},
{
"code": null,
"e": 4832,
"s": 4766,
"text": "libxslt-1.1.26.win32 − www.xmlsoft.org/sources/win32/oldreleases/"
},
{
"code": null,
"e": 4898,
"s": 4832,
"text": "libxslt-1.1.26.win32 − www.xmlsoft.org/sources/win32/oldreleases/"
},
{
"code": null,
"e": 4972,
"s": 4898,
"text": "Extract all of the files and ensure they are included in the system path."
},
{
"code": null,
"e": 5046,
"s": 4972,
"text": "Extract all of the files and ensure they are included in the system path."
},
{
"code": null,
"e": 5241,
"s": 5046,
"text": "Once all the files in the above section have been downloaded and successfully registered, the next step is to write the code to load the Rexx XML functions. This is done with the following code."
},
{
"code": null,
"e": 5375,
"s": 5241,
"text": "rcc = rxfuncadd('XMLLoadFuncs', 'rexxxml', 'xmlloadfuncs') \n\nif rcc then do \n say rxfuncerrmsg() \n exit 1 \nend \ncall xmlloadfuncs"
},
{
"code": null,
"e": 5435,
"s": 5375,
"text": "The following things can be noted about the above program −"
},
{
"code": null,
"e": 5587,
"s": 5435,
"text": "The function rxfuncadd is used to load external libraries. The xmlloadfuncs function is used to load all the libraries in the rexxxml file into memory."
},
{
"code": null,
"e": 5739,
"s": 5587,
"text": "The function rxfuncadd is used to load external libraries. The xmlloadfuncs function is used to load all the libraries in the rexxxml file into memory."
},
{
"code": null,
"e": 5883,
"s": 5739,
"text": "If the value of rcc<>0, then it would result in an error. For this , we can call the rxfuncerrmsg to give us more details on the error message."
},
{
"code": null,
"e": 6027,
"s": 5883,
"text": "If the value of rcc<>0, then it would result in an error. For this , we can call the rxfuncerrmsg to give us more details on the error message."
},
{
"code": null,
"e": 6145,
"s": 6027,
"text": "We finally make a call to xmlloadfuncs, so that all xml related functionality can now be enabled in the Rexx program."
},
{
"code": null,
"e": 6263,
"s": 6145,
"text": "We finally make a call to xmlloadfuncs, so that all xml related functionality can now be enabled in the Rexx program."
},
{
"code": null,
"e": 6324,
"s": 6263,
"text": "Let’s look at the various methods available for XML in Rexx."
},
{
"code": null,
"e": 6406,
"s": 6324,
"text": "This method returns the version of the XML and XSLT libraries used on the system."
},
{
"code": null,
"e": 6420,
"s": 6406,
"text": "xmlVersion()\n"
},
{
"code": null,
"e": 6425,
"s": 6420,
"text": "None"
},
{
"code": null,
"e": 6507,
"s": 6425,
"text": "This method returns the version of the XML and XSLT libraries used on the system."
},
{
"code": null,
"e": 6660,
"s": 6507,
"text": "rcc = rxfuncadd('XMLLoadFuncs', 'rexxxml', 'xmlloadfuncs') \n\nif rcc then do \n say rxfuncerrmsg() \n exit 1 \nend \ncall xmlloadfuncs \nsay xmlVersion() "
},
{
"code": null,
"e": 6801,
"s": 6660,
"text": "When we run above program we will get the following result. This again depends on the version of the XML libraries being used on the system."
},
{
"code": null,
"e": 6821,
"s": 6801,
"text": "1.0.0 20631 10126 \n"
},
{
"code": null,
"e": 6934,
"s": 6821,
"text": "This function is used to parse the XML data sent to the function. The document tree is returned by the function."
},
{
"code": null,
"e": 6958,
"s": 6934,
"text": "xmlParseXML(filename) \n"
},
{
"code": null,
"e": 7028,
"s": 6958,
"text": "Filename − This is the name of the XML file which needs to be parsed."
},
{
"code": null,
"e": 7098,
"s": 7028,
"text": "Filename − This is the name of the XML file which needs to be parsed."
},
{
"code": null,
"e": 7183,
"s": 7098,
"text": "The document tree is returned by the function. Else returns 0, if there is an error."
},
{
"code": null,
"e": 7367,
"s": 7183,
"text": "rcc = rxfuncadd('XMLLoadFuncs', 'rexxxml', 'xmlloadfuncs') \n\nif rcc then do \n say rxfuncerrmsg() \n exit 1 \nend \ncall xmlloadfuncs \n\nsay xmlVersion() \nsw = xmlParseXML('test.xml') "
},
{
"code": null,
"e": 7386,
"s": 7367,
"text": "No general output."
},
{
"code": null,
"e": 7538,
"s": 7386,
"text": "This method evaluates the XPath expression passed to it. This is used for parsing the document tree to result a nodeset which can be processed further."
},
{
"code": null,
"e": 7568,
"s": 7538,
"text": "xmlParseXML(XPath,document) \n"
},
{
"code": null,
"e": 7622,
"s": 7568,
"text": "XPath − This is the path of the node in the xml file."
},
{
"code": null,
"e": 7676,
"s": 7622,
"text": "XPath − This is the path of the node in the xml file."
},
{
"code": null,
"e": 7709,
"s": 7676,
"text": "document − This the XML document"
},
{
"code": null,
"e": 7742,
"s": 7709,
"text": "document − This the XML document"
},
{
"code": null,
"e": 7829,
"s": 7742,
"text": "Evaluates XPath expression and returns result as a nodeset which can be used later on."
},
{
"code": null,
"e": 8091,
"s": 7829,
"text": "rcc = rxfuncadd('XMLLoadFuncs', 'rexxxml', 'xmlloadfuncs') \n\nif rcc then do \n say rxfuncerrmsg() \n exit 1 \nend \ncall xmlloadfuncs\n\nsay xmlVersion() \ndocument = xmlParseXML('test.xml') \nnodeset = xmlFindNode('//movie', document) \nsay xmlNodesetCount(nodeset)"
},
{
"code": null,
"e": 8151,
"s": 8091,
"text": "When we run above program we will get the following result."
},
{
"code": null,
"e": 8154,
"s": 8151,
"text": "4\n"
},
{
"code": null,
"e": 8213,
"s": 8154,
"text": "The output shows the number of movie nodes in our xml list"
},
{
"code": null,
"e": 8303,
"s": 8213,
"text": "The below method is used to Evaluate an XPath expression and return a string as a result."
},
{
"code": null,
"e": 8329,
"s": 8303,
"text": "xmlParseXML(XPath,Node) \n"
},
{
"code": null,
"e": 8383,
"s": 8329,
"text": "XPath − This is the path of the node in the xml file."
},
{
"code": null,
"e": 8437,
"s": 8383,
"text": "XPath − This is the path of the node in the xml file."
},
{
"code": null,
"e": 8475,
"s": 8437,
"text": "document − The specific node element."
},
{
"code": null,
"e": 8513,
"s": 8475,
"text": "document − The specific node element."
},
{
"code": null,
"e": 8576,
"s": 8513,
"text": "A string is returned based on the XPath expression sent to it."
},
{
"code": null,
"e": 8908,
"s": 8576,
"text": "rcc = rxfuncadd('XMLLoadFuncs', 'rexxxml', 'xmlloadfuncs') \n\nif rcc then do \n say rxfuncerrmsg() \n exit 1 \nend \ncall xmlloadfuncs \n\ndocument = xmlParseXML('test.xml') \nnodeset = xmlFindNode('//movie', document) \ndo j = 1 to xmlNodesetCount(nodeset) \nvalue = xmlEvalExpression('type', xmlNodesetItem(nodeset, j)) \nsay value \nend"
},
{
"code": null,
"e": 8968,
"s": 8908,
"text": "When we run above program we will get the following result."
},
{
"code": null,
"e": 9031,
"s": 8968,
"text": "War, Thriller \nAnime, Science Fiction \nAnime, Action \nComedy \n"
},
{
"code": null,
"e": 9038,
"s": 9031,
"text": " Print"
},
{
"code": null,
"e": 9049,
"s": 9038,
"text": " Add Notes"
}
] |
XGBoost for Multi-class Classification | by Ernest Ng | Towards Data Science
|
Customer touch points are your brand’s points of customer contact, from start to finish. For example, customers may find your business through mail discount, SMS, email promotions etc. There are many types of touch points depending on your company’s marketing team!
Touch point prediction is an important tool similar to customer segmentation because it allows for a company’s marketing efforts to be better served if they target specific customer groups with touch points that have a higher chance of ending in a purchase. Through their customers’ profile, companies will have a deeper understanding of the customers’ preferences and execute accurately tailored marketing materials towards each of them.
The aim of this project is to predict the next best touch point action for each customer based on their profile and previous touch point. Let us see what we have to work with!
I like taking notes when I am exploring a dataset, this allows me to keep a checklist of things to clean/explore further later in the project. From the first look, we can see that there are missing values in the SocialMedia column and under the touch points column, we see a sequence of touch points that might have led to a purchase.
Check for missing values and imputation!
We see that 25% of entries do not have touch points and 2.9% of entries do not have credit rating. Missing touch points could mean that the customers purchased without having to go through any online promotion links etc. The lack of credit rating might point to new customers.
I also noted that missing values under SocialMedia column were denoted with empty spaces.
Treating missing values for each column:1. SocialMedia — change ‘ ‘ to ‘U’ (denotes Unknown social media status)2. creditRating — change NaN to ‘New’ (denotes new customers)3. touchpoints — I assume that the touch points are stated in order from left to right, so the last value is the most recent touchpoint for a customer before making a purchase. I will hence take only the last value as labels to predict which touchpoint should be assigned for a future customer
data = df[df['nTouchpoints']!=0].reset_index().drop('index', axis=1)data['recent_touchpoint'] = data['touchpoints'].apply(lambda x: x.split()[-1])data.recent_touchpoint.value_counts()
I would like to explore the relationship of the segment variable with other variables in my dataset. Some possibilities could be segmentation based on income, average spending, credit rating or a combination. We have to check for any multicollinearity between any of our variables. Multicollinearity reduces the precision of the estimate coefficients, which weakens the statistical power of our regression model. I will explore these relationships with graphs and heat maps.
There isn’t a general pattern we can observe with average spending over each credit ratings as seen from each line plot for P1 to P4. The purple line shows us mean average spending per credit rating group and its 95% confidence interval. Comparing both plots, it seems that the high earners with credit rating of 6 spends less than others, and low earners with credit rating of 7 spends more than others.
We see that number of touch points is highly correlated with average spending however the correlation is low-moderate below 0.5. Since the degree of multicollinearity is not severe, I will leave the variables untouched.
Skewed distributions can be a pain in the ass when you are building your model, especially with outliers in the way. The best way to check for any outliers is to plot the distribution! A general rule in Machine Learning is to ensure that all our numerical variables are approximately in the same range and normally distributed so we have to do normalisation/standardisation.
Some observations that I made:
1. Age distribution looks normally distributed with slight left skew2. Number of married > single > divorced > unknown customers.3. Approximately same number of customers in each category for segment and SocialMedia.4. Distribution of customers across credit ratings looks normal with slight right skew.5. Most customers go through only 1 touchpoint6. Distribution of income looks normal.7. Average spending distribution can be considered exponential but there are obviously outliers that we have to deal with.
I remove all customers earning $18156.7 because our median aveSpend is only at 91.52 which is far from the max value. Leaving them in the data will only skew our aveSpend distribution. When removing outliers, we must ensure that the mean/median will not largely affected and take note that we do not introduce any bias.
Note that the max-min range of all 3 variables are very different from one another. When we do further analysis, like multivariate linear regression, for example, the attributed income will intrinsically influence the result more due to its larger value. Hence, it is important to standardise and normalise the data to bring all variables to the same range.
I use a Robust Scaler (QuantileTransformer): similar to normalisation but it instead uses the interquartile range, so that it is robust to outliers.
We use one-hot encoding to convert categorical variables (marital, segment, SocialMedia, creditRating) into binary variables. We can use the in built OneHotEncoder from sklearn but I chose to write my own functions for the same purpose!
Now our numerical variables follow a normal distribution. We will start labelling our data using the most recent touchpoint. Let us see how many possible labels are there in our data.
Create a mapping from labels to a unique integer and vice versa for labelling and prediction later
For our model data, select columns we want to use in our model and I will use stratified sampling to retrieve them. For more details on stratified sampling, I explained the procedure in my previous post — Keras, Tell Me The Genre Of My Book.
As the baseline model, I used Random Forest. A baseline is a method that uses heuristics, simple summary statistics, randomness, or machine learning to create predictions for a dataset. You can use these predictions to measure the baseline’s performance (e.g., accuracy) — this metric will then become what you compare any other machine learning algorithm against. In this case, I used multi class logistic loss since we predicting the probabilities of the next touchpoint, I want to find the average difference between all probability distributions. In addition, I also used micro F1-score since we have imbalanced classes of labels.
I picked Random Forest Classifier simply because it runs fast and I am able to use GridSearchCV to iterate to the best model possible efficiently. After initialising and tuning my RandomForestClassifier model with GridSearchCV, I got a train accuracy of 1.0 and test accuracy of 0.77688 which shows overfitting.
Our Random Forest Classifier seems to pay more attention to average spending, income and age.
XGBoost is a decision-tree-based ensemble Machine Learning algorithm that uses a gradient boosting framework. In prediction problems involving unstructured data (images, text, etc.) artificial neural networks tend to outperform all other algorithms or frameworks. However, when it comes to small-to-medium structured/tabular data, decision tree based algorithms are considered best-in-class right now.
The implementation of XGBoost offers several advanced features for model tuning, computing environments and algorithm enhancement. It is capable of performing the three main forms of gradient boosting (Gradient Boosting (GB), Stochastic GB and Regularised GB) and it is robust enough to support fine tuning and addition of regularisation parameters.
This ensemble method seeks to create a strong classifier based on previous ‘weaker’ classifiers. By adding models on top of each other iteratively, the errors of the previous model are corrected by the next predictor, until the training data is accurately predicted or reproduced by the model. Long story short, we are updating the model using gradient descent! XGBoost has been the not-so-secret recipe to winning many Kaggle competitions so now you know why this method is so popular amongst Machine Learning enthusiast.
For our initial model, this were the results I got.
As we can see, XGBoost already outperforms Random Forest on the first model iteration. Let us start fine tuning our model, although I will not go into details on how I tune my model. More information on step-by-step tuning can be found here!
Parameters that I tuned:
min_child_weight: Minimum number of samples that a node can represent in order to be split further
max_depth: Tune this to avoid our tree from growing too deep and resulting in overfitting
reg_alpha: Degree of regularisation
Compared to our first iteration of the XGBoost model, we managed to improve slightly in terms of accuracy and micro F1-score. We achieved lower multi class logistic loss and classification error!
We see that a high feature importance score is assigned to ‘unknown’ marital status. This could be due to the fact that there are only 44 customers with ‘unknown’ marital status, hence to reduce bias, our XGBoost model assigns more weight to ‘unknown’ feature.
I will tune gamma, subsample and colsample_bytree and learning rate if I had enough computational power. Due to the limited time I have, I only focus on max_depth and reg_alpha (applying regularisation to reduce overfitting). Try it out and play around with the parameters!
Full code implementation can be found on my Github here!
Thank you for reading my article. I would appreciate it if I could get comments on how I can improve my Data Science projects and I am always looking to collaborate with anyone with an interest in Machine Learning too :)
|
[
{
"code": null,
"e": 438,
"s": 172,
"text": "Customer touch points are your brand’s points of customer contact, from start to finish. For example, customers may find your business through mail discount, SMS, email promotions etc. There are many types of touch points depending on your company’s marketing team!"
},
{
"code": null,
"e": 877,
"s": 438,
"text": "Touch point prediction is an important tool similar to customer segmentation because it allows for a company’s marketing efforts to be better served if they target specific customer groups with touch points that have a higher chance of ending in a purchase. Through their customers’ profile, companies will have a deeper understanding of the customers’ preferences and execute accurately tailored marketing materials towards each of them."
},
{
"code": null,
"e": 1053,
"s": 877,
"text": "The aim of this project is to predict the next best touch point action for each customer based on their profile and previous touch point. Let us see what we have to work with!"
},
{
"code": null,
"e": 1388,
"s": 1053,
"text": "I like taking notes when I am exploring a dataset, this allows me to keep a checklist of things to clean/explore further later in the project. From the first look, we can see that there are missing values in the SocialMedia column and under the touch points column, we see a sequence of touch points that might have led to a purchase."
},
{
"code": null,
"e": 1429,
"s": 1388,
"text": "Check for missing values and imputation!"
},
{
"code": null,
"e": 1706,
"s": 1429,
"text": "We see that 25% of entries do not have touch points and 2.9% of entries do not have credit rating. Missing touch points could mean that the customers purchased without having to go through any online promotion links etc. The lack of credit rating might point to new customers."
},
{
"code": null,
"e": 1796,
"s": 1706,
"text": "I also noted that missing values under SocialMedia column were denoted with empty spaces."
},
{
"code": null,
"e": 2263,
"s": 1796,
"text": "Treating missing values for each column:1. SocialMedia — change ‘ ‘ to ‘U’ (denotes Unknown social media status)2. creditRating — change NaN to ‘New’ (denotes new customers)3. touchpoints — I assume that the touch points are stated in order from left to right, so the last value is the most recent touchpoint for a customer before making a purchase. I will hence take only the last value as labels to predict which touchpoint should be assigned for a future customer"
},
{
"code": null,
"e": 2447,
"s": 2263,
"text": "data = df[df['nTouchpoints']!=0].reset_index().drop('index', axis=1)data['recent_touchpoint'] = data['touchpoints'].apply(lambda x: x.split()[-1])data.recent_touchpoint.value_counts()"
},
{
"code": null,
"e": 2922,
"s": 2447,
"text": "I would like to explore the relationship of the segment variable with other variables in my dataset. Some possibilities could be segmentation based on income, average spending, credit rating or a combination. We have to check for any multicollinearity between any of our variables. Multicollinearity reduces the precision of the estimate coefficients, which weakens the statistical power of our regression model. I will explore these relationships with graphs and heat maps."
},
{
"code": null,
"e": 3327,
"s": 2922,
"text": "There isn’t a general pattern we can observe with average spending over each credit ratings as seen from each line plot for P1 to P4. The purple line shows us mean average spending per credit rating group and its 95% confidence interval. Comparing both plots, it seems that the high earners with credit rating of 6 spends less than others, and low earners with credit rating of 7 spends more than others."
},
{
"code": null,
"e": 3547,
"s": 3327,
"text": "We see that number of touch points is highly correlated with average spending however the correlation is low-moderate below 0.5. Since the degree of multicollinearity is not severe, I will leave the variables untouched."
},
{
"code": null,
"e": 3922,
"s": 3547,
"text": "Skewed distributions can be a pain in the ass when you are building your model, especially with outliers in the way. The best way to check for any outliers is to plot the distribution! A general rule in Machine Learning is to ensure that all our numerical variables are approximately in the same range and normally distributed so we have to do normalisation/standardisation."
},
{
"code": null,
"e": 3953,
"s": 3922,
"text": "Some observations that I made:"
},
{
"code": null,
"e": 4464,
"s": 3953,
"text": "1. Age distribution looks normally distributed with slight left skew2. Number of married > single > divorced > unknown customers.3. Approximately same number of customers in each category for segment and SocialMedia.4. Distribution of customers across credit ratings looks normal with slight right skew.5. Most customers go through only 1 touchpoint6. Distribution of income looks normal.7. Average spending distribution can be considered exponential but there are obviously outliers that we have to deal with."
},
{
"code": null,
"e": 4784,
"s": 4464,
"text": "I remove all customers earning $18156.7 because our median aveSpend is only at 91.52 which is far from the max value. Leaving them in the data will only skew our aveSpend distribution. When removing outliers, we must ensure that the mean/median will not largely affected and take note that we do not introduce any bias."
},
{
"code": null,
"e": 5142,
"s": 4784,
"text": "Note that the max-min range of all 3 variables are very different from one another. When we do further analysis, like multivariate linear regression, for example, the attributed income will intrinsically influence the result more due to its larger value. Hence, it is important to standardise and normalise the data to bring all variables to the same range."
},
{
"code": null,
"e": 5291,
"s": 5142,
"text": "I use a Robust Scaler (QuantileTransformer): similar to normalisation but it instead uses the interquartile range, so that it is robust to outliers."
},
{
"code": null,
"e": 5528,
"s": 5291,
"text": "We use one-hot encoding to convert categorical variables (marital, segment, SocialMedia, creditRating) into binary variables. We can use the in built OneHotEncoder from sklearn but I chose to write my own functions for the same purpose!"
},
{
"code": null,
"e": 5712,
"s": 5528,
"text": "Now our numerical variables follow a normal distribution. We will start labelling our data using the most recent touchpoint. Let us see how many possible labels are there in our data."
},
{
"code": null,
"e": 5811,
"s": 5712,
"text": "Create a mapping from labels to a unique integer and vice versa for labelling and prediction later"
},
{
"code": null,
"e": 6053,
"s": 5811,
"text": "For our model data, select columns we want to use in our model and I will use stratified sampling to retrieve them. For more details on stratified sampling, I explained the procedure in my previous post — Keras, Tell Me The Genre Of My Book."
},
{
"code": null,
"e": 6688,
"s": 6053,
"text": "As the baseline model, I used Random Forest. A baseline is a method that uses heuristics, simple summary statistics, randomness, or machine learning to create predictions for a dataset. You can use these predictions to measure the baseline’s performance (e.g., accuracy) — this metric will then become what you compare any other machine learning algorithm against. In this case, I used multi class logistic loss since we predicting the probabilities of the next touchpoint, I want to find the average difference between all probability distributions. In addition, I also used micro F1-score since we have imbalanced classes of labels."
},
{
"code": null,
"e": 7000,
"s": 6688,
"text": "I picked Random Forest Classifier simply because it runs fast and I am able to use GridSearchCV to iterate to the best model possible efficiently. After initialising and tuning my RandomForestClassifier model with GridSearchCV, I got a train accuracy of 1.0 and test accuracy of 0.77688 which shows overfitting."
},
{
"code": null,
"e": 7094,
"s": 7000,
"text": "Our Random Forest Classifier seems to pay more attention to average spending, income and age."
},
{
"code": null,
"e": 7496,
"s": 7094,
"text": "XGBoost is a decision-tree-based ensemble Machine Learning algorithm that uses a gradient boosting framework. In prediction problems involving unstructured data (images, text, etc.) artificial neural networks tend to outperform all other algorithms or frameworks. However, when it comes to small-to-medium structured/tabular data, decision tree based algorithms are considered best-in-class right now."
},
{
"code": null,
"e": 7846,
"s": 7496,
"text": "The implementation of XGBoost offers several advanced features for model tuning, computing environments and algorithm enhancement. It is capable of performing the three main forms of gradient boosting (Gradient Boosting (GB), Stochastic GB and Regularised GB) and it is robust enough to support fine tuning and addition of regularisation parameters."
},
{
"code": null,
"e": 8369,
"s": 7846,
"text": "This ensemble method seeks to create a strong classifier based on previous ‘weaker’ classifiers. By adding models on top of each other iteratively, the errors of the previous model are corrected by the next predictor, until the training data is accurately predicted or reproduced by the model. Long story short, we are updating the model using gradient descent! XGBoost has been the not-so-secret recipe to winning many Kaggle competitions so now you know why this method is so popular amongst Machine Learning enthusiast."
},
{
"code": null,
"e": 8421,
"s": 8369,
"text": "For our initial model, this were the results I got."
},
{
"code": null,
"e": 8663,
"s": 8421,
"text": "As we can see, XGBoost already outperforms Random Forest on the first model iteration. Let us start fine tuning our model, although I will not go into details on how I tune my model. More information on step-by-step tuning can be found here!"
},
{
"code": null,
"e": 8688,
"s": 8663,
"text": "Parameters that I tuned:"
},
{
"code": null,
"e": 8787,
"s": 8688,
"text": "min_child_weight: Minimum number of samples that a node can represent in order to be split further"
},
{
"code": null,
"e": 8877,
"s": 8787,
"text": "max_depth: Tune this to avoid our tree from growing too deep and resulting in overfitting"
},
{
"code": null,
"e": 8913,
"s": 8877,
"text": "reg_alpha: Degree of regularisation"
},
{
"code": null,
"e": 9109,
"s": 8913,
"text": "Compared to our first iteration of the XGBoost model, we managed to improve slightly in terms of accuracy and micro F1-score. We achieved lower multi class logistic loss and classification error!"
},
{
"code": null,
"e": 9370,
"s": 9109,
"text": "We see that a high feature importance score is assigned to ‘unknown’ marital status. This could be due to the fact that there are only 44 customers with ‘unknown’ marital status, hence to reduce bias, our XGBoost model assigns more weight to ‘unknown’ feature."
},
{
"code": null,
"e": 9644,
"s": 9370,
"text": "I will tune gamma, subsample and colsample_bytree and learning rate if I had enough computational power. Due to the limited time I have, I only focus on max_depth and reg_alpha (applying regularisation to reduce overfitting). Try it out and play around with the parameters!"
},
{
"code": null,
"e": 9701,
"s": 9644,
"text": "Full code implementation can be found on my Github here!"
}
] |
unordered_multimap and its application
|
16 Jun, 2022
Allows Duplicates: We have discussed unordered_map in our previous post, but there is a limitation, we can not store duplicates in unordered_map, that is if we have a key-value pair already in our unordered_multimap and another pair is inserted, then both will be there whereas in case of unordered_map the previous value corresponding to the key is updated by the new value that is only would be there. Even can exist in unordered_multimap twice.
Internal Representation: The internal implementation of unordered_multimap is the same as that of unordered_map but for duplicate keys, another count value is maintained with each key-value pair. As pairs are stored in the hash table, there is no particular order among them but pairs with the same keys come together in the data structure whereas pairs with the same values are not guaranteed to come together.
Time Complexity: All operation on unordered_multimap takes a constant amount of time on average but time can go to linear in the worst case depending on internally used hash function but in long run unordered_multimap outperforms multimap (tree-based multimap).
Functions: unordered_multimap supports many functions which are demonstrated in the below code :
CPP
// C++ program to demonstrate various function of// unordered_multimap#include <bits/stdc++.h>using namespace std; // making typedef for short declarationtypedef unordered_multimap<string, int>::iterator unit; // Utility function to print unordered_multimapvoid printUmm(unordered_multimap<string, int> umm){ // begin() returns iterator to first element of map unit it = umm.begin(); for (; it != umm.end(); it++){ cout << "<" << it->first << ", " << it->second << "> "; cout << endl; }} // Driver codeint main(){ // empty initialization unordered_multimap<string, int> umm1; // Initialization by initializer list unordered_multimap<string, int> umm2( { { "apple", 1 }, { "ball", 2 }, { "apple", 10 }, { "cat", 7 }, { "dog", 9 }, { "cat", 6 }, { "apple", 1 } }); // Initialization by assignment operation umm1 = umm2; printUmm(umm1); // empty returns true, if container is empty else it // returns false if (umm2.empty()) cout << "unordered multimap 2 is empty\n"; else cout << "unordered multimap 2 is not empty\n"; // size returns total number of elements in container cout << "Size of unordered multimap 1 is " << umm1.size() << endl; string key = "apple"; // find and return any pair, associated with key unit it = umm1.find(key); if (it != umm1.end()) { cout << "\nkey " << key << " is there in unordered " << " multimap 1\n"; cout << "\none of the value associated with " << key << " is " << it->second << endl; } else cout << "\nkey " << key << " is not there in unordered" << " multimap 1\n"; // count returns count of total number of pair // associated with key int cnt = umm1.count(key); cout << "\ntotal values associated with " << key << " are " << cnt << "\n\n"; printUmm(umm2); // one insertion by making pair explicitly umm2.insert(make_pair("dog", 11)); // insertion by initializer list umm2.insert({ { "alpha", 12 }, { "beta", 33 } }); cout << "\nAfter insertion of <alpha, 12> and <beta, " "33>\n"; printUmm(umm2); // erase deletes all pairs corresponding to key umm2.erase("apple"); cout << "\nAfter deletion of apple\n"; printUmm(umm2); // clear deletes all pairs from container umm1.clear(); umm2.clear(); if (umm2.empty()) cout << "\nunordered multimap 2 is empty\n"; else cout << "\nunordered multimap 2 is not empty\n";}
<dog, 9>
<cat, 6>
<cat, 7>
<ball, 2>
<apple, 1>
<apple, 10>
<apple, 1>
unordered multimap 2 is not empty
Size of unordered multimap 1 is 7
key apple is there in unordered multimap 1
one of the value associated with apple is 1
total values associated with apple are 3
<dog, 9>
<cat, 6>
<cat, 7>
<ball, 2>
<apple, 1>
<apple, 10>
<apple, 1>
After insertion of <alpha, 12> and <beta, 33>
<alpha, 12>
<dog, 11>
<dog, 9>
<beta, 33>
<cat, 6>
<cat, 7>
<ball, 2>
<apple, 1>
<apple, 10>
<apple, 1>
After deletion of apple
<alpha, 12>
<dog, 11>
<dog, 9>
<beta, 33>
<cat, 6>
<cat, 7>
<ball, 2>
unordered multimap 2 is empty
As we can see in the above code most of the operations work similar to unordered_map but some things to note are : We can use the initializer list for initializing and inserting many pairs at once. There is no [] operator for unordered_multimap because values corresponding to a key are not unique, there can be many values associated with a single key so [] operator can not be applied to them. Erase function deletes all instances of values associated with the supplied key. Find function returns an iterator to any instance of key-value pair among all pairs associated with that key.
How to access/delete a specific value for a key? If we want to check whether a specific value is there or not, we need to loop over all pairs of key-value until we get our specific value, if we get our specific value in the unordered_multimap then use erase(position) method to delete that specific value from unordered_multimap.
CPP
// C++ program to erase particular value.#include <bits/stdc++.h>using namespace std; // Utility function to print unordered_multimapvoid printUmm(unordered_multimap<string, int>& umm){ // Iterator pointing to first element of unordered_map auto it1 = umm.begin(); for (; it1 != umm.end(); it1++) { cout << "<" << it1->first << ", " << it1->second << "> "; cout << endl; }} int main(){ // Initialization by intializer list unordered_multimap<string, int> umm{ { "apple", 1 }, { "ball", 2 }, { "apple", 10 }, { "cat", 7 }, { "dog", 9 }, { "cat", 6 }, { "apple", 1 } }; // Iterator pointing to first element of unordered_map auto it = umm.begin(); // Search for an element with value 1 while (it != umm.end()) { if (it->second == 1) break; it++; } // Erase the element pointed by iterator it if (it != umm.end()) umm.erase(it); cout << "After deletion of value 1 from umm" << endl; printUmm(umm); return 0;}
After deletion of value 1 from umm
<dog, 9>
<cat, 6>
<cat, 7>
<ball, 2>
<apple, 10>
<apple, 1>
Methods of unordered_multimap:
begin()– Returns an iterator pointing to the first element in the container or to the first element in one of its bucket.
end()– Returns an iterator pointing to the position after the last element in the container or to the position after the last element in one of its bucket.
count()– Returns the number of elements in the container whose key is equal to the key passed in the parameter.
cbegin()– Returns a constant iterator pointing to the first element in the container or to the first element in one of its bucket.
cend()– Returns a constant iterator pointing to the position after the last element in the container or to the position after the last element in one of its bucket.
clear() – Clears the contents of the unordered_multimap container.
size()– Returns the size of the unordered_multimap. It denotes the number of elements in that container.
swap()– Swaps the contents of two unordered_multimap containers. The sizes can differ of both the containers.
find()– Returns an iterator which points to one of the elements which have the key k.
bucket_size()– Returns the number of elements in the bucket n.
empty()– It returns true if the unordered_multimap container is empty. Otherwise, it returns false.
equal_range()– Returns the range in which all the element’s key is equal to a key.
operator=– Copy/Assign/Move elements from different container.
max_size()– Returns the maximum number of elements that the unordered_multimap container can hold.
load_factor()– Returns the current load factor in the unordered_multimap container.
key_eq()– Returns a boolean value according to the comparison.
emplace()– Inserts a new {key, element} in the unordered_multimap container.
emplace_hint()– Inserts a new {key:element} in the unordered_multimap container.
bucket_count()– Returns the total number of buckets in the unordered_multimap container.
bucket()– Returns the bucket number in which a given key is.
max_load_factor()– Returns the maximum load factor of the unordered_multimap container.
rehash()– Sets the number of buckets in the container to N or more.
reserve()– Sets the number of buckets in the container (bucket_count) to the most appropriate number so that it contains at least n elements.
hash_function()– This hash function is a unary function that takes a single argument only and returns a unique value of type size_t based on it.
max_bucket_count()– Returns the maximum number of buckets that the unordered multimap container can have.
Recent articles on unordered_multimapThis article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
shubhamgandhi
saurabh1990aror
carhantersen
germanshephered48
harendrakumar123
simmytarika5
cpp-containers-library
CPP-Library
cpp-unordered_multimap
STL
C Language
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 502,
"s": 54,
"text": "Allows Duplicates: We have discussed unordered_map in our previous post, but there is a limitation, we can not store duplicates in unordered_map, that is if we have a key-value pair already in our unordered_multimap and another pair is inserted, then both will be there whereas in case of unordered_map the previous value corresponding to the key is updated by the new value that is only would be there. Even can exist in unordered_multimap twice."
},
{
"code": null,
"e": 915,
"s": 502,
"text": "Internal Representation: The internal implementation of unordered_multimap is the same as that of unordered_map but for duplicate keys, another count value is maintained with each key-value pair. As pairs are stored in the hash table, there is no particular order among them but pairs with the same keys come together in the data structure whereas pairs with the same values are not guaranteed to come together. "
},
{
"code": null,
"e": 1178,
"s": 915,
"text": "Time Complexity: All operation on unordered_multimap takes a constant amount of time on average but time can go to linear in the worst case depending on internally used hash function but in long run unordered_multimap outperforms multimap (tree-based multimap). "
},
{
"code": null,
"e": 1276,
"s": 1178,
"text": "Functions: unordered_multimap supports many functions which are demonstrated in the below code : "
},
{
"code": null,
"e": 1280,
"s": 1276,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate various function of// unordered_multimap#include <bits/stdc++.h>using namespace std; // making typedef for short declarationtypedef unordered_multimap<string, int>::iterator unit; // Utility function to print unordered_multimapvoid printUmm(unordered_multimap<string, int> umm){ // begin() returns iterator to first element of map unit it = umm.begin(); for (; it != umm.end(); it++){ cout << \"<\" << it->first << \", \" << it->second << \"> \"; cout << endl; }} // Driver codeint main(){ // empty initialization unordered_multimap<string, int> umm1; // Initialization by initializer list unordered_multimap<string, int> umm2( { { \"apple\", 1 }, { \"ball\", 2 }, { \"apple\", 10 }, { \"cat\", 7 }, { \"dog\", 9 }, { \"cat\", 6 }, { \"apple\", 1 } }); // Initialization by assignment operation umm1 = umm2; printUmm(umm1); // empty returns true, if container is empty else it // returns false if (umm2.empty()) cout << \"unordered multimap 2 is empty\\n\"; else cout << \"unordered multimap 2 is not empty\\n\"; // size returns total number of elements in container cout << \"Size of unordered multimap 1 is \" << umm1.size() << endl; string key = \"apple\"; // find and return any pair, associated with key unit it = umm1.find(key); if (it != umm1.end()) { cout << \"\\nkey \" << key << \" is there in unordered \" << \" multimap 1\\n\"; cout << \"\\none of the value associated with \" << key << \" is \" << it->second << endl; } else cout << \"\\nkey \" << key << \" is not there in unordered\" << \" multimap 1\\n\"; // count returns count of total number of pair // associated with key int cnt = umm1.count(key); cout << \"\\ntotal values associated with \" << key << \" are \" << cnt << \"\\n\\n\"; printUmm(umm2); // one insertion by making pair explicitly umm2.insert(make_pair(\"dog\", 11)); // insertion by initializer list umm2.insert({ { \"alpha\", 12 }, { \"beta\", 33 } }); cout << \"\\nAfter insertion of <alpha, 12> and <beta, \" \"33>\\n\"; printUmm(umm2); // erase deletes all pairs corresponding to key umm2.erase(\"apple\"); cout << \"\\nAfter deletion of apple\\n\"; printUmm(umm2); // clear deletes all pairs from container umm1.clear(); umm2.clear(); if (umm2.empty()) cout << \"\\nunordered multimap 2 is empty\\n\"; else cout << \"\\nunordered multimap 2 is not empty\\n\";}",
"e": 3880,
"s": 1280,
"text": null
},
{
"code": null,
"e": 4562,
"s": 3880,
"text": "<dog, 9> \n<cat, 6> \n<cat, 7> \n<ball, 2> \n<apple, 1> \n<apple, 10> \n<apple, 1> \nunordered multimap 2 is not empty\nSize of unordered multimap 1 is 7\n\nkey apple is there in unordered multimap 1\n\none of the value associated with apple is 1\n\ntotal values associated with apple are 3\n\n<dog, 9> \n<cat, 6> \n<cat, 7> \n<ball, 2> \n<apple, 1> \n<apple, 10> \n<apple, 1> \n\nAfter insertion of <alpha, 12> and <beta, 33>\n<alpha, 12> \n<dog, 11> \n<dog, 9> \n<beta, 33> \n<cat, 6> \n<cat, 7> \n<ball, 2> \n<apple, 1> \n<apple, 10> \n<apple, 1> \n\nAfter deletion of apple\n<alpha, 12> \n<dog, 11> \n<dog, 9> \n<beta, 33> \n<cat, 6> \n<cat, 7> \n<ball, 2> \n\nunordered multimap 2 is empty"
},
{
"code": null,
"e": 5150,
"s": 4562,
"text": "As we can see in the above code most of the operations work similar to unordered_map but some things to note are : We can use the initializer list for initializing and inserting many pairs at once. There is no [] operator for unordered_multimap because values corresponding to a key are not unique, there can be many values associated with a single key so [] operator can not be applied to them. Erase function deletes all instances of values associated with the supplied key. Find function returns an iterator to any instance of key-value pair among all pairs associated with that key. "
},
{
"code": null,
"e": 5481,
"s": 5150,
"text": "How to access/delete a specific value for a key? If we want to check whether a specific value is there or not, we need to loop over all pairs of key-value until we get our specific value, if we get our specific value in the unordered_multimap then use erase(position) method to delete that specific value from unordered_multimap. "
},
{
"code": null,
"e": 5485,
"s": 5481,
"text": "CPP"
},
{
"code": "// C++ program to erase particular value.#include <bits/stdc++.h>using namespace std; // Utility function to print unordered_multimapvoid printUmm(unordered_multimap<string, int>& umm){ // Iterator pointing to first element of unordered_map auto it1 = umm.begin(); for (; it1 != umm.end(); it1++) { cout << \"<\" << it1->first << \", \" << it1->second << \"> \"; cout << endl; }} int main(){ // Initialization by intializer list unordered_multimap<string, int> umm{ { \"apple\", 1 }, { \"ball\", 2 }, { \"apple\", 10 }, { \"cat\", 7 }, { \"dog\", 9 }, { \"cat\", 6 }, { \"apple\", 1 } }; // Iterator pointing to first element of unordered_map auto it = umm.begin(); // Search for an element with value 1 while (it != umm.end()) { if (it->second == 1) break; it++; } // Erase the element pointed by iterator it if (it != umm.end()) umm.erase(it); cout << \"After deletion of value 1 from umm\" << endl; printUmm(umm); return 0;}",
"e": 6539,
"s": 5485,
"text": null
},
{
"code": null,
"e": 6646,
"s": 6539,
"text": "After deletion of value 1 from umm\n<dog, 9> \n<cat, 6> \n<cat, 7> \n<ball, 2> \n<apple, 10> \n<apple, 1> "
},
{
"code": null,
"e": 6678,
"s": 6646,
"text": "Methods of unordered_multimap: "
},
{
"code": null,
"e": 6800,
"s": 6678,
"text": "begin()– Returns an iterator pointing to the first element in the container or to the first element in one of its bucket."
},
{
"code": null,
"e": 6956,
"s": 6800,
"text": "end()– Returns an iterator pointing to the position after the last element in the container or to the position after the last element in one of its bucket."
},
{
"code": null,
"e": 7068,
"s": 6956,
"text": "count()– Returns the number of elements in the container whose key is equal to the key passed in the parameter."
},
{
"code": null,
"e": 7199,
"s": 7068,
"text": "cbegin()– Returns a constant iterator pointing to the first element in the container or to the first element in one of its bucket."
},
{
"code": null,
"e": 7364,
"s": 7199,
"text": "cend()– Returns a constant iterator pointing to the position after the last element in the container or to the position after the last element in one of its bucket."
},
{
"code": null,
"e": 7431,
"s": 7364,
"text": "clear() – Clears the contents of the unordered_multimap container."
},
{
"code": null,
"e": 7536,
"s": 7431,
"text": "size()– Returns the size of the unordered_multimap. It denotes the number of elements in that container."
},
{
"code": null,
"e": 7646,
"s": 7536,
"text": "swap()– Swaps the contents of two unordered_multimap containers. The sizes can differ of both the containers."
},
{
"code": null,
"e": 7732,
"s": 7646,
"text": "find()– Returns an iterator which points to one of the elements which have the key k."
},
{
"code": null,
"e": 7795,
"s": 7732,
"text": "bucket_size()– Returns the number of elements in the bucket n."
},
{
"code": null,
"e": 7895,
"s": 7795,
"text": "empty()– It returns true if the unordered_multimap container is empty. Otherwise, it returns false."
},
{
"code": null,
"e": 7978,
"s": 7895,
"text": "equal_range()– Returns the range in which all the element’s key is equal to a key."
},
{
"code": null,
"e": 8041,
"s": 7978,
"text": "operator=– Copy/Assign/Move elements from different container."
},
{
"code": null,
"e": 8140,
"s": 8041,
"text": "max_size()– Returns the maximum number of elements that the unordered_multimap container can hold."
},
{
"code": null,
"e": 8224,
"s": 8140,
"text": "load_factor()– Returns the current load factor in the unordered_multimap container."
},
{
"code": null,
"e": 8287,
"s": 8224,
"text": "key_eq()– Returns a boolean value according to the comparison."
},
{
"code": null,
"e": 8364,
"s": 8287,
"text": "emplace()– Inserts a new {key, element} in the unordered_multimap container."
},
{
"code": null,
"e": 8445,
"s": 8364,
"text": "emplace_hint()– Inserts a new {key:element} in the unordered_multimap container."
},
{
"code": null,
"e": 8534,
"s": 8445,
"text": "bucket_count()– Returns the total number of buckets in the unordered_multimap container."
},
{
"code": null,
"e": 8595,
"s": 8534,
"text": "bucket()– Returns the bucket number in which a given key is."
},
{
"code": null,
"e": 8683,
"s": 8595,
"text": "max_load_factor()– Returns the maximum load factor of the unordered_multimap container."
},
{
"code": null,
"e": 8751,
"s": 8683,
"text": "rehash()– Sets the number of buckets in the container to N or more."
},
{
"code": null,
"e": 8893,
"s": 8751,
"text": "reserve()– Sets the number of buckets in the container (bucket_count) to the most appropriate number so that it contains at least n elements."
},
{
"code": null,
"e": 9038,
"s": 8893,
"text": "hash_function()– This hash function is a unary function that takes a single argument only and returns a unique value of type size_t based on it."
},
{
"code": null,
"e": 9144,
"s": 9038,
"text": "max_bucket_count()– Returns the maximum number of buckets that the unordered multimap container can have."
},
{
"code": null,
"e": 9353,
"s": 9144,
"text": "Recent articles on unordered_multimapThis article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 9367,
"s": 9353,
"text": "shubhamgandhi"
},
{
"code": null,
"e": 9383,
"s": 9367,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 9396,
"s": 9383,
"text": "carhantersen"
},
{
"code": null,
"e": 9414,
"s": 9396,
"text": "germanshephered48"
},
{
"code": null,
"e": 9431,
"s": 9414,
"text": "harendrakumar123"
},
{
"code": null,
"e": 9444,
"s": 9431,
"text": "simmytarika5"
},
{
"code": null,
"e": 9467,
"s": 9444,
"text": "cpp-containers-library"
},
{
"code": null,
"e": 9479,
"s": 9467,
"text": "CPP-Library"
},
{
"code": null,
"e": 9502,
"s": 9479,
"text": "cpp-unordered_multimap"
},
{
"code": null,
"e": 9506,
"s": 9502,
"text": "STL"
},
{
"code": null,
"e": 9517,
"s": 9506,
"text": "C Language"
},
{
"code": null,
"e": 9521,
"s": 9517,
"text": "C++"
},
{
"code": null,
"e": 9525,
"s": 9521,
"text": "STL"
},
{
"code": null,
"e": 9529,
"s": 9525,
"text": "CPP"
}
] |
Python NLTK | tokenize.WordPunctTokenizer()
|
30 Sep, 2019
With the help of nltk.tokenize.WordPunctTokenizer()() method, we are able to extract the tokens from string of words or sentences in the form of Alphabetic and Non-Alphabetic character by using tokenize.WordPunctTokenizer()() method.
Syntax : tokenize.WordPunctTokenizer()()Return : Return the tokens from a string of alphabetic or non-alphabetic character.
Example #1 :In this example we can see that by using tokenize.WordPunctTokenizer()() method, we are able to extract the tokens from stream of alphabetic or non-alphabetic character.
# import WordPunctTokenizer() method from nltkfrom nltk.tokenize import WordPunctTokenizer # Create a reference variable for Class WordPunctTokenizertk = WordPunctTokenizer() # Create a string inputgfg = "GeeksforGeeks...$$&* \nis\t for geeks" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek)
Output :
[‘GeeksforGeeks’, ‘...$$&*’, ‘is’, ‘for’, ‘geeks’]
Example #2 :
# import WordPunctTokenizer() method from nltkfrom nltk.tokenize import WordPunctTokenizer # Create a reference variable for Class WordPunctTokenizertk = WordPunctTokenizer() # Create a string inputgfg = "The price\t of burger \nin BurgerKing is Rs.36.\n" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek)
Output :
[‘The’, ‘price’, ‘of’, ‘burger’, ‘in’, ‘BurgerKing’, ‘is’, ‘Rs’, ‘.’, ’36’, ‘.’]
shubham_singh
Python-nltk
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Sep, 2019"
},
{
"code": null,
"e": 262,
"s": 28,
"text": "With the help of nltk.tokenize.WordPunctTokenizer()() method, we are able to extract the tokens from string of words or sentences in the form of Alphabetic and Non-Alphabetic character by using tokenize.WordPunctTokenizer()() method."
},
{
"code": null,
"e": 386,
"s": 262,
"text": "Syntax : tokenize.WordPunctTokenizer()()Return : Return the tokens from a string of alphabetic or non-alphabetic character."
},
{
"code": null,
"e": 568,
"s": 386,
"text": "Example #1 :In this example we can see that by using tokenize.WordPunctTokenizer()() method, we are able to extract the tokens from stream of alphabetic or non-alphabetic character."
},
{
"code": "# import WordPunctTokenizer() method from nltkfrom nltk.tokenize import WordPunctTokenizer # Create a reference variable for Class WordPunctTokenizertk = WordPunctTokenizer() # Create a string inputgfg = \"GeeksforGeeks...$$&* \\nis\\t for geeks\" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek)",
"e": 885,
"s": 568,
"text": null
},
{
"code": null,
"e": 894,
"s": 885,
"text": "Output :"
},
{
"code": null,
"e": 945,
"s": 894,
"text": "[‘GeeksforGeeks’, ‘...$$&*’, ‘is’, ‘for’, ‘geeks’]"
},
{
"code": null,
"e": 958,
"s": 945,
"text": "Example #2 :"
},
{
"code": "# import WordPunctTokenizer() method from nltkfrom nltk.tokenize import WordPunctTokenizer # Create a reference variable for Class WordPunctTokenizertk = WordPunctTokenizer() # Create a string inputgfg = \"The price\\t of burger \\nin BurgerKing is Rs.36.\\n\" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek)",
"e": 1287,
"s": 958,
"text": null
},
{
"code": null,
"e": 1296,
"s": 1287,
"text": "Output :"
},
{
"code": null,
"e": 1377,
"s": 1296,
"text": "[‘The’, ‘price’, ‘of’, ‘burger’, ‘in’, ‘BurgerKing’, ‘is’, ‘Rs’, ‘.’, ’36’, ‘.’]"
},
{
"code": null,
"e": 1391,
"s": 1377,
"text": "shubham_singh"
},
{
"code": null,
"e": 1403,
"s": 1391,
"text": "Python-nltk"
},
{
"code": null,
"e": 1410,
"s": 1403,
"text": "Python"
},
{
"code": null,
"e": 1508,
"s": 1410,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1540,
"s": 1508,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1567,
"s": 1540,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1598,
"s": 1567,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1621,
"s": 1598,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1642,
"s": 1621,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1698,
"s": 1642,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1740,
"s": 1698,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1782,
"s": 1740,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1821,
"s": 1782,
"text": "Python | Get unique values from a list"
}
] |
Operator grammar and precedence parser in TOC
|
15 Oct, 2020
A grammar that is used to define mathematical operators is called an operator grammar or operator precedence grammar. Such grammars have the restriction that no production has either an empty right-hand side (null productions) or two adjacent non-terminals in its right-hand side.
Examples –This is an example of operator grammar:
E->E+E/E*E/id
However, the grammar given below is not an operator grammar because two non-terminals are adjacent to each other:
S->SAS/a
A->bSb/b
We can convert it into an operator grammar, though:
S->SbSbS/SbS/a
A->bSb/b
Operator precedence parser –An operator precedence parser is a bottom-up parser that interprets an operator grammar. This parser is only used for operator grammars. Ambiguous grammars are not allowed in any parser except operator precedence parser.There are two methods for determining what precedence relations should hold between a pair of terminals:
Use the conventional associativity and precedence of operator.The second method of selecting operator-precedence relations is first to construct an unambiguous grammar for the language, a grammar that reflects the correct associativity and precedence in its parse trees.
Use the conventional associativity and precedence of operator.
The second method of selecting operator-precedence relations is first to construct an unambiguous grammar for the language, a grammar that reflects the correct associativity and precedence in its parse trees.
This parser relies on the following three precedence relations: ⋖, ≐, ⋗a ⋖ b This means a “yields precedence to” b.a ⋗ b This means a “takes precedence over” b.a ≐ b This means a “has same precedence as” b.
Figure – Operator precedence relation table for grammar E->E+E/E*E/id
There is not given any relation between id and id as id will not be compared and two variables can not come side by side. There is also a disadvantage of this table – if we have n operators then size of table will be n*n and complexity will be 0(n2). In order to decrease the size of table, we use operator function table.
Operator precedence parsers usually do not store the precedence table with the relations; rather they are implemented in a special way. Operator precedence parsers use precedence functions that map terminal symbols to integers, and the precedence relations between the symbols are implemented by numerical comparison. The parsing table can be encoded by two precedence functions f and g that map terminal symbols to integers. We select f and g such that:
f(a) < g(b) whenever a yields precedence to bf(a) = g(b) whenever a and b have the same precedencef(a) > g(b) whenever a takes precedence over b
f(a) < g(b) whenever a yields precedence to b
f(a) = g(b) whenever a and b have the same precedence
f(a) > g(b) whenever a takes precedence over b
Example – Consider the following grammar:
E -> E + E/E * E/( E )/id
This is the directed graph representing the precedence function:
Since there is no cycle in the graph, we can make this function table:
fid -> g* -> f+ ->g+ -> f$
gid -> f* -> g* ->f+ -> g+ ->f$
Size of the table is 2n.
One disadvantage of function tables is that even though we have blank entries in relation table we have non-blank entries in function table. Blank entries are also called error. Hence error detection capability of relation table is greater than function table.
#include<stdlib.h>#include<stdio.h>#include<string.h> // function f to exit from the loop// if given condition is not truevoid f(){ printf("Not operator grammar"); exit(0);} void main(){ char grm[20][20], c; // Here using flag variable, // considering grammar is not operator grammar int i, n, j = 2, flag = 0; // taking number of productions from user scanf("%d", &n); for (i = 0; i < n; i++) scanf("%s", grm[i]); for (i = 0; i < n; i++) { c = grm[i][2]; while (c != '\0') { if (grm[i][3] == '+' || grm[i][3] == '-' || grm[i][3] == '*' || grm[i][3] == '/') flag = 1; else { flag = 0; f(); } if (c == '$') { flag = 0; f(); } c = grm[i][++j]; } } if (flag == 1) printf("Operator grammar");}
Input :3
A=A*A
B=AA
A=$
Output : Not operator grammar
Input :2
A=A/A
B=A+A
Output : Operator grammar
$ is a null production here which are also not allowed in operator grammars.
Advantages –
It can easily be constructed by hand.It is simple to implement this type of parsing.
It can easily be constructed by hand.
It is simple to implement this type of parsing.
Disadvantages –
It is hard to handle tokens like the minus sign (-), which has two different precedence (depending on whether it is unary or binary).It is applicable only to a small class of grammars.
It is hard to handle tokens like the minus sign (-), which has two different precedence (depending on whether it is unary or binary).
It is applicable only to a small class of grammars.
ShubhamDamkondwar
AdityaKumar28
arihantjain17
Compiler Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Issues in the design of a code generator
Peephole Optimization in Compiler Design
Directed Acyclic graph in Compiler Design (with examples)
Type Checking in Compiler Design
Difference between Compiler and Interpreter
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n15 Oct, 2020"
},
{
"code": null,
"e": 335,
"s": 54,
"text": "A grammar that is used to define mathematical operators is called an operator grammar or operator precedence grammar. Such grammars have the restriction that no production has either an empty right-hand side (null productions) or two adjacent non-terminals in its right-hand side."
},
{
"code": null,
"e": 385,
"s": 335,
"text": "Examples –This is an example of operator grammar:"
},
{
"code": null,
"e": 400,
"s": 385,
"text": "E->E+E/E*E/id "
},
{
"code": null,
"e": 514,
"s": 400,
"text": "However, the grammar given below is not an operator grammar because two non-terminals are adjacent to each other:"
},
{
"code": null,
"e": 533,
"s": 514,
"text": "S->SAS/a\nA->bSb/b "
},
{
"code": null,
"e": 585,
"s": 533,
"text": "We can convert it into an operator grammar, though:"
},
{
"code": null,
"e": 611,
"s": 585,
"text": "S->SbSbS/SbS/a\nA->bSb/b "
},
{
"code": null,
"e": 964,
"s": 611,
"text": "Operator precedence parser –An operator precedence parser is a bottom-up parser that interprets an operator grammar. This parser is only used for operator grammars. Ambiguous grammars are not allowed in any parser except operator precedence parser.There are two methods for determining what precedence relations should hold between a pair of terminals:"
},
{
"code": null,
"e": 1235,
"s": 964,
"text": "Use the conventional associativity and precedence of operator.The second method of selecting operator-precedence relations is first to construct an unambiguous grammar for the language, a grammar that reflects the correct associativity and precedence in its parse trees."
},
{
"code": null,
"e": 1298,
"s": 1235,
"text": "Use the conventional associativity and precedence of operator."
},
{
"code": null,
"e": 1507,
"s": 1298,
"text": "The second method of selecting operator-precedence relations is first to construct an unambiguous grammar for the language, a grammar that reflects the correct associativity and precedence in its parse trees."
},
{
"code": null,
"e": 1714,
"s": 1507,
"text": "This parser relies on the following three precedence relations: ⋖, ≐, ⋗a ⋖ b This means a “yields precedence to” b.a ⋗ b This means a “takes precedence over” b.a ≐ b This means a “has same precedence as” b."
},
{
"code": null,
"e": 1784,
"s": 1714,
"text": "Figure – Operator precedence relation table for grammar E->E+E/E*E/id"
},
{
"code": null,
"e": 2107,
"s": 1784,
"text": "There is not given any relation between id and id as id will not be compared and two variables can not come side by side. There is also a disadvantage of this table – if we have n operators then size of table will be n*n and complexity will be 0(n2). In order to decrease the size of table, we use operator function table."
},
{
"code": null,
"e": 2562,
"s": 2107,
"text": "Operator precedence parsers usually do not store the precedence table with the relations; rather they are implemented in a special way. Operator precedence parsers use precedence functions that map terminal symbols to integers, and the precedence relations between the symbols are implemented by numerical comparison. The parsing table can be encoded by two precedence functions f and g that map terminal symbols to integers. We select f and g such that:"
},
{
"code": null,
"e": 2707,
"s": 2562,
"text": "f(a) < g(b) whenever a yields precedence to bf(a) = g(b) whenever a and b have the same precedencef(a) > g(b) whenever a takes precedence over b"
},
{
"code": null,
"e": 2753,
"s": 2707,
"text": "f(a) < g(b) whenever a yields precedence to b"
},
{
"code": null,
"e": 2807,
"s": 2753,
"text": "f(a) = g(b) whenever a and b have the same precedence"
},
{
"code": null,
"e": 2854,
"s": 2807,
"text": "f(a) > g(b) whenever a takes precedence over b"
},
{
"code": null,
"e": 2896,
"s": 2854,
"text": "Example – Consider the following grammar:"
},
{
"code": null,
"e": 2926,
"s": 2896,
"text": " E -> E + E/E * E/( E )/id "
},
{
"code": null,
"e": 2991,
"s": 2926,
"text": "This is the directed graph representing the precedence function:"
},
{
"code": null,
"e": 3062,
"s": 2991,
"text": "Since there is no cycle in the graph, we can make this function table:"
},
{
"code": null,
"e": 3122,
"s": 3062,
"text": "fid -> g* -> f+ ->g+ -> f$\ngid -> f* -> g* ->f+ -> g+ ->f$ "
},
{
"code": null,
"e": 3147,
"s": 3122,
"text": "Size of the table is 2n."
},
{
"code": null,
"e": 3408,
"s": 3147,
"text": "One disadvantage of function tables is that even though we have blank entries in relation table we have non-blank entries in function table. Blank entries are also called error. Hence error detection capability of relation table is greater than function table."
},
{
"code": "#include<stdlib.h>#include<stdio.h>#include<string.h> // function f to exit from the loop// if given condition is not truevoid f(){ printf(\"Not operator grammar\"); exit(0);} void main(){ char grm[20][20], c; // Here using flag variable, // considering grammar is not operator grammar int i, n, j = 2, flag = 0; // taking number of productions from user scanf(\"%d\", &n); for (i = 0; i < n; i++) scanf(\"%s\", grm[i]); for (i = 0; i < n; i++) { c = grm[i][2]; while (c != '\\0') { if (grm[i][3] == '+' || grm[i][3] == '-' || grm[i][3] == '*' || grm[i][3] == '/') flag = 1; else { flag = 0; f(); } if (c == '$') { flag = 0; f(); } c = grm[i][++j]; } } if (flag == 1) printf(\"Operator grammar\");}",
"e": 4349,
"s": 3408,
"text": null
},
{
"code": null,
"e": 4454,
"s": 4349,
"text": "Input :3\nA=A*A\nB=AA\nA=$\n\nOutput : Not operator grammar\n\nInput :2\nA=A/A\nB=A+A\n\nOutput : Operator grammar\n"
},
{
"code": null,
"e": 4531,
"s": 4454,
"text": "$ is a null production here which are also not allowed in operator grammars."
},
{
"code": null,
"e": 4544,
"s": 4531,
"text": "Advantages –"
},
{
"code": null,
"e": 4629,
"s": 4544,
"text": "It can easily be constructed by hand.It is simple to implement this type of parsing."
},
{
"code": null,
"e": 4667,
"s": 4629,
"text": "It can easily be constructed by hand."
},
{
"code": null,
"e": 4715,
"s": 4667,
"text": "It is simple to implement this type of parsing."
},
{
"code": null,
"e": 4731,
"s": 4715,
"text": "Disadvantages –"
},
{
"code": null,
"e": 4916,
"s": 4731,
"text": "It is hard to handle tokens like the minus sign (-), which has two different precedence (depending on whether it is unary or binary).It is applicable only to a small class of grammars."
},
{
"code": null,
"e": 5050,
"s": 4916,
"text": "It is hard to handle tokens like the minus sign (-), which has two different precedence (depending on whether it is unary or binary)."
},
{
"code": null,
"e": 5102,
"s": 5050,
"text": "It is applicable only to a small class of grammars."
},
{
"code": null,
"e": 5120,
"s": 5102,
"text": "ShubhamDamkondwar"
},
{
"code": null,
"e": 5134,
"s": 5120,
"text": "AdityaKumar28"
},
{
"code": null,
"e": 5148,
"s": 5134,
"text": "arihantjain17"
},
{
"code": null,
"e": 5164,
"s": 5148,
"text": "Compiler Design"
},
{
"code": null,
"e": 5172,
"s": 5164,
"text": "GATE CS"
},
{
"code": null,
"e": 5270,
"s": 5172,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5311,
"s": 5270,
"text": "Issues in the design of a code generator"
},
{
"code": null,
"e": 5352,
"s": 5311,
"text": "Peephole Optimization in Compiler Design"
},
{
"code": null,
"e": 5410,
"s": 5352,
"text": "Directed Acyclic graph in Compiler Design (with examples)"
},
{
"code": null,
"e": 5443,
"s": 5410,
"text": "Type Checking in Compiler Design"
},
{
"code": null,
"e": 5487,
"s": 5443,
"text": "Difference between Compiler and Interpreter"
},
{
"code": null,
"e": 5507,
"s": 5487,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 5531,
"s": 5507,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 5544,
"s": 5531,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 5571,
"s": 5544,
"text": "Types of Operating Systems"
}
] |
GATE | GATE-CS-2017 (Set 1) | Question 16
|
22 Jul, 2021
Consider the following CPU processes with arrival times (in milliseconds) and length of CPU bursts (in milliseconds) as given below:
If the pre-emptive shortest remaining time first scheduling algorithm is used to schedule the processes, then the average waiting time across all processes is _______ milliseconds.
Note: This questions appeared as Numerical Answer Type.(A) 1(B) 2(C) 3(D) 4Answer: (C)Explanation:
Turn Around Time
P1 = 12-0 = 12
P2 = 6-3 = 3
P3 = 17-5 = 12
P4 = 8 - 6 = 2
Waiting Time
P1 = 12-7 = 5
P2 = 3-3 = 0
P3 = 12-5 = 7
P4 = 2 - 2 = 0
Average Waiting time = (7+0+5+0)/4 = 3.0
Therefore, option C is correct
Alternate Solution
Given, with arrival time and burst time:
Using (preemptive) shortest remaining time first algorithm, gantt chart is:
Therefore,Average waiting time = ( 5 + 0 + 7 + 0 ) / 4 = 12 / 4 = 3
This explanation has been contributed by Mithlesh Upadhyay.
Watch GeeksforGeeks Video Explanation :
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=maVQoJuMAlM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Quiz of this Question
GATE-CS-2017 (Set 1)
GATE-GATE-CS-2017 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2015 (Set 2) | Question 55
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jul, 2021"
},
{
"code": null,
"e": 161,
"s": 28,
"text": "Consider the following CPU processes with arrival times (in milliseconds) and length of CPU bursts (in milliseconds) as given below:"
},
{
"code": null,
"e": 342,
"s": 161,
"text": "If the pre-emptive shortest remaining time first scheduling algorithm is used to schedule the processes, then the average waiting time across all processes is _______ milliseconds."
},
{
"code": null,
"e": 442,
"s": 342,
"text": "Note: This questions appeared as Numerical Answer Type.(A) 1(B) 2(C) 3(D) 4Answer: (C)Explanation: "
},
{
"code": null,
"e": 459,
"s": 442,
"text": "Turn Around Time"
},
{
"code": null,
"e": 519,
"s": 459,
"text": "P1 = 12-0 = 12\nP2 = 6-3 = 3\nP3 = 17-5 = 12\nP4 = 8 - 6 = 2\n"
},
{
"code": null,
"e": 532,
"s": 519,
"text": "Waiting Time"
},
{
"code": null,
"e": 590,
"s": 532,
"text": "P1 = 12-7 = 5\nP2 = 3-3 = 0\nP3 = 12-5 = 7\nP4 = 2 - 2 = 0\n"
},
{
"code": null,
"e": 631,
"s": 590,
"text": "Average Waiting time = (7+0+5+0)/4 = 3.0"
},
{
"code": null,
"e": 662,
"s": 631,
"text": "Therefore, option C is correct"
},
{
"code": null,
"e": 681,
"s": 662,
"text": "Alternate Solution"
},
{
"code": null,
"e": 722,
"s": 681,
"text": "Given, with arrival time and burst time:"
},
{
"code": null,
"e": 798,
"s": 722,
"text": "Using (preemptive) shortest remaining time first algorithm, gantt chart is:"
},
{
"code": null,
"e": 866,
"s": 798,
"text": "Therefore,Average waiting time = ( 5 + 0 + 7 + 0 ) / 4 = 12 / 4 = 3"
},
{
"code": null,
"e": 926,
"s": 866,
"text": "This explanation has been contributed by Mithlesh Upadhyay."
},
{
"code": null,
"e": 966,
"s": 926,
"text": "Watch GeeksforGeeks Video Explanation :"
},
{
"code": null,
"e": 1258,
"s": 966,
"text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=maVQoJuMAlM\" 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": 1280,
"s": 1258,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 1301,
"s": 1280,
"text": "GATE-CS-2017 (Set 1)"
},
{
"code": null,
"e": 1327,
"s": 1301,
"text": "GATE-GATE-CS-2017 (Set 1)"
},
{
"code": null,
"e": 1332,
"s": 1327,
"text": "GATE"
},
{
"code": null,
"e": 1430,
"s": 1332,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1472,
"s": 1430,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 1534,
"s": 1472,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 1576,
"s": 1534,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 20"
},
{
"code": null,
"e": 1610,
"s": 1576,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 1652,
"s": 1610,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 1694,
"s": 1652,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 1728,
"s": 1694,
"text": "GATE | GATE CS 2008 | Question 40"
},
{
"code": null,
"e": 1770,
"s": 1728,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 51"
},
{
"code": null,
"e": 1804,
"s": 1770,
"text": "GATE | GATE CS 1996 | Question 63"
}
] |
How to add time delay in Python?
|
23 Jun, 2022
In this article, we are going to discuss how to add delay in Python.
In order to add time delay in our program code, we use the sleep() function from the time module. This is the in-built module in Python we don’t need to install externally.
Time delay means we are adding delay during the execution time in our program code. It should be between two statements or between any part of the program code according to you.
Approach:
Import the time module
For adding time delay during execution we use the sleep() function between the two statements between which we want the delay. In the sleep() function passing the parameter as an integer or float value.
Run the program.
Notice the delay in the execution time.
time.sleep(value)
To understand the topic perfectly. Let’s see the implementation by taking some examples.
Note: As an output, I have shown the GIF, so that you can notice the time delay in the program code during the execution time.
Python3
# importing moduleimport time # running loop from 0 to 4for i in range(0,5): # printing numbers print(i) # adding 2 seconds time delay time.sleep(2)
Output:
Python3
# importing time moduleimport time def message(string): for i in string: # printing each character of the message print(i, end="") # adding time delay of half second time.sleep(0.5) # main functionif __name__ == '__main__': msg = "Its looks like auto typing" # calling the function for printing the # characters with delay message(msg)
Output:
Python3
# importing moduleimport time # function to print the patterndef pattern(n): for i in range(0, n): for j in range(0, i+1): print('*', end=' ') # adding two second of time delay time.sleep(0.5) print(' ') # main functionif __name__ == '__main__': # taking range from the user num = 4 print("Printing the pattern") # calling function to print the pattern pattern(num)
Output:
Python3
# importingimport timefrom threading import Thread # making first thread of Geeksclass Geeks(Thread): def run(self): for x in range(4): print("Geeks") # adding delay of 2.2 seconds time.sleep(2.2) # making second thread of Forclass For(Thread): def run(self): for x in range(3): print('For') # adding delay of 2.3 seconds time.sleep(2.3) print("Hello") # making the object for both the# threads separatelyg1 = Geeks()f1 = For() # starting the first threadg1.start() # starting the second threadf1.start() # waiting for the both thread to join# after completing their jobg1.join()f1.join() # when threads complete their jobs# message will be printedprint("All Done!!")
Output:
The threading.Event.wait procedure, the thread waits until the set() method execution is not complete. Time can be used in it; if a specific time is set, execution will halt until that time has passed; after that, it will resume while the set() of an event is still active.
What is the Syntax of threading.Event.wait function
threading.Event.wait()
Example:
Python3
from time import sleep if __name__ == '__main__': # delay in seconds delay = 2 print('Geeks') sleep(delay) print('for') sleep(delay) print('Geeks')
Output:
Geeks
for
Geeks
Actions that need to be scheduled to begin at a specific time are represented by timer objects. These items are scheduled to execute on a different thread that performs the action.
What is the Syntax of threading.Timer function
threading.Timer(interval, function)
Example:
Python3
# Program to demonstrate# timer objects in python import threading def gfg(): print("Computer Science: GeeksforGeeks\n") timer = threading.Timer(1.0, gfg)timer.start()print("Timer")
Output:
Timer
Computer Science: GeeksforGeeks
surajkumarguptaintern
Picked
Python time-module
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 122,
"s": 52,
"text": "In this article, we are going to discuss how to add delay in Python. "
},
{
"code": null,
"e": 295,
"s": 122,
"text": "In order to add time delay in our program code, we use the sleep() function from the time module. This is the in-built module in Python we don’t need to install externally."
},
{
"code": null,
"e": 473,
"s": 295,
"text": "Time delay means we are adding delay during the execution time in our program code. It should be between two statements or between any part of the program code according to you."
},
{
"code": null,
"e": 483,
"s": 473,
"text": "Approach:"
},
{
"code": null,
"e": 506,
"s": 483,
"text": "Import the time module"
},
{
"code": null,
"e": 709,
"s": 506,
"text": "For adding time delay during execution we use the sleep() function between the two statements between which we want the delay. In the sleep() function passing the parameter as an integer or float value."
},
{
"code": null,
"e": 726,
"s": 709,
"text": "Run the program."
},
{
"code": null,
"e": 766,
"s": 726,
"text": "Notice the delay in the execution time."
},
{
"code": null,
"e": 784,
"s": 766,
"text": "time.sleep(value)"
},
{
"code": null,
"e": 873,
"s": 784,
"text": "To understand the topic perfectly. Let’s see the implementation by taking some examples."
},
{
"code": null,
"e": 1000,
"s": 873,
"text": "Note: As an output, I have shown the GIF, so that you can notice the time delay in the program code during the execution time."
},
{
"code": null,
"e": 1008,
"s": 1000,
"text": "Python3"
},
{
"code": "# importing moduleimport time # running loop from 0 to 4for i in range(0,5): # printing numbers print(i) # adding 2 seconds time delay time.sleep(2)",
"e": 1168,
"s": 1008,
"text": null
},
{
"code": null,
"e": 1176,
"s": 1168,
"text": "Output:"
},
{
"code": null,
"e": 1184,
"s": 1176,
"text": "Python3"
},
{
"code": "# importing time moduleimport time def message(string): for i in string: # printing each character of the message print(i, end=\"\") # adding time delay of half second time.sleep(0.5) # main functionif __name__ == '__main__': msg = \"Its looks like auto typing\" # calling the function for printing the # characters with delay message(msg)",
"e": 1589,
"s": 1184,
"text": null
},
{
"code": null,
"e": 1597,
"s": 1589,
"text": "Output:"
},
{
"code": null,
"e": 1605,
"s": 1597,
"text": "Python3"
},
{
"code": "# importing moduleimport time # function to print the patterndef pattern(n): for i in range(0, n): for j in range(0, i+1): print('*', end=' ') # adding two second of time delay time.sleep(0.5) print(' ') # main functionif __name__ == '__main__': # taking range from the user num = 4 print(\"Printing the pattern\") # calling function to print the pattern pattern(num)",
"e": 2073,
"s": 1605,
"text": null
},
{
"code": null,
"e": 2081,
"s": 2073,
"text": "Output:"
},
{
"code": null,
"e": 2089,
"s": 2081,
"text": "Python3"
},
{
"code": "# importingimport timefrom threading import Thread # making first thread of Geeksclass Geeks(Thread): def run(self): for x in range(4): print(\"Geeks\") # adding delay of 2.2 seconds time.sleep(2.2) # making second thread of Forclass For(Thread): def run(self): for x in range(3): print('For') # adding delay of 2.3 seconds time.sleep(2.3) print(\"Hello\") # making the object for both the# threads separatelyg1 = Geeks()f1 = For() # starting the first threadg1.start() # starting the second threadf1.start() # waiting for the both thread to join# after completing their jobg1.join()f1.join() # when threads complete their jobs# message will be printedprint(\"All Done!!\")",
"e": 2877,
"s": 2089,
"text": null
},
{
"code": null,
"e": 2885,
"s": 2877,
"text": "Output:"
},
{
"code": null,
"e": 3159,
"s": 2885,
"text": "The threading.Event.wait procedure, the thread waits until the set() method execution is not complete. Time can be used in it; if a specific time is set, execution will halt until that time has passed; after that, it will resume while the set() of an event is still active."
},
{
"code": null,
"e": 3211,
"s": 3159,
"text": "What is the Syntax of threading.Event.wait function"
},
{
"code": null,
"e": 3234,
"s": 3211,
"text": "threading.Event.wait()"
},
{
"code": null,
"e": 3243,
"s": 3234,
"text": "Example:"
},
{
"code": null,
"e": 3251,
"s": 3243,
"text": "Python3"
},
{
"code": "from time import sleep if __name__ == '__main__': # delay in seconds delay = 2 print('Geeks') sleep(delay) print('for') sleep(delay) print('Geeks')",
"e": 3421,
"s": 3251,
"text": null
},
{
"code": null,
"e": 3429,
"s": 3421,
"text": "Output:"
},
{
"code": null,
"e": 3445,
"s": 3429,
"text": "Geeks\nfor\nGeeks"
},
{
"code": null,
"e": 3626,
"s": 3445,
"text": "Actions that need to be scheduled to begin at a specific time are represented by timer objects. These items are scheduled to execute on a different thread that performs the action."
},
{
"code": null,
"e": 3673,
"s": 3626,
"text": "What is the Syntax of threading.Timer function"
},
{
"code": null,
"e": 3709,
"s": 3673,
"text": "threading.Timer(interval, function)"
},
{
"code": null,
"e": 3718,
"s": 3709,
"text": "Example:"
},
{
"code": null,
"e": 3726,
"s": 3718,
"text": "Python3"
},
{
"code": "# Program to demonstrate# timer objects in python import threading def gfg(): print(\"Computer Science: GeeksforGeeks\\n\") timer = threading.Timer(1.0, gfg)timer.start()print(\"Timer\")",
"e": 3912,
"s": 3726,
"text": null
},
{
"code": null,
"e": 3920,
"s": 3912,
"text": "Output:"
},
{
"code": null,
"e": 3958,
"s": 3920,
"text": "Timer\nComputer Science: GeeksforGeeks"
},
{
"code": null,
"e": 3980,
"s": 3958,
"text": "surajkumarguptaintern"
},
{
"code": null,
"e": 3987,
"s": 3980,
"text": "Picked"
},
{
"code": null,
"e": 4006,
"s": 3987,
"text": "Python time-module"
},
{
"code": null,
"e": 4030,
"s": 4006,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 4037,
"s": 4030,
"text": "Python"
},
{
"code": null,
"e": 4056,
"s": 4037,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4154,
"s": 4056,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4186,
"s": 4154,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4213,
"s": 4186,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4234,
"s": 4213,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4257,
"s": 4234,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4313,
"s": 4257,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4344,
"s": 4313,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4386,
"s": 4344,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4428,
"s": 4386,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4467,
"s": 4428,
"text": "Python | Get unique values from a list"
}
] |
Median of sliding window in an array
|
13 Jan, 2020
Given an array of integer arr[] and an integer k, the task is to find the median of each window of size k starting from the left and moving towards the right by one position each time.
Examples:
Input: arr[] = {-1, 5, 13, 8, 2, 3, 3, 1}, k = 3Output: 5 8 8 3 3 3
Input: arr[] = {-1, 5, 13, 8, 2, 3, 3, 1}, k = 4Output: 6.5 6.5 5.5 3.0 2.5
Approach: Create a pair class to hold the items and their index. It also implements the comparable interface so that compareTo() method will be invoked by the Treeset to find the nodes. Note that the two pairs are equal only when their indices are equal. This is important since a window can contain duplicates and we may end up deleting multiple items in single remove() call if we only check for the value.
The idea is to maintain two sorted sets (minSet and maxSet) of Pair objects of length (k / 2) and (k / 2) + 1 depending on whether k is even or odd, minSet will always contain the first set of numbers (smaller) of window k and maxSet will contain the second set of numbers (larger).
As we move our window, we will remove elements from either of the sets (log n) and add a new element (log n) maintaining the minSet and maxSet rule specified above.
Below is the implementation of the above approach:
// Java implementation of the approachimport java.util.TreeSet; public class GFG { // Pair class for the value and its index static class Pair implements Comparable<Pair> { private int value, index; // Constructor public Pair(int v, int p) { value = v; index = p; } // This method will be used by the treeset to // search a value by index and setting the tree // nodes (left or right) @Override public int compareTo(Pair o) { // Two nodes are equal only when // their indices are same if (index == o.index) { return 0; } else if (value == o.value) { return Integer.compare(index, o.index); } else { return Integer.compare(value, o.value); } } // Function to return the value // of the current object public int value() { return value; } // Update the value and the position // for the same object to save space public void renew(int v, int p) { value = v; index = p; } @Override public String toString() { return String.format("(%d, %d)", value, index); } } // Function to print the median for the current window static void printMedian(TreeSet<Pair> minSet, TreeSet<Pair> maxSet, int window) { // If the window size is even then the // median will be the average of the // two middle elements if (window % 2 == 0) { System.out.print((minSet.last().value() + maxSet.first().value()) / 2.0); System.out.print(" "); } // Else it will be the middle element else { System.out.print(minSet.size() > maxSet.size() ? minSet.last().value() : maxSet.first().value()); System.out.print(" "); } } // Function to find the median // of every window of size k static void findMedian(int arr[], int k) { TreeSet<Pair> minSet = new TreeSet<>(); TreeSet<Pair> maxSet = new TreeSet<>(); // To hold the pairs, we will keep renewing // these instead of creating the new pairs Pair[] windowPairs = new Pair[k]; for (int i = 0; i < k; i++) { windowPairs[i] = new Pair(arr[i], i); } // Add k/2 items to maxSet for (int i = 0; i < k / 2; i++) { maxSet.add(windowPairs[i]); } for (int i = k / 2; i < k; i++) { // Below logic is to maintain the // maxSet and the minSet criteria if (arr[i] < maxSet.first().value()) { minSet.add(windowPairs[i]); } else { minSet.add(maxSet.pollFirst()); maxSet.add(windowPairs[i]); } } printMedian(minSet, maxSet, k); for (int i = k; i < arr.length; i++) { // Get the pair at the start of the window, this // will reset to 0 at every k, 2k, 3k, ... Pair temp = windowPairs[i % k]; if (temp.value() <= minSet.last().value()) { // Remove the starting pair of the window minSet.remove(temp); // Renew window start to new window end temp.renew(arr[i], i); // Below logic is to maintain the // maxSet and the minSet criteria if (temp.value() < maxSet.first().value()) { minSet.add(temp); } else { minSet.add(maxSet.pollFirst()); maxSet.add(temp); } } else { maxSet.remove(temp); temp.renew(arr[i], i); // Below logic is to maintain the // maxSet and the minSet criteria if (temp.value() > minSet.last().value()) { maxSet.add(temp); } else { maxSet.add(minSet.pollLast()); minSet.add(temp); } } printMedian(minSet, maxSet, k); } } // Driver code public static void main(String[] args) { int[] arr = new int[] { 0, 9, 1, 8, 2, 7, 3, 6, 4, 5 }; int k = 3; findMedian(arr, k); }}
1 8 2 7 3 6 4 5
median-finding
sliding-window
Arrays
Binary Search Tree
Dynamic Programming
Java Programs
Sorting
sliding-window
Arrays
Dynamic Programming
Sorting
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jan, 2020"
},
{
"code": null,
"e": 239,
"s": 54,
"text": "Given an array of integer arr[] and an integer k, the task is to find the median of each window of size k starting from the left and moving towards the right by one position each time."
},
{
"code": null,
"e": 249,
"s": 239,
"text": "Examples:"
},
{
"code": null,
"e": 317,
"s": 249,
"text": "Input: arr[] = {-1, 5, 13, 8, 2, 3, 3, 1}, k = 3Output: 5 8 8 3 3 3"
},
{
"code": null,
"e": 393,
"s": 317,
"text": "Input: arr[] = {-1, 5, 13, 8, 2, 3, 3, 1}, k = 4Output: 6.5 6.5 5.5 3.0 2.5"
},
{
"code": null,
"e": 802,
"s": 393,
"text": "Approach: Create a pair class to hold the items and their index. It also implements the comparable interface so that compareTo() method will be invoked by the Treeset to find the nodes. Note that the two pairs are equal only when their indices are equal. This is important since a window can contain duplicates and we may end up deleting multiple items in single remove() call if we only check for the value."
},
{
"code": null,
"e": 1085,
"s": 802,
"text": "The idea is to maintain two sorted sets (minSet and maxSet) of Pair objects of length (k / 2) and (k / 2) + 1 depending on whether k is even or odd, minSet will always contain the first set of numbers (smaller) of window k and maxSet will contain the second set of numbers (larger)."
},
{
"code": null,
"e": 1250,
"s": 1085,
"text": "As we move our window, we will remove elements from either of the sets (log n) and add a new element (log n) maintaining the minSet and maxSet rule specified above."
},
{
"code": null,
"e": 1301,
"s": 1250,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java implementation of the approachimport java.util.TreeSet; public class GFG { // Pair class for the value and its index static class Pair implements Comparable<Pair> { private int value, index; // Constructor public Pair(int v, int p) { value = v; index = p; } // This method will be used by the treeset to // search a value by index and setting the tree // nodes (left or right) @Override public int compareTo(Pair o) { // Two nodes are equal only when // their indices are same if (index == o.index) { return 0; } else if (value == o.value) { return Integer.compare(index, o.index); } else { return Integer.compare(value, o.value); } } // Function to return the value // of the current object public int value() { return value; } // Update the value and the position // for the same object to save space public void renew(int v, int p) { value = v; index = p; } @Override public String toString() { return String.format(\"(%d, %d)\", value, index); } } // Function to print the median for the current window static void printMedian(TreeSet<Pair> minSet, TreeSet<Pair> maxSet, int window) { // If the window size is even then the // median will be the average of the // two middle elements if (window % 2 == 0) { System.out.print((minSet.last().value() + maxSet.first().value()) / 2.0); System.out.print(\" \"); } // Else it will be the middle element else { System.out.print(minSet.size() > maxSet.size() ? minSet.last().value() : maxSet.first().value()); System.out.print(\" \"); } } // Function to find the median // of every window of size k static void findMedian(int arr[], int k) { TreeSet<Pair> minSet = new TreeSet<>(); TreeSet<Pair> maxSet = new TreeSet<>(); // To hold the pairs, we will keep renewing // these instead of creating the new pairs Pair[] windowPairs = new Pair[k]; for (int i = 0; i < k; i++) { windowPairs[i] = new Pair(arr[i], i); } // Add k/2 items to maxSet for (int i = 0; i < k / 2; i++) { maxSet.add(windowPairs[i]); } for (int i = k / 2; i < k; i++) { // Below logic is to maintain the // maxSet and the minSet criteria if (arr[i] < maxSet.first().value()) { minSet.add(windowPairs[i]); } else { minSet.add(maxSet.pollFirst()); maxSet.add(windowPairs[i]); } } printMedian(minSet, maxSet, k); for (int i = k; i < arr.length; i++) { // Get the pair at the start of the window, this // will reset to 0 at every k, 2k, 3k, ... Pair temp = windowPairs[i % k]; if (temp.value() <= minSet.last().value()) { // Remove the starting pair of the window minSet.remove(temp); // Renew window start to new window end temp.renew(arr[i], i); // Below logic is to maintain the // maxSet and the minSet criteria if (temp.value() < maxSet.first().value()) { minSet.add(temp); } else { minSet.add(maxSet.pollFirst()); maxSet.add(temp); } } else { maxSet.remove(temp); temp.renew(arr[i], i); // Below logic is to maintain the // maxSet and the minSet criteria if (temp.value() > minSet.last().value()) { maxSet.add(temp); } else { maxSet.add(minSet.pollLast()); minSet.add(temp); } } printMedian(minSet, maxSet, k); } } // Driver code public static void main(String[] args) { int[] arr = new int[] { 0, 9, 1, 8, 2, 7, 3, 6, 4, 5 }; int k = 3; findMedian(arr, k); }}",
"e": 5971,
"s": 1301,
"text": null
},
{
"code": null,
"e": 5988,
"s": 5971,
"text": "1 8 2 7 3 6 4 5\n"
},
{
"code": null,
"e": 6003,
"s": 5988,
"text": "median-finding"
},
{
"code": null,
"e": 6018,
"s": 6003,
"text": "sliding-window"
},
{
"code": null,
"e": 6025,
"s": 6018,
"text": "Arrays"
},
{
"code": null,
"e": 6044,
"s": 6025,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 6064,
"s": 6044,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 6078,
"s": 6064,
"text": "Java Programs"
},
{
"code": null,
"e": 6086,
"s": 6078,
"text": "Sorting"
},
{
"code": null,
"e": 6101,
"s": 6086,
"text": "sliding-window"
},
{
"code": null,
"e": 6108,
"s": 6101,
"text": "Arrays"
},
{
"code": null,
"e": 6128,
"s": 6108,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 6136,
"s": 6128,
"text": "Sorting"
},
{
"code": null,
"e": 6155,
"s": 6136,
"text": "Binary Search Tree"
}
] |
Whatsapp using Python!
|
21 Oct, 2021
Have you ever wished to automatically wish your friends on their birthdays, or send a set of messages to your friend ( or any Whatsapp contact! ) automatically at a pre-set time, or send your friends by sending thousands of random texts on WhatsApp! Using Browser Automation you can do all of it and much more!
1) Python Bindings for Selenium ( Browser Automation software )
pip install selenium
2) Chrome web driver
Download Chrome driver from here: Chromedriver download page( choose your specific version ) Extract it in a known location, as we need the location later
If you get stuck somewhere, Refer To the documentation: Documentation link
3) Chromium Web Browser( Open-source version of chrome browser )
sudo apt-get install chromium-browser
That’s it! You are all set.
Python
from selenium import webdriverfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.common.keys import Keysfrom selenium.webdriver.common.by import Byimport time # Replace below path with the absolute path# to chromedriver in your computerdriver = webdriver.Chrome('/home/saket/Downloads/chromedriver') driver.get("https://web.whatsapp.com/")wait = WebDriverWait(driver, 600) # Replace 'Friend's Name' with the name of your friend# or the name of a grouptarget = '"Friend\'s Name"' # Replace the below string with your own messagestring = "Message sent using Python!!!" x_arg = '//span[contains(@title,' + target + ')]'group_title = wait.until(EC.presence_of_element_located(( By.XPATH, x_arg)))group_title.click()inp_xpath = '//div[@class="_13NKt copyable-text selectable-text"][@data-tab="9"]'input_box = wait.until(EC.presence_of_element_located(( By.XPATH, inp_xpath)))for i in range(100): input_box.send_keys(string + Keys.ENTER) time.sleep(1)
Keep your mobile phone with you. Choose WhatsApp web from the top bar in WhatsApp(3 dots)
Then Run the script ( make sure that you have added the absolute path for the chrome driver and have replaced the target variable with your friend’s name ). Scan the QR code that appears on the screen and enjoy the power of python!
Please use this script only for educational purposes, i am not responsible if your friends ( or even Whatsapp ) block you.
Feel free to modify the code. Try to :
Text Multiple Groups at onceSend the messages from a predefined list of messages randomly orSend a completely random text.
Text Multiple Groups at once
Send the messages from a predefined list of messages randomly or
Send a completely random text.
Comment below about your experience!
When it comes to browser automation, this is just the tip of the iceberg. Will write more articles on browser automation to give you a glimpse of its power!
Related Post :
Browser Automation Using Selenium
This article is contributed by Saket Modi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ddeevviissaavviittaa
menonkartikeya
Python-projects
selenium
Python
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 366,
"s": 54,
"text": "Have you ever wished to automatically wish your friends on their birthdays, or send a set of messages to your friend ( or any Whatsapp contact! ) automatically at a pre-set time, or send your friends by sending thousands of random texts on WhatsApp! Using Browser Automation you can do all of it and much more! "
},
{
"code": null,
"e": 431,
"s": 366,
"text": "1) Python Bindings for Selenium ( Browser Automation software ) "
},
{
"code": null,
"e": 452,
"s": 431,
"text": "pip install selenium"
},
{
"code": null,
"e": 474,
"s": 452,
"text": "2) Chrome web driver "
},
{
"code": null,
"e": 629,
"s": 474,
"text": "Download Chrome driver from here: Chromedriver download page( choose your specific version ) Extract it in a known location, as we need the location later"
},
{
"code": null,
"e": 704,
"s": 629,
"text": "If you get stuck somewhere, Refer To the documentation: Documentation link"
},
{
"code": null,
"e": 770,
"s": 704,
"text": "3) Chromium Web Browser( Open-source version of chrome browser ) "
},
{
"code": null,
"e": 808,
"s": 770,
"text": "sudo apt-get install chromium-browser"
},
{
"code": null,
"e": 836,
"s": 808,
"text": "That’s it! You are all set."
},
{
"code": null,
"e": 843,
"s": 836,
"text": "Python"
},
{
"code": "from selenium import webdriverfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.common.keys import Keysfrom selenium.webdriver.common.by import Byimport time # Replace below path with the absolute path# to chromedriver in your computerdriver = webdriver.Chrome('/home/saket/Downloads/chromedriver') driver.get(\"https://web.whatsapp.com/\")wait = WebDriverWait(driver, 600) # Replace 'Friend's Name' with the name of your friend# or the name of a grouptarget = '\"Friend\\'s Name\"' # Replace the below string with your own messagestring = \"Message sent using Python!!!\" x_arg = '//span[contains(@title,' + target + ')]'group_title = wait.until(EC.presence_of_element_located(( By.XPATH, x_arg)))group_title.click()inp_xpath = '//div[@class=\"_13NKt copyable-text selectable-text\"][@data-tab=\"9\"]'input_box = wait.until(EC.presence_of_element_located(( By.XPATH, inp_xpath)))for i in range(100): input_box.send_keys(string + Keys.ENTER) time.sleep(1)",
"e": 1893,
"s": 843,
"text": null
},
{
"code": null,
"e": 1984,
"s": 1893,
"text": "Keep your mobile phone with you. Choose WhatsApp web from the top bar in WhatsApp(3 dots) "
},
{
"code": null,
"e": 2216,
"s": 1984,
"text": "Then Run the script ( make sure that you have added the absolute path for the chrome driver and have replaced the target variable with your friend’s name ). Scan the QR code that appears on the screen and enjoy the power of python!"
},
{
"code": null,
"e": 2339,
"s": 2216,
"text": "Please use this script only for educational purposes, i am not responsible if your friends ( or even Whatsapp ) block you."
},
{
"code": null,
"e": 2379,
"s": 2339,
"text": "Feel free to modify the code. Try to : "
},
{
"code": null,
"e": 2502,
"s": 2379,
"text": "Text Multiple Groups at onceSend the messages from a predefined list of messages randomly orSend a completely random text."
},
{
"code": null,
"e": 2531,
"s": 2502,
"text": "Text Multiple Groups at once"
},
{
"code": null,
"e": 2596,
"s": 2531,
"text": "Send the messages from a predefined list of messages randomly or"
},
{
"code": null,
"e": 2627,
"s": 2596,
"text": "Send a completely random text."
},
{
"code": null,
"e": 2664,
"s": 2627,
"text": "Comment below about your experience!"
},
{
"code": null,
"e": 2821,
"s": 2664,
"text": "When it comes to browser automation, this is just the tip of the iceberg. Will write more articles on browser automation to give you a glimpse of its power!"
},
{
"code": null,
"e": 2837,
"s": 2821,
"text": "Related Post : "
},
{
"code": null,
"e": 2871,
"s": 2837,
"text": "Browser Automation Using Selenium"
},
{
"code": null,
"e": 3165,
"s": 2871,
"text": "This article is contributed by Saket Modi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 3290,
"s": 3165,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3311,
"s": 3290,
"text": "ddeevviissaavviittaa"
},
{
"code": null,
"e": 3326,
"s": 3311,
"text": "menonkartikeya"
},
{
"code": null,
"e": 3342,
"s": 3326,
"text": "Python-projects"
},
{
"code": null,
"e": 3351,
"s": 3342,
"text": "selenium"
},
{
"code": null,
"e": 3358,
"s": 3351,
"text": "Python"
},
{
"code": null,
"e": 3367,
"s": 3358,
"text": "TechTips"
}
] |
Program for focal length of a lens
|
12 Apr, 2021
Write a program to determine the focal length of a lens.Focal length is the distance between the center of the lens to the principal foci. In order to determine the focal length of a lens we should know the distance between the lens and the image ( I ) and the distance between the lens and the object ( O ). Here, we will use the lens equation also called the focal length equation.The lens equation is :
= +
here, F is the focal length I is the distance between the lens and the image O is the distance between the lens and the objectExamples :
Input : O = 50, I = 2
Output : F = 1.92308
Input : O = 25, I = 5
Output : F = 4.16667
C++
Java
Python3
C#
PHP
Javascript
// C++ program to determine// the focal length of a lens#include <iostream>using namespace std; // Function to determine the focal length of a lensfloat focal_length(float image_distance, float object_distance){ return 1 / ((1 / image_distance) + (1 / object_distance));} // Driver functionint main(){ // variable to store the distance // between the lens and the image float image_distance = 2; // variable to store the distance // between the lens and the object float object_distance = 50; cout << "Focal length of a lens is " << focal_length(image_distance, object_distance) << " units ."; return 0;}
// Java program to determine// the focal length of a lens import java.io.*; class GFG { // Function to determine the focal // length of a lens static float focal_length(float image_distance, float object_distance) { return 1 / ((1 / image_distance) + (1 / object_distance)); } public static void main(String[] args) { // variable to store the distance // between the lens and the image float image_distance = 2; // variable to store the distance // between the lens and the object float object_distance = 50; System.out.println("Focal length of a lens is " + focal_length(image_distance, object_distance) + " units."); }} // This code is contributed by Ajit.
# Python3 program to determine# the focal length of a lens # Function to determine the focal length of a lensdef focal_length(image_distance, object_distance) : return 1 / ((1 / image_distance) + (1 / object_distance)) # Driver Code# Variable to store the distance# between the lens and the imageimage_distance = 2 # Variable to store the distance# between the lens and the objectobject_distance = 50 result = focal_length(image_distance, object_distance)print("Focal length of a lens is ", result, " units.")
// C# program to determine// the focal length of a lensusing System; class GFG { // Function to determine the focal // length of a lens static float focal_length(float image_distance, float object_distance) { return 1 / ((1 / image_distance) + (1 / object_distance)); } // Driver code public static void Main() { // variable to store the distance // between the lens and the image float image_distance = 2; // variable to store the distance // between the lens and the object float object_distance = 50; Console.WriteLine("Focal length of a lens is " + focal_length(image_distance, object_distance) + " units."); }} // This code is contributed by Vt_m.
<?php// PHP program to determine// the focal length of a lens// Function to determine the// focal length of a lensfunction focal_length($image_distance, $object_distance){ return 1 / ((1 / $image_distance) + (1 / $object_distance));} // Driver Code // variable to store the distance // between the lens and the image $image_distance = 2; // variable to store the distance // between the lens and the object $object_distance = 50; echo "Focal length of a lens is " , focal_length($image_distance, $object_distance) , " units ."; // This code is contributed by anuj_67.?>
<script> // javascript program to determine// the focal length of a lens // Function to determine the focal // length of a lens function focal_length(image_distance, object_distance) { return 1 / ((1 / image_distance) + (1 / object_distance)); } // Driver Function // variable to store the distance // between the lens and the image let image_distance = 2; // variable to store the distance // between the lens and the object let object_distance = 50; document.write("Focal length of a lens is " + focal_length(image_distance, object_distance) + " units."); </script>
Output :
Focal length of a lens is 1.92308 units .
vt_m
souravghosh0416
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Apr, 2021"
},
{
"code": null,
"e": 436,
"s": 28,
"text": "Write a program to determine the focal length of a lens.Focal length is the distance between the center of the lens to the principal foci. In order to determine the focal length of a lens we should know the distance between the lens and the image ( I ) and the distance between the lens and the object ( O ). Here, we will use the lens equation also called the focal length equation.The lens equation is : "
},
{
"code": null,
"e": 443,
"s": 436,
"text": " = + "
},
{
"code": null,
"e": 582,
"s": 443,
"text": "here, F is the focal length I is the distance between the lens and the image O is the distance between the lens and the objectExamples : "
},
{
"code": null,
"e": 669,
"s": 582,
"text": "Input : O = 50, I = 2\nOutput : F = 1.92308\n\nInput : O = 25, I = 5\nOutput : F = 4.16667"
},
{
"code": null,
"e": 677,
"s": 673,
"text": "C++"
},
{
"code": null,
"e": 682,
"s": 677,
"text": "Java"
},
{
"code": null,
"e": 690,
"s": 682,
"text": "Python3"
},
{
"code": null,
"e": 693,
"s": 690,
"text": "C#"
},
{
"code": null,
"e": 697,
"s": 693,
"text": "PHP"
},
{
"code": null,
"e": 708,
"s": 697,
"text": "Javascript"
},
{
"code": "// C++ program to determine// the focal length of a lens#include <iostream>using namespace std; // Function to determine the focal length of a lensfloat focal_length(float image_distance, float object_distance){ return 1 / ((1 / image_distance) + (1 / object_distance));} // Driver functionint main(){ // variable to store the distance // between the lens and the image float image_distance = 2; // variable to store the distance // between the lens and the object float object_distance = 50; cout << \"Focal length of a lens is \" << focal_length(image_distance, object_distance) << \" units .\"; return 0;}",
"e": 1359,
"s": 708,
"text": null
},
{
"code": "// Java program to determine// the focal length of a lens import java.io.*; class GFG { // Function to determine the focal // length of a lens static float focal_length(float image_distance, float object_distance) { return 1 / ((1 / image_distance) + (1 / object_distance)); } public static void main(String[] args) { // variable to store the distance // between the lens and the image float image_distance = 2; // variable to store the distance // between the lens and the object float object_distance = 50; System.out.println(\"Focal length of a lens is \" + focal_length(image_distance, object_distance) + \" units.\"); }} // This code is contributed by Ajit.",
"e": 2213,
"s": 1359,
"text": null
},
{
"code": "# Python3 program to determine# the focal length of a lens # Function to determine the focal length of a lensdef focal_length(image_distance, object_distance) : return 1 / ((1 / image_distance) + (1 / object_distance)) # Driver Code# Variable to store the distance# between the lens and the imageimage_distance = 2 # Variable to store the distance# between the lens and the objectobject_distance = 50 result = focal_length(image_distance, object_distance)print(\"Focal length of a lens is \", result, \" units.\")",
"e": 2726,
"s": 2213,
"text": null
},
{
"code": "// C# program to determine// the focal length of a lensusing System; class GFG { // Function to determine the focal // length of a lens static float focal_length(float image_distance, float object_distance) { return 1 / ((1 / image_distance) + (1 / object_distance)); } // Driver code public static void Main() { // variable to store the distance // between the lens and the image float image_distance = 2; // variable to store the distance // between the lens and the object float object_distance = 50; Console.WriteLine(\"Focal length of a lens is \" + focal_length(image_distance, object_distance) + \" units.\"); }} // This code is contributed by Vt_m.",
"e": 3571,
"s": 2726,
"text": null
},
{
"code": "<?php// PHP program to determine// the focal length of a lens// Function to determine the// focal length of a lensfunction focal_length($image_distance, $object_distance){ return 1 / ((1 / $image_distance) + (1 / $object_distance));} // Driver Code // variable to store the distance // between the lens and the image $image_distance = 2; // variable to store the distance // between the lens and the object $object_distance = 50; echo \"Focal length of a lens is \" , focal_length($image_distance, $object_distance) , \" units .\"; // This code is contributed by anuj_67.?>",
"e": 4246,
"s": 3571,
"text": null
},
{
"code": "<script> // javascript program to determine// the focal length of a lens // Function to determine the focal // length of a lens function focal_length(image_distance, object_distance) { return 1 / ((1 / image_distance) + (1 / object_distance)); } // Driver Function // variable to store the distance // between the lens and the image let image_distance = 2; // variable to store the distance // between the lens and the object let object_distance = 50; document.write(\"Focal length of a lens is \" + focal_length(image_distance, object_distance) + \" units.\"); </script>",
"e": 5014,
"s": 4246,
"text": null
},
{
"code": null,
"e": 5024,
"s": 5014,
"text": "Output : "
},
{
"code": null,
"e": 5067,
"s": 5024,
"text": "Focal length of a lens is 1.92308 units . "
},
{
"code": null,
"e": 5074,
"s": 5069,
"text": "vt_m"
},
{
"code": null,
"e": 5090,
"s": 5074,
"text": "souravghosh0416"
},
{
"code": null,
"e": 5103,
"s": 5090,
"text": "Mathematical"
},
{
"code": null,
"e": 5122,
"s": 5103,
"text": "School Programming"
},
{
"code": null,
"e": 5135,
"s": 5122,
"text": "Mathematical"
}
] |
Python – Get list of running processes
|
29 Dec, 2020
A Process is a program that is being executed (processed). A process may not have to be one run explicitly by the user, it could be a system process spawned by the operating system. Any applications that execute on an operating system firstly creates a process of its own in order to execute. In a typical OS installation, most processes are os services and background applications, that are run to maintain the operating system, software and hardware. In this article, we will take a look at different ways of obtaining the list of running processes of a Windows OS, through Python. Firstly, we would describe a python method in order to achieve the result and then would look at a command found in the Windows Command Processor for the same. Method 1:We would be using the wmi library for getting the list of running processes on Windows OS. In order the install the module, execute the following command in the command interpreter of your operating system:-
pip install wmi
COde:
Python3
import wmi # Initializing the wmi constructorf = wmi.WMI() # Printing the header for the later columnsprint("pid Process name") # Iterating through all the running processesfor process in f.Win32_Process(): # Displaying the P_ID and P_Name of the process print(f"{process.ProcessId:<10} {process.Name}")
Output:
3196 RuntimeBroker.exe
3524 ShellExperienceHost.exe
3548 SearchIndexer.exe
3796 SearchUI.exe
4136 IDMan.exe
4368 IEMonitor.exe
4488 notepad.exe
2616 SettingSyncHost.exe
4212 dasHost.exe
4664 AdaptiveSleepService.exe
4716 svchost.exe
5412 chrome.exe
1376 chrome.exe
1280 cmd.exe
4928 conhost.exe
5596 py.exe
5060 python.exe
1508 WmiPrvSE.exe
Explanation:Firstly, we initialize the WMI() function of wmi library. This allows us to use the functions found inside it such as WMI.Win32_Service, WMI.Win32_Process, WMI.Win32_Printjob which are designed to perform different tasks. We would be using the WMI.Win32_Process function in order to get the list of running processes on the system. Then we called the function WMI.Win32_Process() to get the running processes, iterated through each process and stored in variable process. Then we obtained the ProcessID (pid) and ProcessName (name) of the process using the associated attributes. We used F-strings for the output in order to add padding to the output to align it properly. Method 2:In this method, we would be using a command found inside the Windows Command Processor (cmd.exe) under the name WMIC ( Windows Management Instrumentation Command line) in order to get the desired result. WMIC is a commandline utility that allows users to performs Windows Management Instrumentation (WMI) operations with a command prompt. For the purpose of getting running processes, we would be executing the command:
wmic process get description, processid
Code:
Python3
import os # Running the aforementioned command and saving its outputoutput = os.popen('wmic process get description, processid').read() # Displaying the outputprint(output)
Output:
Description ProcessId
System Idle Process 0
System 4
smss.exe 340
csrss.exe 460
wininit.exe 604
csrss.exe 624
winlogon.exe 692
services.exe 736
lsass.exe 756
svchost.exe 844
svchost.exe 904
dwm.exe 1012
svchost.exe 80
svchost.exe 420
atiesrxx.exe 1076
svchost.exe 1992
svchost.exe 2032
MsMpEng.exe 2052
NisSrv.exe 2852
sihost.exe 3032
taskhostw.exe 2148
GoogleCrashHandler.exe 2712
GoogleCrashHandler64.exe 2704
explorer.exe 2892
RuntimeBroker.exe 3196
ShellExperienceHost.exe 3524
SearchIndexer.exe 3548
chrome.exe 1340
chrome.exe 2216
Note: It is not mandatory to use the os library for the purpose. The user could pick any other alternatives (Subprocess, shutil etc) which allows for commandline command execution.Explanation: We used the function popen() found inside the os module, in order to execute the command in the command processor. Then we passed the output of the above command to read() in order to get data in readable form out of os._wrap_close object. In the end, we displayed the output.
Method 3:
We will use the subprocess module to interact with cmd and to retrieve information into your python ide. we can read the cmd command through the subprocess module.
Let’s see this logic, if we run this wmic process list brief code into our terminal then we got like this:
Approach:
import module
Get the output for the command “wmic process list brief ” using subprocess.check_output()
Now get the Split the string and arrange your data with your own needs.
Code:
Python3
# import moduleimport subprocess # traverse the software listData = subprocess.check_output(['wmic', 'process', 'list', 'brief'])a = str(Data)# try block# arrange the stringtry: for i in range(len(a)): print(a.split("\\r\\r\\n")[i])except IndexError as e: print("All Done")
Output:
b'HandleCount Name Priority ProcessId ThreadCount WorkingSetSize
0 System Idle Process 0 0 8 8192
5649 System 8 4 222 1835008
0 Registry 8 120 4 33910784
89 smss.exe 11 516 2 532480
815 csrss.exe 13 652 13 2019328
217 wininit.exe 13 740 1 3239936
781 services.exe 9 812 8 8294400
1843 lsass.exe 9 832 7 14864384
86 svchost.exe 8 1020 1 1351680
32 fontdrvhost.exe 8 308 5 196608
1526 svchost.exe 8 8 12 38608896
270 WUDFHost.exe 8 592 5 2097152
1479 svchost.exe 8 1056 11 16363520
541 svchost.exe 8 1104 15 4509696
279 svchost.exe 8 1260 3 2584576
146 svchost.exe 8 1284 1 6389760
214 svchost.exe 8 1300 3 3452928
327 svchost.exe 8 1308 6 5795840
345 svchost.exe 8 1332 13 10571776
395 svchost.exe 8 1452 7 5079040
261 svchost.exe 8 1460 5 5914624
161 svchost.exe 8 1472 2 4902912
390 svchost.exe 8 1580 11 9826304
348 WUDFHost.exe 13 1652 12 11526144
225 svchost.exe 8 1736 2 10473472
205 svchost.exe 8 1744 1 2093056
278 svchost.exe 8 1752 2 4444160
174 svchost.exe 8 1824 4 4063232
224 svchost.exe 8 1832 6 3821568
593 svchost.exe 8 2024 5 7610368
186 svchost.exe 8 1424 2 5058560
168 igfxCUIService.exe 8 2120 2 3579904
435 svchost.exe 8 2188 6 12341248
279 svchost.exe 8 2220 10 5017600
227 svchost.exe 8 2296 3 7024640
221 svchost.exe 8 2308 3 1908736
384 svchost.exe 8 2396 7 8499200
0 Memory Compression 8 2424 54 298409984
240 svchost.exe 8 2440 2 4845568
179 svchost.exe 8 2476 5 3567616
239 svchost.exe 8 2660 8 5775360
3352 svchost.exe 8 2684 9 6230016
225 svchost.exe 8 2816 2 4804608
487 svchost.exe 8 2872 7 9641984
473 svchost.exe 8 2912 4 13836288
142 svchost.exe 8 3032 4 2727936
633 svchost.exe 8 3048 3 16154624
555 svchost.exe 8 2072 14 12455936
267 svchost.exe 8 2936 4 7462912
465 spoolsv.exe 8 3168 7 4685824
420 svchost.exe 8 3200 10 8019968
187 svchost.exe 8 3324 6 2433024
174 svchost.exe 8 3572 2 2650112
416 svchost.exe 8 3584 5 13344768
540 svchost.exe 8 3592 10 24936448
161 IntelCpHDCPSvc.exe 8 3604 3 2052096
406 svchost.exe 8 3612 19 25100288
kumar_satyam
Python os-module-programs
python-os-module
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 991,
"s": 28,
"text": "A Process is a program that is being executed (processed). A process may not have to be one run explicitly by the user, it could be a system process spawned by the operating system. Any applications that execute on an operating system firstly creates a process of its own in order to execute. In a typical OS installation, most processes are os services and background applications, that are run to maintain the operating system, software and hardware. In this article, we will take a look at different ways of obtaining the list of running processes of a Windows OS, through Python. Firstly, we would describe a python method in order to achieve the result and then would look at a command found in the Windows Command Processor for the same. Method 1:We would be using the wmi library for getting the list of running processes on Windows OS. In order the install the module, execute the following command in the command interpreter of your operating system:- "
},
{
"code": null,
"e": 1010,
"s": 991,
"text": "pip install wmi\n\n\n"
},
{
"code": null,
"e": 1017,
"s": 1010,
"text": "COde: "
},
{
"code": null,
"e": 1025,
"s": 1017,
"text": "Python3"
},
{
"code": "import wmi # Initializing the wmi constructorf = wmi.WMI() # Printing the header for the later columnsprint(\"pid Process name\") # Iterating through all the running processesfor process in f.Win32_Process(): # Displaying the P_ID and P_Name of the process print(f\"{process.ProcessId:<10} {process.Name}\")",
"e": 1342,
"s": 1025,
"text": null
},
{
"code": null,
"e": 1352,
"s": 1342,
"text": "Output: "
},
{
"code": null,
"e": 1803,
"s": 1352,
"text": "3196 RuntimeBroker.exe\n3524 ShellExperienceHost.exe\n3548 SearchIndexer.exe\n3796 SearchUI.exe\n4136 IDMan.exe\n4368 IEMonitor.exe\n4488 notepad.exe\n2616 SettingSyncHost.exe\n4212 dasHost.exe\n4664 AdaptiveSleepService.exe\n4716 svchost.exe\n5412 chrome.exe\n1376 chrome.exe\n1280 cmd.exe\n4928 conhost.exe\n5596 py.exe\n5060 python.exe\n1508 WmiPrvSE.exe\n\n"
},
{
"code": null,
"e": 2920,
"s": 1803,
"text": "Explanation:Firstly, we initialize the WMI() function of wmi library. This allows us to use the functions found inside it such as WMI.Win32_Service, WMI.Win32_Process, WMI.Win32_Printjob which are designed to perform different tasks. We would be using the WMI.Win32_Process function in order to get the list of running processes on the system. Then we called the function WMI.Win32_Process() to get the running processes, iterated through each process and stored in variable process. Then we obtained the ProcessID (pid) and ProcessName (name) of the process using the associated attributes. We used F-strings for the output in order to add padding to the output to align it properly. Method 2:In this method, we would be using a command found inside the Windows Command Processor (cmd.exe) under the name WMIC ( Windows Management Instrumentation Command line) in order to get the desired result. WMIC is a commandline utility that allows users to performs Windows Management Instrumentation (WMI) operations with a command prompt. For the purpose of getting running processes, we would be executing the command: "
},
{
"code": null,
"e": 2964,
"s": 2920,
"text": "wmic process get description, processid \n\n\n"
},
{
"code": null,
"e": 2971,
"s": 2964,
"text": "Code: "
},
{
"code": null,
"e": 2979,
"s": 2971,
"text": "Python3"
},
{
"code": "import os # Running the aforementioned command and saving its outputoutput = os.popen('wmic process get description, processid').read() # Displaying the outputprint(output)",
"e": 3152,
"s": 2979,
"text": null
},
{
"code": null,
"e": 3162,
"s": 3152,
"text": "Output: "
},
{
"code": null,
"e": 4083,
"s": 3162,
"text": "Description ProcessId\n\nSystem Idle Process 0\nSystem 4\nsmss.exe 340\ncsrss.exe 460\nwininit.exe 604\ncsrss.exe 624\nwinlogon.exe 692\nservices.exe 736\nlsass.exe 756\nsvchost.exe 844\nsvchost.exe 904\ndwm.exe 1012\nsvchost.exe 80\nsvchost.exe 420\natiesrxx.exe 1076\nsvchost.exe 1992\nsvchost.exe 2032\nMsMpEng.exe 2052\nNisSrv.exe 2852\nsihost.exe 3032\ntaskhostw.exe 2148\nGoogleCrashHandler.exe 2712\nGoogleCrashHandler64.exe 2704\nexplorer.exe 2892\nRuntimeBroker.exe 3196\nShellExperienceHost.exe 3524\nSearchIndexer.exe 3548\nchrome.exe 1340\nchrome.exe 2216\n\n\n"
},
{
"code": null,
"e": 4553,
"s": 4083,
"text": "Note: It is not mandatory to use the os library for the purpose. The user could pick any other alternatives (Subprocess, shutil etc) which allows for commandline command execution.Explanation: We used the function popen() found inside the os module, in order to execute the command in the command processor. Then we passed the output of the above command to read() in order to get data in readable form out of os._wrap_close object. In the end, we displayed the output."
},
{
"code": null,
"e": 4563,
"s": 4553,
"text": "Method 3:"
},
{
"code": null,
"e": 4727,
"s": 4563,
"text": "We will use the subprocess module to interact with cmd and to retrieve information into your python ide. we can read the cmd command through the subprocess module."
},
{
"code": null,
"e": 4834,
"s": 4727,
"text": "Let’s see this logic, if we run this wmic process list brief code into our terminal then we got like this:"
},
{
"code": null,
"e": 4844,
"s": 4834,
"text": "Approach:"
},
{
"code": null,
"e": 4858,
"s": 4844,
"text": "import module"
},
{
"code": null,
"e": 4948,
"s": 4858,
"text": "Get the output for the command “wmic process list brief ” using subprocess.check_output()"
},
{
"code": null,
"e": 5020,
"s": 4948,
"text": "Now get the Split the string and arrange your data with your own needs."
},
{
"code": null,
"e": 5026,
"s": 5020,
"text": "Code:"
},
{
"code": null,
"e": 5034,
"s": 5026,
"text": "Python3"
},
{
"code": "# import moduleimport subprocess # traverse the software listData = subprocess.check_output(['wmic', 'process', 'list', 'brief'])a = str(Data)# try block# arrange the stringtry: for i in range(len(a)): print(a.split(\"\\\\r\\\\r\\\\n\")[i])except IndexError as e: print(\"All Done\")",
"e": 5322,
"s": 5034,
"text": null
},
{
"code": null,
"e": 5330,
"s": 5322,
"text": "Output:"
},
{
"code": null,
"e": 12983,
"s": 5330,
"text": "b'HandleCount Name Priority ProcessId ThreadCount WorkingSetSize \n0 System Idle Process 0 0 8 8192 \n5649 System 8 4 222 1835008 \n0 Registry 8 120 4 33910784 \n89 smss.exe 11 516 2 532480 \n815 csrss.exe 13 652 13 2019328 \n217 wininit.exe 13 740 1 3239936 \n781 services.exe 9 812 8 8294400 \n1843 lsass.exe 9 832 7 14864384 \n86 svchost.exe 8 1020 1 1351680 \n32 fontdrvhost.exe 8 308 5 196608 \n1526 svchost.exe 8 8 12 38608896 \n270 WUDFHost.exe 8 592 5 2097152 \n1479 svchost.exe 8 1056 11 16363520 \n541 svchost.exe 8 1104 15 4509696 \n279 svchost.exe 8 1260 3 2584576 \n146 svchost.exe 8 1284 1 6389760 \n214 svchost.exe 8 1300 3 3452928 \n327 svchost.exe 8 1308 6 5795840 \n345 svchost.exe 8 1332 13 10571776 \n395 svchost.exe 8 1452 7 5079040 \n261 svchost.exe 8 1460 5 5914624 \n161 svchost.exe 8 1472 2 4902912 \n390 svchost.exe 8 1580 11 9826304 \n348 WUDFHost.exe 13 1652 12 11526144 \n225 svchost.exe 8 1736 2 10473472 \n205 svchost.exe 8 1744 1 2093056 \n278 svchost.exe 8 1752 2 4444160 \n174 svchost.exe 8 1824 4 4063232 \n224 svchost.exe 8 1832 6 3821568 \n593 svchost.exe 8 2024 5 7610368 \n186 svchost.exe 8 1424 2 5058560 \n168 igfxCUIService.exe 8 2120 2 3579904 \n435 svchost.exe 8 2188 6 12341248 \n279 svchost.exe 8 2220 10 5017600 \n227 svchost.exe 8 2296 3 7024640 \n221 svchost.exe 8 2308 3 1908736 \n384 svchost.exe 8 2396 7 8499200 \n0 Memory Compression 8 2424 54 298409984 \n240 svchost.exe 8 2440 2 4845568 \n179 svchost.exe 8 2476 5 3567616 \n239 svchost.exe 8 2660 8 5775360 \n3352 svchost.exe 8 2684 9 6230016 \n225 svchost.exe 8 2816 2 4804608 \n487 svchost.exe 8 2872 7 9641984 \n473 svchost.exe 8 2912 4 13836288 \n142 svchost.exe 8 3032 4 2727936 \n633 svchost.exe 8 3048 3 16154624 \n555 svchost.exe 8 2072 14 12455936 \n267 svchost.exe 8 2936 4 7462912 \n465 spoolsv.exe 8 3168 7 4685824 \n420 svchost.exe 8 3200 10 8019968 \n187 svchost.exe 8 3324 6 2433024 \n174 svchost.exe 8 3572 2 2650112 \n416 svchost.exe 8 3584 5 13344768 \n540 svchost.exe 8 3592 10 24936448 \n161 IntelCpHDCPSvc.exe 8 3604 3 2052096 \n406 svchost.exe 8 3612 19 25100288 \n"
},
{
"code": null,
"e": 12998,
"s": 12985,
"text": "kumar_satyam"
},
{
"code": null,
"e": 13024,
"s": 12998,
"text": "Python os-module-programs"
},
{
"code": null,
"e": 13041,
"s": 13024,
"text": "python-os-module"
},
{
"code": null,
"e": 13056,
"s": 13041,
"text": "python-utility"
},
{
"code": null,
"e": 13063,
"s": 13056,
"text": "Python"
}
] |
Normal Probability Plot in R using ggplot2
|
14 Jan, 2022
A normal probability plot is a graphical representation of the data. A normal probability plot is used to check if the given data set is normally distributed or not. It is used to compare a data set with the normal distribution. If a given data set is normally distributed then it will reside in a shape like a straight line.
In this article, we are going to use ggplot2 with qqplotr to plot and check if the dataset is normally distributed using qqplot only.
Install the following necessary libraries by pasting them in r console
install.packages(“ggplot2”)
install.packages(“qqplotr”)
Create a random data set with a different mean and standard deviation that you want to plot.
Plotting data using stat_qq_point() method.
Plotting data points with line using stat_qq_line() function.
Given below is a proper implementation using the above approach
Example 1: Plotting data using stat_qq_point() method.
R
# importing librarieslibrary(ggplot2)library(qqplotr) # creating random datarandom_values = rnorm(500, mean = 90, sd = 50) # plotting data without line and labelsggplot(mapping = aes(sample = random_values)) + stat_qq_point(size = 2)
Output:
Fig. 1 Plotting Data points.
Example 2: Plotting data points with line using stat_qq_line() function.
R
# importing librarieslibrary(ggplot2)library(qqplotr) # creating random datarandom_values = rnorm(500, mean = 90, sd = 50) # plotting data with proper labels# And adding line with proper propertiesggplot(mapping = aes(sample = random_values))+ stat_qq_point(size = 2,color = "red")+ stat_qq_line(color="green")+ xlab("x-axis") + ylab("y-axis")
Output:
Fig. 2 Adding normal line
adnanirshad158
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": "\n14 Jan, 2022"
},
{
"code": null,
"e": 354,
"s": 28,
"text": "A normal probability plot is a graphical representation of the data. A normal probability plot is used to check if the given data set is normally distributed or not. It is used to compare a data set with the normal distribution. If a given data set is normally distributed then it will reside in a shape like a straight line."
},
{
"code": null,
"e": 488,
"s": 354,
"text": "In this article, we are going to use ggplot2 with qqplotr to plot and check if the dataset is normally distributed using qqplot only."
},
{
"code": null,
"e": 559,
"s": 488,
"text": "Install the following necessary libraries by pasting them in r console"
},
{
"code": null,
"e": 587,
"s": 559,
"text": "install.packages(“ggplot2”)"
},
{
"code": null,
"e": 615,
"s": 587,
"text": "install.packages(“qqplotr”)"
},
{
"code": null,
"e": 708,
"s": 615,
"text": "Create a random data set with a different mean and standard deviation that you want to plot."
},
{
"code": null,
"e": 752,
"s": 708,
"text": "Plotting data using stat_qq_point() method."
},
{
"code": null,
"e": 814,
"s": 752,
"text": "Plotting data points with line using stat_qq_line() function."
},
{
"code": null,
"e": 879,
"s": 814,
"text": "Given below is a proper implementation using the above approach "
},
{
"code": null,
"e": 934,
"s": 879,
"text": "Example 1: Plotting data using stat_qq_point() method."
},
{
"code": null,
"e": 936,
"s": 934,
"text": "R"
},
{
"code": "# importing librarieslibrary(ggplot2)library(qqplotr) # creating random datarandom_values = rnorm(500, mean = 90, sd = 50) # plotting data without line and labelsggplot(mapping = aes(sample = random_values)) + stat_qq_point(size = 2)",
"e": 1170,
"s": 936,
"text": null
},
{
"code": null,
"e": 1178,
"s": 1170,
"text": "Output:"
},
{
"code": null,
"e": 1207,
"s": 1178,
"text": "Fig. 1 Plotting Data points."
},
{
"code": null,
"e": 1280,
"s": 1207,
"text": "Example 2: Plotting data points with line using stat_qq_line() function."
},
{
"code": null,
"e": 1282,
"s": 1280,
"text": "R"
},
{
"code": "# importing librarieslibrary(ggplot2)library(qqplotr) # creating random datarandom_values = rnorm(500, mean = 90, sd = 50) # plotting data with proper labels# And adding line with proper propertiesggplot(mapping = aes(sample = random_values))+ stat_qq_point(size = 2,color = \"red\")+ stat_qq_line(color=\"green\")+ xlab(\"x-axis\") + ylab(\"y-axis\")",
"e": 1626,
"s": 1282,
"text": null
},
{
"code": null,
"e": 1634,
"s": 1626,
"text": "Output:"
},
{
"code": null,
"e": 1660,
"s": 1634,
"text": "Fig. 2 Adding normal line"
},
{
"code": null,
"e": 1675,
"s": 1660,
"text": "adnanirshad158"
},
{
"code": null,
"e": 1682,
"s": 1675,
"text": "Picked"
},
{
"code": null,
"e": 1691,
"s": 1682,
"text": "R-Charts"
},
{
"code": null,
"e": 1700,
"s": 1691,
"text": "R-Graphs"
},
{
"code": null,
"e": 1708,
"s": 1700,
"text": "R-plots"
},
{
"code": null,
"e": 1719,
"s": 1708,
"text": "R Language"
}
] |
Perl | Variables
|
10 Aug, 2021
Variables in Perl are used to store and manipulate data throughout the program. When a variable is created it occupies memory space. The data type of a variable helps the interpreter to allocate memory and decide what to be stored in the reserved memory. Therefore, variables can store integers, decimals, or strings with the assignment of different data types to the variables.
A variable in Perl can be named anything with the use of a specific datatype. There are some rules to follow while naming a variable:
Variables in Perl are case-sensitive.
Example:
$John and $john are two different variables
It starts with $, @ or % as per the datatype required, followed by zero or more letters, underscores, and digits
Variables in Perl cannot contain white spaces or any other special character except underscore.
Example:
$my-name = "John"; // Invalid
$my name = "John"; // Invalid
$my_name = "John"; // Valid
Variable Declaration is done on the basis of the datatype used to define the variable. These variables can be of three different datatypes:
Scalar Variables: It contains a single string or numeric value. It starts with $ symbol.
Syntax: $var_name = value;
Example:
$item = "Hello"
$item_one = 2
Array Variables: It contains a randomly ordered set of values. It starts with @ symbol.
Syntax : @var_name = (val1, val2, val3, .....);
Example:
@price_list = (70, 30, 40);
@name_list = ("Apple", "Banana", "Guava");
Hash Variables: It contains (key, value) pair efficiently accessed per key. It starts with % symbol.
Syntax : %var_name = ( key1=>val1, key2=>val2, key3=>val3, .....);
Example:
%item_pairs = ("Apple" =>2, "Banana'=>3);
%pair_random = ("Hi" =>8, "Bye"=>9);
Perl allows modifying its variable values anytime after the variable declaration is done. There are various ways for the modification of a variable:
A scalar variable can be modified simply by redefining its value.
Example:
$name = "John";
# This can be modified by simply
# redeclaring the variable $name.
$name = "Rahul";
An element of an array can be modified by passing the index of that element to the array and defining a new value to it.
Example:
@array = ("A", "B", "C", "D", "E");
# If value of second variable is to
# be modified then it can be done by
@array[2] = "4";
# $array[2] = "4"; is an alternate way of updating value in an array.
# This will change the array to,
# @array = ("A", "B", "4", "D", "E");
A value in a hash can be modified by using its Key.
Example:
%Hash = ("A", 10, "B", 20, "C", 30)
# This will modify the value
# assigned to Key 'B'
$Hash{"B"} = 46;
Perl provides various methods to define a String to a variable. This can be done with the use of single quotes, double quotes, using q-operator and double-q operator, etc. Using single quotes and double quotes for writing strings is the same but there exists a slight difference between how they work. Strings that are written with the use of single quotes display the content written within it exactly as it is.
Example:
$name = "John"
print 'Hi $name\nHow are you?'
The above code will print:
Hi $name\nHow are you?
Whereas strings written within double quotes replace the variables with their value and then display the string. It even replaces the escape sequences with their real use.Example:
$name = "John"
print "Hi $name\nHow are you?"
The above code will print:
Hi John
How are you?
Example Code:
Perl
#!/usr/bin/perluse Data::Dumper; # Scalar Variable$name = "GeeksForGeeks"; # Array Variable@array = ("G", "E", "E", "K", "S"); # Hash Variable%Hash = ('Welcome', 10, 'to', 20, 'Geeks', 40); # Variable Modification@array[2] = "F"; print "Modified Array is @array\n"; # Interpolation of a Variable # Using Single Quoteprint 'Name is $name\n'; # Using Double Quotesprint "\nName is $name"; # Printing hash contentsprint Dumper(\%Hash);
Modified Array is G E F K S
Name is $name\n
Name is GeeksForGeeks$VAR1 = {
'to' => 20,
'Welcome' => 10,
'Geeks' => 40
};
vikas_iiitp
perl-basics
perl-data-types
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Aug, 2021"
},
{
"code": null,
"e": 408,
"s": 28,
"text": "Variables in Perl are used to store and manipulate data throughout the program. When a variable is created it occupies memory space. The data type of a variable helps the interpreter to allocate memory and decide what to be stored in the reserved memory. Therefore, variables can store integers, decimals, or strings with the assignment of different data types to the variables. "
},
{
"code": null,
"e": 543,
"s": 408,
"text": "A variable in Perl can be named anything with the use of a specific datatype. There are some rules to follow while naming a variable: "
},
{
"code": null,
"e": 583,
"s": 543,
"text": "Variables in Perl are case-sensitive. "
},
{
"code": null,
"e": 593,
"s": 583,
"text": "Example: "
},
{
"code": null,
"e": 637,
"s": 593,
"text": "$John and $john are two different variables"
},
{
"code": null,
"e": 750,
"s": 637,
"text": "It starts with $, @ or % as per the datatype required, followed by zero or more letters, underscores, and digits"
},
{
"code": null,
"e": 847,
"s": 750,
"text": "Variables in Perl cannot contain white spaces or any other special character except underscore. "
},
{
"code": null,
"e": 856,
"s": 847,
"text": "Example:"
},
{
"code": null,
"e": 945,
"s": 856,
"text": "$my-name = \"John\"; // Invalid \n$my name = \"John\"; // Invalid\n$my_name = \"John\"; // Valid"
},
{
"code": null,
"e": 1089,
"s": 945,
"text": " Variable Declaration is done on the basis of the datatype used to define the variable. These variables can be of three different datatypes: "
},
{
"code": null,
"e": 1180,
"s": 1089,
"text": "Scalar Variables: It contains a single string or numeric value. It starts with $ symbol. "
},
{
"code": null,
"e": 1207,
"s": 1180,
"text": "Syntax: $var_name = value;"
},
{
"code": null,
"e": 1217,
"s": 1207,
"text": "Example: "
},
{
"code": null,
"e": 1248,
"s": 1217,
"text": "$item = \"Hello\" \n$item_one = 2"
},
{
"code": null,
"e": 1337,
"s": 1248,
"text": "Array Variables: It contains a randomly ordered set of values. It starts with @ symbol. "
},
{
"code": null,
"e": 1385,
"s": 1337,
"text": "Syntax : @var_name = (val1, val2, val3, .....);"
},
{
"code": null,
"e": 1395,
"s": 1385,
"text": "Example: "
},
{
"code": null,
"e": 1466,
"s": 1395,
"text": "@price_list = (70, 30, 40);\n@name_list = (\"Apple\", \"Banana\", \"Guava\");"
},
{
"code": null,
"e": 1568,
"s": 1466,
"text": "Hash Variables: It contains (key, value) pair efficiently accessed per key. It starts with % symbol. "
},
{
"code": null,
"e": 1635,
"s": 1568,
"text": "Syntax : %var_name = ( key1=>val1, key2=>val2, key3=>val3, .....);"
},
{
"code": null,
"e": 1645,
"s": 1635,
"text": "Example: "
},
{
"code": null,
"e": 1725,
"s": 1645,
"text": "%item_pairs = (\"Apple\" =>2, \"Banana'=>3);\n%pair_random = (\"Hi\" =>8, \"Bye\"=>9);\n"
},
{
"code": null,
"e": 1877,
"s": 1725,
"text": " Perl allows modifying its variable values anytime after the variable declaration is done. There are various ways for the modification of a variable: "
},
{
"code": null,
"e": 1944,
"s": 1877,
"text": "A scalar variable can be modified simply by redefining its value. "
},
{
"code": null,
"e": 1954,
"s": 1944,
"text": "Example: "
},
{
"code": null,
"e": 2055,
"s": 1954,
"text": "$name = \"John\";\n\n# This can be modified by simply\n# redeclaring the variable $name.\n$name = \"Rahul\";"
},
{
"code": null,
"e": 2177,
"s": 2055,
"text": "An element of an array can be modified by passing the index of that element to the array and defining a new value to it. "
},
{
"code": null,
"e": 2187,
"s": 2177,
"text": "Example: "
},
{
"code": null,
"e": 2457,
"s": 2187,
"text": "@array = (\"A\", \"B\", \"C\", \"D\", \"E\");\n\n# If value of second variable is to\n# be modified then it can be done by\n@array[2] = \"4\";\n# $array[2] = \"4\"; is an alternate way of updating value in an array.\n\n# This will change the array to,\n# @array = (\"A\", \"B\", \"4\", \"D\", \"E\");"
},
{
"code": null,
"e": 2510,
"s": 2457,
"text": "A value in a hash can be modified by using its Key. "
},
{
"code": null,
"e": 2520,
"s": 2510,
"text": "Example: "
},
{
"code": null,
"e": 2626,
"s": 2520,
"text": "%Hash = (\"A\", 10, \"B\", 20, \"C\", 30)\n\n# This will modify the value \n# assigned to Key 'B'\n$Hash{\"B\"} = 46;"
},
{
"code": null,
"e": 3043,
"s": 2626,
"text": " Perl provides various methods to define a String to a variable. This can be done with the use of single quotes, double quotes, using q-operator and double-q operator, etc. Using single quotes and double quotes for writing strings is the same but there exists a slight difference between how they work. Strings that are written with the use of single quotes display the content written within it exactly as it is. "
},
{
"code": null,
"e": 3052,
"s": 3043,
"text": "Example:"
},
{
"code": null,
"e": 3099,
"s": 3052,
"text": "$name = \"John\"\nprint 'Hi $name\\nHow are you?' "
},
{
"code": null,
"e": 3126,
"s": 3099,
"text": "The above code will print:"
},
{
"code": null,
"e": 3149,
"s": 3126,
"text": "Hi $name\\nHow are you?"
},
{
"code": null,
"e": 3330,
"s": 3149,
"text": "Whereas strings written within double quotes replace the variables with their value and then display the string. It even replaces the escape sequences with their real use.Example: "
},
{
"code": null,
"e": 3377,
"s": 3330,
"text": "$name = \"John\"\nprint \"Hi $name\\nHow are you?\" "
},
{
"code": null,
"e": 3405,
"s": 3377,
"text": "The above code will print: "
},
{
"code": null,
"e": 3426,
"s": 3405,
"text": "Hi John\nHow are you?"
},
{
"code": null,
"e": 3441,
"s": 3426,
"text": "Example Code: "
},
{
"code": null,
"e": 3446,
"s": 3441,
"text": "Perl"
},
{
"code": "#!/usr/bin/perluse Data::Dumper; # Scalar Variable$name = \"GeeksForGeeks\"; # Array Variable@array = (\"G\", \"E\", \"E\", \"K\", \"S\"); # Hash Variable%Hash = ('Welcome', 10, 'to', 20, 'Geeks', 40); # Variable Modification@array[2] = \"F\"; print \"Modified Array is @array\\n\"; # Interpolation of a Variable # Using Single Quoteprint 'Name is $name\\n'; # Using Double Quotesprint \"\\nName is $name\"; # Printing hash contentsprint Dumper(\\%Hash);",
"e": 3879,
"s": 3446,
"text": null
},
{
"code": null,
"e": 4038,
"s": 3879,
"text": "Modified Array is G E F K S\nName is $name\\n\nName is GeeksForGeeks$VAR1 = {\n 'to' => 20,\n 'Welcome' => 10,\n 'Geeks' => 40\n };"
},
{
"code": null,
"e": 4052,
"s": 4040,
"text": "vikas_iiitp"
},
{
"code": null,
"e": 4064,
"s": 4052,
"text": "perl-basics"
},
{
"code": null,
"e": 4080,
"s": 4064,
"text": "perl-data-types"
},
{
"code": null,
"e": 4087,
"s": 4080,
"text": "Picked"
},
{
"code": null,
"e": 4092,
"s": 4087,
"text": "Perl"
},
{
"code": null,
"e": 4097,
"s": 4092,
"text": "Perl"
}
] |
How to Add or Remove class in jQuery ?
|
10 Aug, 2021
The addClass() or removeClass() methods are used to add the CSS classes when there is a need to add to our webpage when there is some event listener or to create some kind of effect.
In this article, let us see how can we add a CSS class or remove a CSS class in jQuery.
Syntax:
Adding a class:$('selector').addClass(class_name);
$('selector').addClass(class_name);
Removing a class:$('selector').removeClass(class_name);
$('selector').removeClass(class_name);
Example: The following example adds a class that makes the background colour black when clicked on ADD CLASS button and also removes that added class when clicked on the REMOVE CLASS button.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <!-- Including jQuery --> <script src= "https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"> </script> <style> h1 { color: #006600; } button { color: white; background-color: #006600; width: auto; height: 30px; } body { text-align: center; } div { margin: 10px; height: 150px; width: 150px; position: relative; text-align: center; display: flex; left: 215px; } .bg-black { background-color: black; } </style></head> <body> <h1>Geeks For Geeks</h1> <button id="btnadd"> ADD CLASS </button> <button id="btnremove"> REMOVE CLASS </button> <div id="GFG_IMAGE"> <!-- Image added using img tag with src attribute --> <img src="https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg" height='150px' width='150px'> <img> </div> <script> $(document).ready(function() { $('#btnadd').click(function() { $('img').addClass('bg-black'); }); $('#btnremove').click(function() { $('img').removeClass('bg-black'); }); }); </script></body> </html>
Output:
Add class and remove class
CSS-Properties
jQuery-Methods
jQuery-Questions
Picked
CSS
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
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": "\n10 Aug, 2021"
},
{
"code": null,
"e": 211,
"s": 28,
"text": "The addClass() or removeClass() methods are used to add the CSS classes when there is a need to add to our webpage when there is some event listener or to create some kind of effect."
},
{
"code": null,
"e": 299,
"s": 211,
"text": "In this article, let us see how can we add a CSS class or remove a CSS class in jQuery."
},
{
"code": null,
"e": 307,
"s": 299,
"text": "Syntax:"
},
{
"code": null,
"e": 358,
"s": 307,
"text": "Adding a class:$('selector').addClass(class_name);"
},
{
"code": null,
"e": 394,
"s": 358,
"text": "$('selector').addClass(class_name);"
},
{
"code": null,
"e": 450,
"s": 394,
"text": "Removing a class:$('selector').removeClass(class_name);"
},
{
"code": null,
"e": 489,
"s": 450,
"text": "$('selector').removeClass(class_name);"
},
{
"code": null,
"e": 680,
"s": 489,
"text": "Example: The following example adds a class that makes the background colour black when clicked on ADD CLASS button and also removes that added class when clicked on the REMOVE CLASS button."
},
{
"code": null,
"e": 685,
"s": 680,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <!-- Including jQuery --> <script src= \"https://code.jquery.com/jquery-3.6.0.min.js\" integrity=\"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=\" crossorigin=\"anonymous\"> </script> <style> h1 { color: #006600; } button { color: white; background-color: #006600; width: auto; height: 30px; } body { text-align: center; } div { margin: 10px; height: 150px; width: 150px; position: relative; text-align: center; display: flex; left: 215px; } .bg-black { background-color: black; } </style></head> <body> <h1>Geeks For Geeks</h1> <button id=\"btnadd\"> ADD CLASS </button> <button id=\"btnremove\"> REMOVE CLASS </button> <div id=\"GFG_IMAGE\"> <!-- Image added using img tag with src attribute --> <img src=\"https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg\" height='150px' width='150px'> <img> </div> <script> $(document).ready(function() { $('#btnadd').click(function() { $('img').addClass('bg-black'); }); $('#btnremove').click(function() { $('img').removeClass('bg-black'); }); }); </script></body> </html>",
"e": 2393,
"s": 685,
"text": null
},
{
"code": null,
"e": 2401,
"s": 2393,
"text": "Output:"
},
{
"code": null,
"e": 2428,
"s": 2401,
"text": "Add class and remove class"
},
{
"code": null,
"e": 2443,
"s": 2428,
"text": "CSS-Properties"
},
{
"code": null,
"e": 2458,
"s": 2443,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 2475,
"s": 2458,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 2482,
"s": 2475,
"text": "Picked"
},
{
"code": null,
"e": 2486,
"s": 2482,
"text": "CSS"
},
{
"code": null,
"e": 2491,
"s": 2486,
"text": "HTML"
},
{
"code": null,
"e": 2498,
"s": 2491,
"text": "JQuery"
},
{
"code": null,
"e": 2515,
"s": 2498,
"text": "Web Technologies"
},
{
"code": null,
"e": 2520,
"s": 2515,
"text": "HTML"
},
{
"code": null,
"e": 2618,
"s": 2520,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2657,
"s": 2618,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2696,
"s": 2657,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 2735,
"s": 2696,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 2772,
"s": 2735,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 2801,
"s": 2772,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2825,
"s": 2801,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2878,
"s": 2825,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2938,
"s": 2878,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 2999,
"s": 2938,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Create a Radial Bar Chart using Recharts in ReactJS
|
29 Jul, 2021
Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents).
Radial Bar chart is a categorical bar chart that is displayed in polar coordinates. It is also known as a circular bar chart. It is used to show comparisons among categorical data by using a circular shape plot.
Approach: To create Radial Bar chart in react using recharts, we use RadialBarChart component of Recharts npm package. To create bar’s in the chart, we use RadialBar component.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the required modules using the following command.
npm install --save recharts
Project Structure: It will look like the following.
Example 1: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import { RadialBarChart, RadialBar } from 'recharts'; const App = () => { // Sample dataconst data = [ {name:'A', x:1,fill:"green"}, {name:'B', x:2, fill:"yellow"}, {name:'C', x:3, fill:"aqua"}, {name:'D', x:4, fill: "blue"}, {name:'E', x:5, fill:"orange"}, {name:'F', x:6, fill:"red"}, {name:'G', x:7, fill:"black"}, {name:'H', x:8, fill:"purple"}, {name:'I', x:9, fill:"gray"},]; return ( <RadialBarChart width={500} height={500} data={data}> <RadialBar minAngle={15} dataKey="x"/> </RadialBarChart>);} export default App;
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:
Output
Example 2: Now change the following code in the App.js file.
App.js
import React from 'react';import { RadialBarChart, RadialBar } from 'recharts'; const App = () => { // Sample dataconst data = [ { name: 'A', x: 31.47, fill: '#8784d8', }, { name: 'B', x: 26.69, fill: '#84a6ed', }, { name: 'C', x: 15.69, fill: '#8ed1e1', }, { name: 'D', x: 8.22, fill: '#82da9d', }, { name: 'E', x: 8.63, fill: '#a2de6c', }, { name: 'F', x: 2.63, fill: '#d0dd57', }, { name: 'G', x: 6.67, fill: '#ffa658', },]; return ( <RadialBarChart width={500} height={500} data={data} innerRadius="20%" outerRadius="70%"> <RadialBar minAngle={30} dataKey="x" clockWise/> </RadialBarChart>);} export default App;
Output: Save the file using CTRL+S. Now open your browser and go to http://localhost:3000/, you will see the following output:
Output
React-Questions
Recharts
JavaScript
ReactJS
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
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
Axios in React: A Guide for Beginners
ReactJS Functional Components
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 246,
"s": 28,
"text": "Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents). "
},
{
"code": null,
"e": 458,
"s": 246,
"text": "Radial Bar chart is a categorical bar chart that is displayed in polar coordinates. It is also known as a circular bar chart. It is used to show comparisons among categorical data by using a circular shape plot."
},
{
"code": null,
"e": 635,
"s": 458,
"text": "Approach: To create Radial Bar chart in react using recharts, we use RadialBarChart component of Recharts npm package. To create bar’s in the chart, we use RadialBar component."
},
{
"code": null,
"e": 687,
"s": 637,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 751,
"s": 687,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 783,
"s": 751,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 883,
"s": 783,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command."
},
{
"code": null,
"e": 897,
"s": 883,
"text": "cd foldername"
},
{
"code": null,
"e": 1003,
"s": 897,
"text": "Step 3: After creating the ReactJS application, Install the required modules using the following command."
},
{
"code": null,
"e": 1031,
"s": 1003,
"text": "npm install --save recharts"
},
{
"code": null,
"e": 1083,
"s": 1031,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 1215,
"s": 1083,
"text": "Example 1: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 1222,
"s": 1215,
"text": "App.js"
},
{
"code": "import React from 'react';import { RadialBarChart, RadialBar } from 'recharts'; const App = () => { // Sample dataconst data = [ {name:'A', x:1,fill:\"green\"}, {name:'B', x:2, fill:\"yellow\"}, {name:'C', x:3, fill:\"aqua\"}, {name:'D', x:4, fill: \"blue\"}, {name:'E', x:5, fill:\"orange\"}, {name:'F', x:6, fill:\"red\"}, {name:'G', x:7, fill:\"black\"}, {name:'H', x:8, fill:\"purple\"}, {name:'I', x:9, fill:\"gray\"},]; return ( <RadialBarChart width={500} height={500} data={data}> <RadialBar minAngle={15} dataKey=\"x\"/> </RadialBarChart>);} export default App;",
"e": 1795,
"s": 1222,
"text": null
},
{
"code": null,
"e": 1908,
"s": 1795,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 1918,
"s": 1908,
"text": "npm start"
},
{
"code": null,
"e": 2017,
"s": 1918,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 2024,
"s": 2017,
"text": "Output"
},
{
"code": null,
"e": 2086,
"s": 2024,
"text": "Example 2: Now change the following code in the App.js file. "
},
{
"code": null,
"e": 2093,
"s": 2086,
"text": "App.js"
},
{
"code": "import React from 'react';import { RadialBarChart, RadialBar } from 'recharts'; const App = () => { // Sample dataconst data = [ { name: 'A', x: 31.47, fill: '#8784d8', }, { name: 'B', x: 26.69, fill: '#84a6ed', }, { name: 'C', x: 15.69, fill: '#8ed1e1', }, { name: 'D', x: 8.22, fill: '#82da9d', }, { name: 'E', x: 8.63, fill: '#a2de6c', }, { name: 'F', x: 2.63, fill: '#d0dd57', }, { name: 'G', x: 6.67, fill: '#ffa658', },]; return ( <RadialBarChart width={500} height={500} data={data} innerRadius=\"20%\" outerRadius=\"70%\"> <RadialBar minAngle={30} dataKey=\"x\" clockWise/> </RadialBarChart>);} export default App;",
"e": 2804,
"s": 2093,
"text": null
},
{
"code": null,
"e": 2931,
"s": 2804,
"text": "Output: Save the file using CTRL+S. Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 2938,
"s": 2931,
"text": "Output"
},
{
"code": null,
"e": 2954,
"s": 2938,
"text": "React-Questions"
},
{
"code": null,
"e": 2963,
"s": 2954,
"text": "Recharts"
},
{
"code": null,
"e": 2974,
"s": 2963,
"text": "JavaScript"
},
{
"code": null,
"e": 2982,
"s": 2974,
"text": "ReactJS"
},
{
"code": null,
"e": 2999,
"s": 2982,
"text": "Web Technologies"
},
{
"code": null,
"e": 3097,
"s": 2999,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3158,
"s": 3097,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3198,
"s": 3158,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3239,
"s": 3198,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3281,
"s": 3239,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3303,
"s": 3281,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 3346,
"s": 3303,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 3391,
"s": 3346,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 3429,
"s": 3391,
"text": "Axios in React: A Guide for Beginners"
}
] |
Fibonacci number in an array
|
24 Mar, 2021
We have been given an array and our task is to check if the element of array is present in Fibonacci series or not. If yes, then print that element. Examples:
Input : 4, 2, 8, 5, 20, 1, 40, 13, 23
Output : 2 8 5 1 13
Here, Fibonacci series will be 0, 1, 1, 2,
3, 5, 8, 13, 21, 34, 55. Numbers that are present
in array are 2, 8, 5, 1, 13
For 2 -> 5 * 2 * 2 - 4 = 36
36 is a perfect square root of 6.
Input : 4, 7, 6, 25
Output : No Fibonacci number in this array
A number is said to be in Fibonacci series if either (5 * n * n – 4) or (5 * n * n + 4) is a perfect square. Please refer check if a given number is Fibonacci number for details.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find Fibonacci series numbers// in a given array.#include <bits/stdc++.h>using namespace std; // Function to check number is a// perfect square or notbool isPerfectSquare(int num){ int n = sqrt(num); return (n * n == num);} // Function to check if the number// is in Fibonacci or notvoid checkFib(int array[], int n){ int count = 0; for (int i = 0; i < n; i++) { if (isPerfectSquare(5 * array[i] * array[i] + 4) || isPerfectSquare(5 * array[i] * array[i] - 4)) { cout << array[i] << " "; count++; } } if (count == 0) cout << "None present" << endl;} // Driver functionint main(){ int array[] = { 4, 2, 8, 5, 20, 1, 40, 13, 23 }; int n = sizeof(array) / sizeof(array[0]); checkFib(array, n); return 0;}
// Java program to find Fibonacci series numbers// in a given arrayimport java.io.*;import java.math.*; class GFG { // Function to check number is a // perfect square or not static boolean isPerfectSquare(int num) { int n = (int)(Math.sqrt(num)); return (n * n == num); } // Function to check if the number // is in Fibonacci or not static void checkFib(int array[], int n) { int count = 0; for (int i = 0; i < n; i++) { if (isPerfectSquare(5 * array[i] * array[i] + 4) || isPerfectSquare(5 * array[i] * array[i] - 4)) { System.out.print(array[i] + " "); count++; } } if (count == 0) System.out.println("None Present"); } // driver program public static void main(String[] args) { int array[] = { 4, 2, 8, 5, 20, 1, 40, 13, 23 }; int n = array.length; checkFib(array, n); }} // Contributed by Pramod Kumar
# Python program to find# Fibonacci series numbers# in a given array. import math def isPerfectSquare(num): n = int(math.sqrt(num)) return (n * n == num) # Function to check if the number# is in Fibonacci or notdef checkFib(array, n): count = 0 for i in range(n): if (isPerfectSquare(5 * array[i] * array[i] + 4) or isPerfectSquare(5 * array[i] * array[i] - 4)): print(array[i], " ", end =""); count = count + 1 if (count == 0): print("None present"); # driver codearray = [4, 2, 8, 5, 20, 1, 40, 13, 23]n = len(array) checkFib(array, n) # This code is contributed# by Anant Agarwal.
// C# program to find Fibonacci series// numbers in a given arrayusing System; class GFG { // Function to check number is a // perfect square or not static bool isPerfectSquare(int num) { int n = (int)(Math.Sqrt(num)); return (n * n == num); } // Function to check if the number // is in Fibonacci or not static void checkFib(int[] array, int n) { int count = 0; for (int i = 0; i < n; i++) { if (isPerfectSquare(5 * array[i] * array[i] + 4) || isPerfectSquare(5 * array[i] * array[i] - 4)) { Console.Write(array[i] + " "); count++; } } if (count == 0) Console.WriteLine("None Present"); } // driver program public static void Main() { int[] array = { 4, 2, 8, 5, 20, 1, 40, 13, 23 }; int n = array.Length; checkFib(array, n); }} // This code is contributed by Sam007
<?php// PHP program to find// Fibonacci series numbers// in a given array. // Function to check// number is a perfect// square or notfunction isPerfectSquare($num){ $n = (int)(sqrt($num)); return ($n * $n == $num);} // Function to check// if the number is// in Fibonacci or notfunction checkFib($array, $n){ $count = 0; for ($i = 0; $i < $n; $i++) { if (isPerfectSquare(5 * $array[$i] * $array[$i] + 4) || isPerfectSquare(5 * $array[$i] * $array[$i] - 4)) { echo $array[$i]." "; $count++; } } if ($count == 0) echo "None present\n";} // Driver Code$array = array(4, 2, 8, 5, 20, 1, 40, 13, 23);$n = sizeof($array); checkFib($array, $n); // This code is contributed by mits. ?>
<script>// Javascript program to find// Fibonacci series numbers// in a given array. // Function to check// number is a perfect// square or notfunction isPerfectSquare(num){ let n = parseInt(Math.sqrt(num)); return (n * n == num);} // Function to check// if the number is// in Fibonacci or notfunction checkFib(array, n){ let count = 0; for (let i = 0; i < n; i++) { if (isPerfectSquare(5 * array[i] * array[i] + 4) || isPerfectSquare(5 * array[i] * array[i] - 4)) { document.write(array[i] + " "); count++; } } if (count == 0) document.write("None present + <br>");} // Driver Codelet array = [4, 2, 8, 5, 20, 1, 40, 13, 23];let n = array.length; checkFib(array, n); // This code is contributed by _saurabh_jaiswal</script>
Output:
2 8 5 1 13
This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sam007
Mithun Kumar
_saurabh_jaiswal
Fibonacci
Arrays
Mathematical
Arrays
Mathematical
Fibonacci
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
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": "\n24 Mar, 2021"
},
{
"code": null,
"e": 213,
"s": 52,
"text": "We have been given an array and our task is to check if the element of array is present in Fibonacci series or not. If yes, then print that element. Examples: "
},
{
"code": null,
"e": 521,
"s": 213,
"text": "Input : 4, 2, 8, 5, 20, 1, 40, 13, 23\nOutput : 2 8 5 1 13\nHere, Fibonacci series will be 0, 1, 1, 2, \n3, 5, 8, 13, 21, 34, 55. Numbers that are present \nin array are 2, 8, 5, 1, 13\nFor 2 -> 5 * 2 * 2 - 4 = 36\n36 is a perfect square root of 6.\n\nInput : 4, 7, 6, 25\nOutput : No Fibonacci number in this array"
},
{
"code": null,
"e": 705,
"s": 523,
"text": "A number is said to be in Fibonacci series if either (5 * n * n – 4) or (5 * n * n + 4) is a perfect square. Please refer check if a given number is Fibonacci number for details. "
},
{
"code": null,
"e": 709,
"s": 705,
"text": "C++"
},
{
"code": null,
"e": 714,
"s": 709,
"text": "Java"
},
{
"code": null,
"e": 722,
"s": 714,
"text": "Python3"
},
{
"code": null,
"e": 725,
"s": 722,
"text": "C#"
},
{
"code": null,
"e": 729,
"s": 725,
"text": "PHP"
},
{
"code": null,
"e": 740,
"s": 729,
"text": "Javascript"
},
{
"code": "// CPP program to find Fibonacci series numbers// in a given array.#include <bits/stdc++.h>using namespace std; // Function to check number is a// perfect square or notbool isPerfectSquare(int num){ int n = sqrt(num); return (n * n == num);} // Function to check if the number// is in Fibonacci or notvoid checkFib(int array[], int n){ int count = 0; for (int i = 0; i < n; i++) { if (isPerfectSquare(5 * array[i] * array[i] + 4) || isPerfectSquare(5 * array[i] * array[i] - 4)) { cout << array[i] << \" \"; count++; } } if (count == 0) cout << \"None present\" << endl;} // Driver functionint main(){ int array[] = { 4, 2, 8, 5, 20, 1, 40, 13, 23 }; int n = sizeof(array) / sizeof(array[0]); checkFib(array, n); return 0;}",
"e": 1535,
"s": 740,
"text": null
},
{
"code": "// Java program to find Fibonacci series numbers// in a given arrayimport java.io.*;import java.math.*; class GFG { // Function to check number is a // perfect square or not static boolean isPerfectSquare(int num) { int n = (int)(Math.sqrt(num)); return (n * n == num); } // Function to check if the number // is in Fibonacci or not static void checkFib(int array[], int n) { int count = 0; for (int i = 0; i < n; i++) { if (isPerfectSquare(5 * array[i] * array[i] + 4) || isPerfectSquare(5 * array[i] * array[i] - 4)) { System.out.print(array[i] + \" \"); count++; } } if (count == 0) System.out.println(\"None Present\"); } // driver program public static void main(String[] args) { int array[] = { 4, 2, 8, 5, 20, 1, 40, 13, 23 }; int n = array.length; checkFib(array, n); }} // Contributed by Pramod Kumar",
"e": 2511,
"s": 1535,
"text": null
},
{
"code": "# Python program to find# Fibonacci series numbers# in a given array. import math def isPerfectSquare(num): n = int(math.sqrt(num)) return (n * n == num) # Function to check if the number# is in Fibonacci or notdef checkFib(array, n): count = 0 for i in range(n): if (isPerfectSquare(5 * array[i] * array[i] + 4) or isPerfectSquare(5 * array[i] * array[i] - 4)): print(array[i], \" \", end =\"\"); count = count + 1 if (count == 0): print(\"None present\"); # driver codearray = [4, 2, 8, 5, 20, 1, 40, 13, 23]n = len(array) checkFib(array, n) # This code is contributed# by Anant Agarwal.",
"e": 3192,
"s": 2511,
"text": null
},
{
"code": "// C# program to find Fibonacci series// numbers in a given arrayusing System; class GFG { // Function to check number is a // perfect square or not static bool isPerfectSquare(int num) { int n = (int)(Math.Sqrt(num)); return (n * n == num); } // Function to check if the number // is in Fibonacci or not static void checkFib(int[] array, int n) { int count = 0; for (int i = 0; i < n; i++) { if (isPerfectSquare(5 * array[i] * array[i] + 4) || isPerfectSquare(5 * array[i] * array[i] - 4)) { Console.Write(array[i] + \" \"); count++; } } if (count == 0) Console.WriteLine(\"None Present\"); } // driver program public static void Main() { int[] array = { 4, 2, 8, 5, 20, 1, 40, 13, 23 }; int n = array.Length; checkFib(array, n); }} // This code is contributed by Sam007",
"e": 4161,
"s": 3192,
"text": null
},
{
"code": "<?php// PHP program to find// Fibonacci series numbers// in a given array. // Function to check// number is a perfect// square or notfunction isPerfectSquare($num){ $n = (int)(sqrt($num)); return ($n * $n == $num);} // Function to check// if the number is// in Fibonacci or notfunction checkFib($array, $n){ $count = 0; for ($i = 0; $i < $n; $i++) { if (isPerfectSquare(5 * $array[$i] * $array[$i] + 4) || isPerfectSquare(5 * $array[$i] * $array[$i] - 4)) { echo $array[$i].\" \"; $count++; } } if ($count == 0) echo \"None present\\n\";} // Driver Code$array = array(4, 2, 8, 5, 20, 1, 40, 13, 23);$n = sizeof($array); checkFib($array, $n); // This code is contributed by mits. ?>",
"e": 4997,
"s": 4161,
"text": null
},
{
"code": "<script>// Javascript program to find// Fibonacci series numbers// in a given array. // Function to check// number is a perfect// square or notfunction isPerfectSquare(num){ let n = parseInt(Math.sqrt(num)); return (n * n == num);} // Function to check// if the number is// in Fibonacci or notfunction checkFib(array, n){ let count = 0; for (let i = 0; i < n; i++) { if (isPerfectSquare(5 * array[i] * array[i] + 4) || isPerfectSquare(5 * array[i] * array[i] - 4)) { document.write(array[i] + \" \"); count++; } } if (count == 0) document.write(\"None present + <br>\");} // Driver Codelet array = [4, 2, 8, 5, 20, 1, 40, 13, 23];let n = array.length; checkFib(array, n); // This code is contributed by _saurabh_jaiswal</script>",
"e": 5881,
"s": 4997,
"text": null
},
{
"code": null,
"e": 5891,
"s": 5881,
"text": "Output: "
},
{
"code": null,
"e": 5902,
"s": 5891,
"text": "2 8 5 1 13"
},
{
"code": null,
"e": 6323,
"s": 5902,
"text": "This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 6330,
"s": 6323,
"text": "Sam007"
},
{
"code": null,
"e": 6343,
"s": 6330,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 6360,
"s": 6343,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 6370,
"s": 6360,
"text": "Fibonacci"
},
{
"code": null,
"e": 6377,
"s": 6370,
"text": "Arrays"
},
{
"code": null,
"e": 6390,
"s": 6377,
"text": "Mathematical"
},
{
"code": null,
"e": 6397,
"s": 6390,
"text": "Arrays"
},
{
"code": null,
"e": 6410,
"s": 6397,
"text": "Mathematical"
},
{
"code": null,
"e": 6420,
"s": 6410,
"text": "Fibonacci"
},
{
"code": null,
"e": 6518,
"s": 6420,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6533,
"s": 6518,
"text": "Arrays in Java"
},
{
"code": null,
"e": 6579,
"s": 6533,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 6647,
"s": 6579,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 6691,
"s": 6647,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 6723,
"s": 6691,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 6753,
"s": 6723,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 6796,
"s": 6753,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 6856,
"s": 6796,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 6871,
"s": 6856,
"text": "C++ Data Types"
}
] |
GATE-CS-2005 - GeeksforGeeks
|
11 Oct, 2021
int ( * f) (int * )
f * (int * ) int
It is a lattice but not a distributive lattice.
Table for Join Operation of above Hesse diagram
V |a b c d e
________________
a |a a a a a
b |a b a a b
c |a a c a c
d |a a a d d
e |a b c d e
Table for Meet Operation of above Hesse diagram
^ |a b c d e
_______________
a |a b c d e
b |b b e e e
c |c e c e e
d |d e e d e
e |e e e e e
Therefore for any two element p, q in the lattice (A,<=)
p <= p V q ; p^q <= p
This satisfies for all element (a,b,c,d,e).
which has 'a' as unique least upper bound and 'e' as unique
greatest lower bound.
The given lattice doesn't obey distributive law, so it is
not distributive lattice,
Note that for b,c,d we have distributive law
b^(cVd) = (b^c) V (b^d). From the diagram / tables given above
we can verify as follows,
(i) L.H.S. = b ^ (c V d) = b ^ a = b
(ii) R.H.S. = (b^c) V (b^d) = e v e = e
b != e which contradict the distributive law.
Hence it is not distributive lattice.
so, option (B) is correct.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
Split given String into substrings of size K by filling elements
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Java Threads
Top 20 Puzzles Commonly Asked During SDE Interviews
Software Testing Metrics, its Types and Example
Software Testing - Boundary Value Analysis
TCS NQT Coding Sheet
|
[
{
"code": null,
"e": 29577,
"s": 29549,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 29597,
"s": 29577,
"text": "int ( * f) (int * )"
},
{
"code": null,
"e": 29614,
"s": 29597,
"text": "f * (int * ) int"
},
{
"code": null,
"e": 30578,
"s": 29614,
"text": "It is a lattice but not a distributive lattice.\n\nTable for Join Operation of above Hesse diagram\n\nV |a b c d e\n________________\na |a a a a a\nb |a b a a b\nc |a a c a c\nd |a a a d d\ne |a b c d e\n\nTable for Meet Operation of above Hesse diagram\n\n^ |a b c d e\n_______________\na |a b c d e\nb |b b e e e\nc |c e c e e\nd |d e e d e\ne |e e e e e\n\nTherefore for any two element p, q in the lattice (A,<=)\n\np <= p V q ; p^q <= p\n\nThis satisfies for all element (a,b,c,d,e).\n\nwhich has 'a' as unique least upper bound and 'e' as unique \ngreatest lower bound.\n\nThe given lattice doesn't obey distributive law, so it is \nnot distributive lattice,\n\nNote that for b,c,d we have distributive law\n\nb^(cVd) = (b^c) V (b^d). From the diagram / tables given above \nwe can verify as follows,\n\n(i) L.H.S. = b ^ (c V d) = b ^ a = b\n\n(ii) R.H.S. = (b^c) V (b^d) = e v e = e\n\nb != e which contradict the distributive law. \nHence it is not distributive lattice.\n\nso, option (B) is correct. "
},
{
"code": null,
"e": 30676,
"s": 30578,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 30750,
"s": 30676,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 30803,
"s": 30750,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 30868,
"s": 30803,
"text": "Split given String into substrings of size K by filling elements"
},
{
"code": null,
"e": 30917,
"s": 30868,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 30942,
"s": 30917,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30955,
"s": 30942,
"text": "Java Threads"
},
{
"code": null,
"e": 31007,
"s": 30955,
"text": "Top 20 Puzzles Commonly Asked During SDE Interviews"
},
{
"code": null,
"e": 31055,
"s": 31007,
"text": "Software Testing Metrics, its Types and Example"
},
{
"code": null,
"e": 31098,
"s": 31055,
"text": "Software Testing - Boundary Value Analysis"
}
] |
Python Program to Print Numbers in an Interval
|
11 May, 2020
Given a range of numbers, find all the numbers between them.
Input : l = 2, u = 5Output : 2 3 4 5
Input : l = 10, u = 20Output : 10 11 12 13 14 15 16 17 18 19 20
The idea is to use range function in Python.
# Python program to print all the numbers within an intervall = 10u = 20 for num in range(l, u + 1): print(num)
10
11
12
13
14
15
16
17
18
19
20
We can also print alternate numbers or numbers with given steps.
# Python program to print all EVEN numbers within an intervall = 10u = 20if l%2==0: for num in range(l, u + 1, 2): print(num)else: for num in range(l+1, u + 1, 2): print(num)
10
12
14
16
18
20
ajeetkjnp68
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
Object Oriented Programming in C++
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 May, 2020"
},
{
"code": null,
"e": 114,
"s": 53,
"text": "Given a range of numbers, find all the numbers between them."
},
{
"code": null,
"e": 151,
"s": 114,
"text": "Input : l = 2, u = 5Output : 2 3 4 5"
},
{
"code": null,
"e": 215,
"s": 151,
"text": "Input : l = 10, u = 20Output : 10 11 12 13 14 15 16 17 18 19 20"
},
{
"code": null,
"e": 260,
"s": 215,
"text": "The idea is to use range function in Python."
},
{
"code": "# Python program to print all the numbers within an intervall = 10u = 20 for num in range(l, u + 1): print(num)",
"e": 376,
"s": 260,
"text": null
},
{
"code": null,
"e": 410,
"s": 376,
"text": "10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n"
},
{
"code": null,
"e": 475,
"s": 410,
"text": "We can also print alternate numbers or numbers with given steps."
},
{
"code": "# Python program to print all EVEN numbers within an intervall = 10u = 20if l%2==0: for num in range(l, u + 1, 2): print(num)else: for num in range(l+1, u + 1, 2): print(num)",
"e": 670,
"s": 475,
"text": null
},
{
"code": null,
"e": 689,
"s": 670,
"text": "10\n12\n14\n16\n18\n20\n"
},
{
"code": null,
"e": 701,
"s": 689,
"text": "ajeetkjnp68"
},
{
"code": null,
"e": 708,
"s": 701,
"text": "Python"
},
{
"code": null,
"e": 727,
"s": 708,
"text": "School Programming"
},
{
"code": null,
"e": 825,
"s": 727,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 867,
"s": 825,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 889,
"s": 867,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 915,
"s": 889,
"text": "Python String | replace()"
},
{
"code": null,
"e": 947,
"s": 915,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 976,
"s": 947,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1001,
"s": 976,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 1017,
"s": 1001,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 1040,
"s": 1017,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1059,
"s": 1040,
"text": "Interfaces in Java"
}
] |
What is Three dots(...) or Ellipsis in Python3
|
05 Sep, 2020
Ellipsis is a Python Object. It has no Methods. It is a singleton Object i.e, provides easy access to single instances.
Various Use Cases of Ellipsis (...):
Default Secondary Prompt in Python interpreter.
Accessing and slicing multidimensional Arrays/NumPy indexing.
In type hinting.
Used as Pass Statement inside Functions.
Ellipsis notation[...] is used as a default secondary prompt in Python interpreter which is seen during multi-line constructs
Example:
Accessing: Giving access to a specified range of elements, just omitting out the serial indices.
Slicing: Important use of Ellipsis is in slicing higher-dimensional data structures.
Example:
Suppose, we have a 4-dimensional matrix of order 2x2x2x2. To select all first row elements(in case of row-major structure) in the 4th dimension, we can simply use the ellipsis notation
Python3
# importing numpyimport numpy as np array = np.random.rand(2, 2, 2, 2)print(array[..., 0])print(array[Ellipsis, 0])
Output:
[[[0.46253663 0.03092289]
[0.72723607 0.75953107]]
[[0.33160093 0.79259324]
[0.76757812 0.21241883]]]
[[[0.46253663 0.03092289]
[0.72723607 0.75953107]]
[[0.33160093 0.79259324]
[0.76757812 0.21241883]]]
In the above example, [:, :, :, 0], [..., 0] and [Ellipsis, 0] are all equivalent.
We can not have multiple ellipsis in a single slicing like a[...,index,...]
Ellipsis is used in specifying type hints using the typing module (e.g. Callable[..., str]). It can serve in either way:
Method 1: When the argument(s) of the function allows the type: Any
Actually callable takes the arguments:
Callable "[" parameters_expression, type_expression "]"
(e.g. Callable[..., str])
Example:
Python3
from typing import Callable def inject(get_next_item: Callable[..., str]) -> None: ...# Argument type is assumed as type: Anydef foo(x: ...) -> None: ...
Using ‘...’ as parameters_expression signifies a function that returns a string without specifying the call signature.
Method 2: When the return value of the function is of type: Any
Actually callable returns this way:
Callable "[" parameters_expression, type_expression "]" -> return_type: #body
Example:
Python3
class flow: # (using "value: Any" to allow arbitrary types) def __understand__(self, name: str, value: ...) -> None: ...
Ellipsis is used instead of pass statement inside functions. ‘pass’ replaced by ‘...’ or ‘Ellipsis’.
Example:
Python3
# style1def foo(): pass# style2def foo(): ...# both the styles are same
Ellipsis can also be used as a default argument value. Especially when you want to distinguish between not passing in value and passing in None.
Example:
Python3
def foo(x = ...): return x print(foo)
Output:
<function foo at 0x7fabdeea6e18>
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 Sep, 2020"
},
{
"code": null,
"e": 148,
"s": 28,
"text": "Ellipsis is a Python Object. It has no Methods. It is a singleton Object i.e, provides easy access to single instances."
},
{
"code": null,
"e": 185,
"s": 148,
"text": "Various Use Cases of Ellipsis (...):"
},
{
"code": null,
"e": 233,
"s": 185,
"text": "Default Secondary Prompt in Python interpreter."
},
{
"code": null,
"e": 295,
"s": 233,
"text": "Accessing and slicing multidimensional Arrays/NumPy indexing."
},
{
"code": null,
"e": 312,
"s": 295,
"text": "In type hinting."
},
{
"code": null,
"e": 353,
"s": 312,
"text": "Used as Pass Statement inside Functions."
},
{
"code": null,
"e": 479,
"s": 353,
"text": "Ellipsis notation[...] is used as a default secondary prompt in Python interpreter which is seen during multi-line constructs"
},
{
"code": null,
"e": 488,
"s": 479,
"text": "Example:"
},
{
"code": null,
"e": 585,
"s": 488,
"text": "Accessing: Giving access to a specified range of elements, just omitting out the serial indices."
},
{
"code": null,
"e": 670,
"s": 585,
"text": "Slicing: Important use of Ellipsis is in slicing higher-dimensional data structures."
},
{
"code": null,
"e": 679,
"s": 670,
"text": "Example:"
},
{
"code": null,
"e": 864,
"s": 679,
"text": "Suppose, we have a 4-dimensional matrix of order 2x2x2x2. To select all first row elements(in case of row-major structure) in the 4th dimension, we can simply use the ellipsis notation"
},
{
"code": null,
"e": 872,
"s": 864,
"text": "Python3"
},
{
"code": "# importing numpyimport numpy as np array = np.random.rand(2, 2, 2, 2)print(array[..., 0])print(array[Ellipsis, 0])",
"e": 989,
"s": 872,
"text": null
},
{
"code": null,
"e": 997,
"s": 989,
"text": "Output:"
},
{
"code": null,
"e": 1214,
"s": 997,
"text": "[[[0.46253663 0.03092289]\n [0.72723607 0.75953107]]\n\n [[0.33160093 0.79259324]\n [0.76757812 0.21241883]]]\n[[[0.46253663 0.03092289]\n [0.72723607 0.75953107]]\n\n [[0.33160093 0.79259324]\n [0.76757812 0.21241883]]]\n"
},
{
"code": null,
"e": 1297,
"s": 1214,
"text": "In the above example, [:, :, :, 0], [..., 0] and [Ellipsis, 0] are all equivalent."
},
{
"code": null,
"e": 1373,
"s": 1297,
"text": "We can not have multiple ellipsis in a single slicing like a[...,index,...]"
},
{
"code": null,
"e": 1494,
"s": 1373,
"text": "Ellipsis is used in specifying type hints using the typing module (e.g. Callable[..., str]). It can serve in either way:"
},
{
"code": null,
"e": 1562,
"s": 1494,
"text": "Method 1: When the argument(s) of the function allows the type: Any"
},
{
"code": null,
"e": 1602,
"s": 1562,
"text": "Actually callable takes the arguments: "
},
{
"code": null,
"e": 1659,
"s": 1602,
"text": "Callable \"[\" parameters_expression, type_expression \"]\"\n"
},
{
"code": null,
"e": 1686,
"s": 1659,
"text": "(e.g. Callable[..., str]) "
},
{
"code": null,
"e": 1695,
"s": 1686,
"text": "Example:"
},
{
"code": null,
"e": 1703,
"s": 1695,
"text": "Python3"
},
{
"code": "from typing import Callable def inject(get_next_item: Callable[..., str]) -> None: ...# Argument type is assumed as type: Anydef foo(x: ...) -> None: ...",
"e": 1882,
"s": 1703,
"text": null
},
{
"code": null,
"e": 2001,
"s": 1882,
"text": "Using ‘...’ as parameters_expression signifies a function that returns a string without specifying the call signature."
},
{
"code": null,
"e": 2067,
"s": 2001,
"text": "Method 2: When the return value of the function is of type: Any "
},
{
"code": null,
"e": 2103,
"s": 2067,
"text": "Actually callable returns this way:"
},
{
"code": null,
"e": 2182,
"s": 2103,
"text": "Callable \"[\" parameters_expression, type_expression \"]\" -> return_type: #body\n"
},
{
"code": null,
"e": 2191,
"s": 2182,
"text": "Example:"
},
{
"code": null,
"e": 2199,
"s": 2191,
"text": "Python3"
},
{
"code": "class flow: # (using \"value: Any\" to allow arbitrary types) def __understand__(self, name: str, value: ...) -> None: ...",
"e": 2330,
"s": 2199,
"text": null
},
{
"code": null,
"e": 2435,
"s": 2333,
"text": "Ellipsis is used instead of pass statement inside functions. ‘pass’ replaced by ‘...’ or ‘Ellipsis’. "
},
{
"code": null,
"e": 2444,
"s": 2435,
"text": "Example:"
},
{
"code": null,
"e": 2452,
"s": 2444,
"text": "Python3"
},
{
"code": "# style1def foo(): pass# style2def foo(): ...# both the styles are same",
"e": 2530,
"s": 2452,
"text": null
},
{
"code": null,
"e": 2675,
"s": 2530,
"text": "Ellipsis can also be used as a default argument value. Especially when you want to distinguish between not passing in value and passing in None."
},
{
"code": null,
"e": 2685,
"s": 2675,
"text": "Example: "
},
{
"code": null,
"e": 2693,
"s": 2685,
"text": "Python3"
},
{
"code": "def foo(x = ...): return x print(foo)",
"e": 2735,
"s": 2693,
"text": null
},
{
"code": null,
"e": 2743,
"s": 2735,
"text": "Output:"
},
{
"code": null,
"e": 2777,
"s": 2743,
"text": "<function foo at 0x7fabdeea6e18>\n"
},
{
"code": null,
"e": 2784,
"s": 2777,
"text": "Python"
}
] |
How to select all links inside the paragraph using jQuery ?
|
06 Sep, 2021
In this article, we will see how to write code to select all links inside the paragraph using jQuery. To select all links inside paragraph element, we use parent descendant selector. This selector is used to selects every element that are descendant to a specific (parent) element.
Syntax:
$("parent descendant")
Approach: Here, we have created links and content inside paragraph element. After that, we use $(“p a”) selector to select all links inside paragraph element and changes its style using css() method.
Example:
HTML
<!DOCTYPE html><html> <head> <title> jQuery code to select all links inside the paragraph </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <style> body { text-align: center; font-size: 30px; } button { background-color: green; color: white; border: none; font-size: 24px; border-radius: 5px; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; } a { text-decoration: none; } </style> <script> $(document).ready(function() { $("button").click(function() { $("p a").css({ color: "white", background: "green" }); }); }); </script></head> <body> <h1 style="color:green"> GeeksforGeeks </h1> <h3> jQuery code to select all links inside the paragraph </h3> <p> <a href="#">GeeksforGeeks</a> is a computer science <br>portal where you can learn <a href="#">HTML</a>, <a href="#">CSS</a>, <br><a href="#"> JavaScript</a>, etc. </p> <button> Click Here </button></body> </html>
Output:
CSS-Properties
jQuery-Questions
jQuery-Selectors
Picked
CSS
HTML
JQuery
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
Design a web page using HTML and CSS
Form validation using jQuery
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": "\n06 Sep, 2021"
},
{
"code": null,
"e": 310,
"s": 28,
"text": "In this article, we will see how to write code to select all links inside the paragraph using jQuery. To select all links inside paragraph element, we use parent descendant selector. This selector is used to selects every element that are descendant to a specific (parent) element."
},
{
"code": null,
"e": 318,
"s": 310,
"text": "Syntax:"
},
{
"code": null,
"e": 341,
"s": 318,
"text": "$(\"parent descendant\")"
},
{
"code": null,
"e": 541,
"s": 341,
"text": "Approach: Here, we have created links and content inside paragraph element. After that, we use $(“p a”) selector to select all links inside paragraph element and changes its style using css() method."
},
{
"code": null,
"e": 552,
"s": 543,
"text": "Example:"
},
{
"code": null,
"e": 557,
"s": 552,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> jQuery code to select all links inside the paragraph </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <style> body { text-align: center; font-size: 30px; } button { background-color: green; color: white; border: none; font-size: 24px; border-radius: 5px; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; } a { text-decoration: none; } </style> <script> $(document).ready(function() { $(\"button\").click(function() { $(\"p a\").css({ color: \"white\", background: \"green\" }); }); }); </script></head> <body> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h3> jQuery code to select all links inside the paragraph </h3> <p> <a href=\"#\">GeeksforGeeks</a> is a computer science <br>portal where you can learn <a href=\"#\">HTML</a>, <a href=\"#\">CSS</a>, <br><a href=\"#\"> JavaScript</a>, etc. </p> <button> Click Here </button></body> </html>",
"e": 1952,
"s": 557,
"text": null
},
{
"code": null,
"e": 1960,
"s": 1952,
"text": "Output:"
},
{
"code": null,
"e": 1975,
"s": 1960,
"text": "CSS-Properties"
},
{
"code": null,
"e": 1992,
"s": 1975,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 2009,
"s": 1992,
"text": "jQuery-Selectors"
},
{
"code": null,
"e": 2016,
"s": 2009,
"text": "Picked"
},
{
"code": null,
"e": 2020,
"s": 2016,
"text": "CSS"
},
{
"code": null,
"e": 2025,
"s": 2020,
"text": "HTML"
},
{
"code": null,
"e": 2032,
"s": 2025,
"text": "JQuery"
},
{
"code": null,
"e": 2049,
"s": 2032,
"text": "Web Technologies"
},
{
"code": null,
"e": 2054,
"s": 2049,
"text": "HTML"
},
{
"code": null,
"e": 2152,
"s": 2054,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2191,
"s": 2152,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2230,
"s": 2191,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 2269,
"s": 2230,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 2306,
"s": 2269,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 2335,
"s": 2306,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2359,
"s": 2335,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2412,
"s": 2359,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2472,
"s": 2412,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 2533,
"s": 2472,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Intrusion Detection System Using Machine Learning Algorithms
|
14 Jan, 2022
Problem Statement: The task is to build a network intrusion detector, a predictive model capable of distinguishing between bad connections, called intrusions or attacks, and good normal connections.
Introduction:Intrusion Detection System is a software application to detect network intrusion using various machine learning algorithms.IDS monitors a network or system for malicious activity and protects a computer network from unauthorized access from users, including perhaps insider. The intrusion detector learning task is to build a predictive model (i.e. a classifier) capable of distinguishing between ‘bad connections’ (intrusion/attacks) and a ‘good (normal) connections’.
#DOS: denial-of-service, e.g. syn flood;
#R2L: unauthorized access from a remote machine, e.g. guessing password;
#U2R: unauthorized access to local superuser (root) privileges, e.g., various “buffer overflow” attacks;
#probing: surveillance and another probing, e.g., port scanning.
Dataset Used : KDD Cup 1999 dataset
Dataset Description: Data files:
kddcup.names : A list of features.
kddcup.data.gz : The full data set
kddcup.data_10_percent.gz : A 10% subset.
kddcup.newtestdata_10_percent_unlabeled.gz
kddcup.testdata.unlabeled.gz
kddcup.testdata.unlabeled_10_percent.gz
corrected.gz : Test data with corrected labels.
training_attack_types : A list of intrusion types.
typo-correction.txt : A brief note on a typo in the data set that has been corrected
Features:
Table 1: Basic features of individual TCP connections.
Table 2: Content features within a connection suggested by domain knowledge.
Table 3: Traffic features computed using a two-second time window.
Various Algorithms Applied: Gaussian Naive Bayes, Decision Tree, Random Forest, Support Vector Machine, Logistic Regression.
Approach Used: I have applied various classification algorithms that are mentioned above on the KDD dataset and compare there results to build a predictive model.
Step 1 – Data Preprocessing:Code: Importing libraries and reading features list from ‘kddcup.names’ file.
import osimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport time # reading features listwith open("..\\kddcup.names", 'r') as f: print(f.read())
Code: Appending columns to the dataset and adding a new column name ‘target’ to the dataset.
cols ="""duration,protocol_type,service,flag,src_bytes,dst_bytes,land,wrong_fragment,urgent,hot,num_failed_logins,logged_in,num_compromised,root_shell,su_attempted,num_root,num_file_creations,num_shells,num_access_files,num_outbound_cmds,is_host_login,is_guest_login,count,srv_count,serror_rate,srv_serror_rate,rerror_rate,srv_rerror_rate,same_srv_rate,diff_srv_rate,srv_diff_host_rate,dst_host_count,dst_host_srv_count,dst_host_same_srv_rate,dst_host_diff_srv_rate,dst_host_same_src_port_rate,dst_host_srv_diff_host_rate,dst_host_serror_rate,dst_host_srv_serror_rate,dst_host_rerror_rate,dst_host_srv_rerror_rate""" columns =[]for c in cols.split(', '): if(c.strip()): columns.append(c.strip()) columns.append('target')print(len(columns))
Output:
42
Code: Reading the ‘attack_types’ file.
with open("..\\training_attack_types", 'r') as f: print(f.read())
Output:
back dos
buffer_overflow u2r
ftp_write r2l
guess_passwd r2l
imap r2l
ipsweep probe
land dos
loadmodule u2r
multihop r2l
neptune dos
nmap probe
perl u2r
phf r2l
pod dos
portsweep probe
rootkit u2r
satan probe
smurf dos
spy r2l
teardrop dos
warezclient r2l
warezmaster r2l
Code: Creating a dictionary of attack_types
attacks_types = { 'normal': 'normal','back': 'dos','buffer_overflow': 'u2r','ftp_write': 'r2l','guess_passwd': 'r2l','imap': 'r2l','ipsweep': 'probe','land': 'dos','loadmodule': 'u2r','multihop': 'r2l','neptune': 'dos','nmap': 'probe','perl': 'u2r','phf': 'r2l','pod': 'dos','portsweep': 'probe','rootkit': 'u2r','satan': 'probe','smurf': 'dos','spy': 'r2l','teardrop': 'dos','warezclient': 'r2l','warezmaster': 'r2l',}
Code: Reading the dataset(‘kddcup.data_10_percent.gz’) and adding Attack Type feature in the training dataset where attack type feature has 5 distinct values i.e. dos, normal, probe, r2l, u2r.
path = "..\\kddcup.data_10_percent.gz"df = pd.read_csv(path, names = columns) # Adding Attack Type columndf['Attack Type'] = df.target.apply(lambda r:attacks_types[r[:-1]])df.head()
Code: Shape of dataframe and getting data type of each feature
df.shape
Output:
(494021, 43)
Code: Finding missing values of all features.
df.isnull().sum()
Output:
duration 0
protocol_type 0
service 0
flag 0
src_bytes 0
dst_bytes 0
land 0
wrong_fragment 0
urgent 0
hot 0
num_failed_logins 0
logged_in 0
num_compromised 0
root_shell 0
su_attempted 0
num_root 0
num_file_creations 0
num_shells 0
num_access_files 0
num_outbound_cmds 0
is_host_login 0
is_guest_login 0
count 0
srv_count 0
serror_rate 0
srv_serror_rate 0
rerror_rate 0
srv_rerror_rate 0
same_srv_rate 0
diff_srv_rate 0
srv_diff_host_rate 0
dst_host_count 0
dst_host_srv_count 0
dst_host_same_srv_rate 0
dst_host_diff_srv_rate 0
dst_host_same_src_port_rate 0
dst_host_srv_diff_host_rate 0
dst_host_serror_rate 0
dst_host_srv_serror_rate 0
dst_host_rerror_rate 0
dst_host_srv_rerror_rate 0
target 0
Attack Type 0
dtype: int64
No missing value found, so we can further proceed to our next step.
Code: Finding Categorical Features
# Finding categorical featuresnum_cols = df._get_numeric_data().columns cate_cols = list(set(df.columns)-set(num_cols))cate_cols.remove('target')cate_cols.remove('Attack Type') cate_cols
Output:
['service', 'flag', 'protocol_type']
Visualizing Categorical Features using bar graph
Protocol type: We notice that ICMP is the most present in the used data, then TCP and almost 20000 packets of UDP type
logged_in (1 if successfully logged in; 0 otherwise): We notice that just 70000 packets are successfully logged in.
Target Feature Distribution:
Attack Type(The attack types grouped by attack, it’s what we will predict)
Code: Data Correlation – Find the highly correlated variables using heatmap and ignore them for analysis.
df = df.dropna('columns')# drop columns with NaN df = df[[col for col in df if df[col].nunique() > 1]]# keep columns where there are more than 1 unique values corr = df.corr() plt.figure(figsize =(15, 12)) sns.heatmap(corr) plt.show()
Output:
Code:
# This variable is highly correlated with num_compromised and should be ignored for analysis.#(Correlation = 0.9938277978738366)df.drop('num_root', axis = 1, inplace = True) # This variable is highly correlated with serror_rate and should be ignored for analysis.#(Correlation = 0.9983615072725952)df.drop('srv_serror_rate', axis = 1, inplace = True) # This variable is highly correlated with rerror_rate and should be ignored for analysis.#(Correlation = 0.9947309539817937)df.drop('srv_rerror_rate', axis = 1, inplace = True) # This variable is highly correlated with srv_serror_rate and should be ignored for analysis.#(Correlation = 0.9993041091850098)df.drop('dst_host_srv_serror_rate', axis = 1, inplace = True) # This variable is highly correlated with rerror_rate and should be ignored for analysis.#(Correlation = 0.9869947924956001)df.drop('dst_host_serror_rate', axis = 1, inplace = True) # This variable is highly correlated with srv_rerror_rate and should be ignored for analysis.#(Correlation = 0.9821663427308375)df.drop('dst_host_rerror_rate', axis = 1, inplace = True) # This variable is highly correlated with rerror_rate and should be ignored for analysis.#(Correlation = 0.9851995540751249)df.drop('dst_host_srv_rerror_rate', axis = 1, inplace = True) # This variable is highly correlated with srv_rerror_rate and should be ignored for analysis.#(Correlation = 0.9865705438845669)df.drop('dst_host_same_srv_rate', axis = 1, inplace = True)
Output:
Code: Feature Mapping – Apply feature mapping on features such as : ‘protocol_type’ & ‘flag’.
# protocol_type feature mappingpmap = {'icmp':0, 'tcp':1, 'udp':2}df['protocol_type'] = df['protocol_type'].map(pmap)
Code:
# flag feature mappingfmap = {'SF':0, 'S0':1, 'REJ':2, 'RSTR':3, 'RSTO':4, 'SH':5, 'S1':6, 'S2':7, 'RSTOS0':8, 'S3':9, 'OTH':10}df['flag'] = df['flag'].map(fmap)
Output:
Code: Remove irrelevant features such as ‘service’ before modelling
df.drop('service', axis = 1, inplace = True)
Step 2 – Modelling
Code: Importing libraries and splitting the dataset
from sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import MinMaxScaler
Code:
# Splitting the datasetdf = df.drop(['target', ], axis = 1)print(df.shape) # Target variable and train sety = df[['Attack Type']]X = df.drop(['Attack Type', ], axis = 1) sc = MinMaxScaler()X = sc.fit_transform(X) # Split test and train data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state = 42)print(X_train.shape, X_test.shape)print(y_train.shape, y_test.shape)
Output:
(494021, 31)
(330994, 30) (163027, 30)
(330994, 1) (163027, 1)
Apply various machine learning classification algorithms such as Support Vector Machines, Random Forest, Naive Bayes, Decision Tree, Logistic Regression to create different models.
Code: Python implementation of Gaussian Naive Bayes
# Gaussian Naive Bayesfrom sklearn.naive_bayes import GaussianNBfrom sklearn.metrics import accuracy_score clfg = GaussianNB()start_time = time.time()clfg.fit(X_train, y_train.values.ravel())end_time = time.time()print("Training time: ", end_time-start_time)
Output:
Training time: 1.1145250797271729
Code:
start_time = time.time()y_test_pred = clfg.predict(X_train)end_time = time.time()print("Testing time: ", end_time-start_time)
Output:
Testing time: 1.543299674987793
Code:
print("Train score is:", clfg.score(X_train, y_train))print("Test score is:", clfg.score(X_test, y_test))
Output:
Train score is: 0.8795114110829804
Test score is: 0.8790384414851528
Code: Python implementation of Decision Tree
# Decision Tree from sklearn.tree import DecisionTreeClassifier clfd = DecisionTreeClassifier(criterion ="entropy", max_depth = 4)start_time = time.time()clfd.fit(X_train, y_train.values.ravel())end_time = time.time()print("Training time: ", end_time-start_time)
Output:
Training time: 2.4408750534057617
start_time = time.time()y_test_pred = clfd.predict(X_train)end_time = time.time()print("Testing time: ", end_time-start_time)
Output:
Testing time: 0.1487727165222168
print("Train score is:", clfd.score(X_train, y_train))print("Test score is:", clfd.score(X_test, y_test))
Output:
Train score is: 0.9905829108684749
Test score is: 0.9905230421954646
Code: Python code implementation of Random Forest
from sklearn.ensemble import RandomForestClassifier clfr = RandomForestClassifier(n_estimators = 30)start_time = time.time()clfr.fit(X_train, y_train.values.ravel())end_time = time.time()print("Training time: ", end_time-start_time)
Output:
Training time: 17.084914684295654
start_time = time.time()y_test_pred = clfr.predict(X_train)end_time = time.time()print("Testing time: ", end_time-start_time)
Output:
Testing time: 0.1487727165222168
print("Train score is:", clfr.score(X_train, y_train))print("Test score is:", clfr.score(X_test, y_test))
Output:
Train score is: 0.99997583037759
Test score is: 0.9996933023364228
Code: Python implementation of Support Vector Classifier
from sklearn.svm import SVC clfs = SVC(gamma = 'scale')start_time = time.time()clfs.fit(X_train, y_train.values.ravel())end_time = time.time()print("Training time: ", end_time-start_time)
Output:
Training time: 218.26840996742249
Code:
start_time = time.time()y_test_pred = clfs.predict(X_train)end_time = time.time()print("Testing time: ", end_time-start_time)
Output:
Testing time: 126.5087513923645
Code:
print("Train score is:", clfs.score(X_train, y_train))print("Test score is:", clfs.score(X_test, y_test))
Output:
Train score is: 0.9987552644458811
Test score is: 0.9987916112055059
Code: Python implementation of Logistic Regression
from sklearn.linear_model import LogisticRegression clfl = LogisticRegression(max_iter = 1200000)start_time = time.time()clfl.fit(X_train, y_train.values.ravel())end_time = time.time()print("Training time: ", end_time-start_time)
Output:
Training time: 92.94222283363342
Code:
start_time = time.time()y_test_pred = clfl.predict(X_train)end_time = time.time()print("Testing time: ", end_time-start_time)
Output:
Testing time: 0.09605908393859863
Code:
print("Train score is:", clfl.score(X_train, y_train))print("Test score is:", clfl.score(X_test, y_test))
Output:
Train score is: 0.9935285835997028
Test score is: 0.9935286792985211
Code: Python implementation of Gradient Descent
from sklearn.ensemble import GradientBoostingClassifier clfg = GradientBoostingClassifier(random_state = 0)start_time = time.time()clfg.fit(X_train, y_train.values.ravel())end_time = time.time()print("Training time: ", end_time-start_time)
Output:
Training time: 633.2290260791779
start_time = time.time()y_test_pred = clfg.predict(X_train)end_time = time.time()print("Testing time: ", end_time-start_time)
Output:
Testing time: 2.9503915309906006
print("Train score is:", clfg.score(X_train, y_train))print("Test score is:", clfg.score(X_test, y_test))
Output:
Train score is: 0.9979304760811374
Test score is: 0.9977181693829856
Code: Analyse the training and testing accuracy of each model.
names = ['NB', 'DT', 'RF', 'SVM', 'LR', 'GB']values = [87.951, 99.058, 99.997, 99.875, 99.352, 99.793]f = plt.figure(figsize =(15, 3), num = 10)plt.subplot(131)plt.bar(names, values)
Output:
Code:
names = ['NB', 'DT', 'RF', 'SVM', 'LR', 'GB']values = [87.903, 99.052, 99.969, 99.879, 99.352, 99.771]f = plt.figure(figsize =(15, 3), num = 10)plt.subplot(131)plt.bar(names, values)
Output:
Code: Analyse the training and testing time of each model.
names = ['NB', 'DT', 'RF', 'SVM', 'LR', 'GB']values = [1.11452, 2.44087, 17.08491, 218.26840, 92.94222, 633.229]f = plt.figure(figsize =(15, 3), num = 10)plt.subplot(131)plt.bar(names, values)
Output:
Code:
names = ['NB', 'DT', 'RF', 'SVM', 'LR', 'GB']values = [1.54329, 0.14877, 0.199471, 126.50875, 0.09605, 2.95039]f = plt.figure(figsize =(15, 3), num = 10)plt.subplot(131)plt.bar(names, values)
Output:
Implementation Link: https://github.com/mudgalabhay/intrusion-detection-system/blob/master/main.ipynb
Conclusion: The above analysis of different models states that the Decision Tree model best fits our data considering both accuracy and time complexity.
Links: The complete code is uploaded on my github account – https://github.com/mudgalabhay/intrusion-detection-system
simmytarika5
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
ML | Monte Carlo Tree Search (MCTS)
Support Vector Machine Algorithm
Markov Decision Process
DBSCAN Clustering in ML | Density based clustering
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": 54,
"s": 26,
"text": "\n14 Jan, 2022"
},
{
"code": null,
"e": 253,
"s": 54,
"text": "Problem Statement: The task is to build a network intrusion detector, a predictive model capable of distinguishing between bad connections, called intrusions or attacks, and good normal connections."
},
{
"code": null,
"e": 736,
"s": 253,
"text": "Introduction:Intrusion Detection System is a software application to detect network intrusion using various machine learning algorithms.IDS monitors a network or system for malicious activity and protects a computer network from unauthorized access from users, including perhaps insider. The intrusion detector learning task is to build a predictive model (i.e. a classifier) capable of distinguishing between ‘bad connections’ (intrusion/attacks) and a ‘good (normal) connections’."
},
{
"code": null,
"e": 777,
"s": 736,
"text": "#DOS: denial-of-service, e.g. syn flood;"
},
{
"code": null,
"e": 850,
"s": 777,
"text": "#R2L: unauthorized access from a remote machine, e.g. guessing password;"
},
{
"code": null,
"e": 955,
"s": 850,
"text": "#U2R: unauthorized access to local superuser (root) privileges, e.g., various “buffer overflow” attacks;"
},
{
"code": null,
"e": 1020,
"s": 955,
"text": "#probing: surveillance and another probing, e.g., port scanning."
},
{
"code": null,
"e": 1056,
"s": 1020,
"text": "Dataset Used : KDD Cup 1999 dataset"
},
{
"code": null,
"e": 1089,
"s": 1056,
"text": "Dataset Description: Data files:"
},
{
"code": null,
"e": 1124,
"s": 1089,
"text": "kddcup.names : A list of features."
},
{
"code": null,
"e": 1159,
"s": 1124,
"text": "kddcup.data.gz : The full data set"
},
{
"code": null,
"e": 1201,
"s": 1159,
"text": "kddcup.data_10_percent.gz : A 10% subset."
},
{
"code": null,
"e": 1244,
"s": 1201,
"text": "kddcup.newtestdata_10_percent_unlabeled.gz"
},
{
"code": null,
"e": 1273,
"s": 1244,
"text": "kddcup.testdata.unlabeled.gz"
},
{
"code": null,
"e": 1313,
"s": 1273,
"text": "kddcup.testdata.unlabeled_10_percent.gz"
},
{
"code": null,
"e": 1361,
"s": 1313,
"text": "corrected.gz : Test data with corrected labels."
},
{
"code": null,
"e": 1412,
"s": 1361,
"text": "training_attack_types : A list of intrusion types."
},
{
"code": null,
"e": 1497,
"s": 1412,
"text": "typo-correction.txt : A brief note on a typo in the data set that has been corrected"
},
{
"code": null,
"e": 1507,
"s": 1497,
"text": "Features:"
},
{
"code": null,
"e": 1562,
"s": 1507,
"text": "Table 1: Basic features of individual TCP connections."
},
{
"code": null,
"e": 1639,
"s": 1562,
"text": "Table 2: Content features within a connection suggested by domain knowledge."
},
{
"code": null,
"e": 1706,
"s": 1639,
"text": "Table 3: Traffic features computed using a two-second time window."
},
{
"code": null,
"e": 1831,
"s": 1706,
"text": "Various Algorithms Applied: Gaussian Naive Bayes, Decision Tree, Random Forest, Support Vector Machine, Logistic Regression."
},
{
"code": null,
"e": 1994,
"s": 1831,
"text": "Approach Used: I have applied various classification algorithms that are mentioned above on the KDD dataset and compare there results to build a predictive model."
},
{
"code": null,
"e": 2100,
"s": 1994,
"text": "Step 1 – Data Preprocessing:Code: Importing libraries and reading features list from ‘kddcup.names’ file."
},
{
"code": "import osimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport time # reading features listwith open(\"..\\\\kddcup.names\", 'r') as f: print(f.read())",
"e": 2294,
"s": 2100,
"text": null
},
{
"code": null,
"e": 2387,
"s": 2294,
"text": "Code: Appending columns to the dataset and adding a new column name ‘target’ to the dataset."
},
{
"code": " cols =\"\"\"duration,protocol_type,service,flag,src_bytes,dst_bytes,land,wrong_fragment,urgent,hot,num_failed_logins,logged_in,num_compromised,root_shell,su_attempted,num_root,num_file_creations,num_shells,num_access_files,num_outbound_cmds,is_host_login,is_guest_login,count,srv_count,serror_rate,srv_serror_rate,rerror_rate,srv_rerror_rate,same_srv_rate,diff_srv_rate,srv_diff_host_rate,dst_host_count,dst_host_srv_count,dst_host_same_srv_rate,dst_host_diff_srv_rate,dst_host_same_src_port_rate,dst_host_srv_diff_host_rate,dst_host_serror_rate,dst_host_srv_serror_rate,dst_host_rerror_rate,dst_host_srv_rerror_rate\"\"\" columns =[]for c in cols.split(', '): if(c.strip()): columns.append(c.strip()) columns.append('target')print(len(columns))",
"e": 3139,
"s": 2387,
"text": null
},
{
"code": null,
"e": 3147,
"s": 3139,
"text": "Output:"
},
{
"code": null,
"e": 3150,
"s": 3147,
"text": "42"
},
{
"code": null,
"e": 3189,
"s": 3150,
"text": "Code: Reading the ‘attack_types’ file."
},
{
"code": " with open(\"..\\\\training_attack_types\", 'r') as f: print(f.read())",
"e": 3259,
"s": 3189,
"text": null
},
{
"code": null,
"e": 3267,
"s": 3259,
"text": "Output:"
},
{
"code": null,
"e": 3538,
"s": 3267,
"text": "back dos\nbuffer_overflow u2r\nftp_write r2l\nguess_passwd r2l\nimap r2l\nipsweep probe\nland dos\nloadmodule u2r\nmultihop r2l\nneptune dos\nnmap probe\nperl u2r\nphf r2l\npod dos\nportsweep probe\nrootkit u2r\nsatan probe\nsmurf dos\nspy r2l\nteardrop dos\nwarezclient r2l\nwarezmaster r2l"
},
{
"code": null,
"e": 3582,
"s": 3538,
"text": "Code: Creating a dictionary of attack_types"
},
{
"code": " attacks_types = { 'normal': 'normal','back': 'dos','buffer_overflow': 'u2r','ftp_write': 'r2l','guess_passwd': 'r2l','imap': 'r2l','ipsweep': 'probe','land': 'dos','loadmodule': 'u2r','multihop': 'r2l','neptune': 'dos','nmap': 'probe','perl': 'u2r','phf': 'r2l','pod': 'dos','portsweep': 'probe','rootkit': 'u2r','satan': 'probe','smurf': 'dos','spy': 'r2l','teardrop': 'dos','warezclient': 'r2l','warezmaster': 'r2l',}",
"e": 4007,
"s": 3582,
"text": null
},
{
"code": null,
"e": 4200,
"s": 4007,
"text": "Code: Reading the dataset(‘kddcup.data_10_percent.gz’) and adding Attack Type feature in the training dataset where attack type feature has 5 distinct values i.e. dos, normal, probe, r2l, u2r."
},
{
"code": "path = \"..\\\\kddcup.data_10_percent.gz\"df = pd.read_csv(path, names = columns) # Adding Attack Type columndf['Attack Type'] = df.target.apply(lambda r:attacks_types[r[:-1]])df.head() ",
"e": 4384,
"s": 4200,
"text": null
},
{
"code": null,
"e": 4447,
"s": 4384,
"text": "Code: Shape of dataframe and getting data type of each feature"
},
{
"code": " df.shape",
"e": 4457,
"s": 4447,
"text": null
},
{
"code": null,
"e": 4465,
"s": 4457,
"text": "Output:"
},
{
"code": null,
"e": 4479,
"s": 4465,
"text": " (494021, 43)"
},
{
"code": null,
"e": 4525,
"s": 4479,
"text": "Code: Finding missing values of all features."
},
{
"code": "df.isnull().sum()",
"e": 4543,
"s": 4525,
"text": null
},
{
"code": null,
"e": 4551,
"s": 4543,
"text": "Output:"
},
{
"code": null,
"e": 5983,
"s": 4551,
"text": "duration 0\nprotocol_type 0\nservice 0\nflag 0\nsrc_bytes 0\ndst_bytes 0\nland 0\nwrong_fragment 0\nurgent 0\nhot 0\nnum_failed_logins 0\nlogged_in 0\nnum_compromised 0\nroot_shell 0\nsu_attempted 0\nnum_root 0\nnum_file_creations 0\nnum_shells 0\nnum_access_files 0\nnum_outbound_cmds 0\nis_host_login 0\nis_guest_login 0\ncount 0\nsrv_count 0\nserror_rate 0\nsrv_serror_rate 0\nrerror_rate 0\nsrv_rerror_rate 0\nsame_srv_rate 0\ndiff_srv_rate 0\nsrv_diff_host_rate 0\ndst_host_count 0\ndst_host_srv_count 0\ndst_host_same_srv_rate 0\ndst_host_diff_srv_rate 0\ndst_host_same_src_port_rate 0\ndst_host_srv_diff_host_rate 0\ndst_host_serror_rate 0\ndst_host_srv_serror_rate 0\ndst_host_rerror_rate 0\ndst_host_srv_rerror_rate 0\ntarget 0\nAttack Type 0\ndtype: int64"
},
{
"code": null,
"e": 6051,
"s": 5983,
"text": "No missing value found, so we can further proceed to our next step."
},
{
"code": null,
"e": 6086,
"s": 6051,
"text": "Code: Finding Categorical Features"
},
{
"code": "# Finding categorical featuresnum_cols = df._get_numeric_data().columns cate_cols = list(set(df.columns)-set(num_cols))cate_cols.remove('target')cate_cols.remove('Attack Type') cate_cols ",
"e": 6276,
"s": 6086,
"text": null
},
{
"code": null,
"e": 6284,
"s": 6276,
"text": "Output:"
},
{
"code": null,
"e": 6322,
"s": 6284,
"text": " ['service', 'flag', 'protocol_type']"
},
{
"code": null,
"e": 6371,
"s": 6322,
"text": "Visualizing Categorical Features using bar graph"
},
{
"code": null,
"e": 6490,
"s": 6371,
"text": "Protocol type: We notice that ICMP is the most present in the used data, then TCP and almost 20000 packets of UDP type"
},
{
"code": null,
"e": 6606,
"s": 6490,
"text": "logged_in (1 if successfully logged in; 0 otherwise): We notice that just 70000 packets are successfully logged in."
},
{
"code": null,
"e": 6635,
"s": 6606,
"text": "Target Feature Distribution:"
},
{
"code": null,
"e": 6710,
"s": 6635,
"text": "Attack Type(The attack types grouped by attack, it’s what we will predict)"
},
{
"code": null,
"e": 6816,
"s": 6710,
"text": "Code: Data Correlation – Find the highly correlated variables using heatmap and ignore them for analysis."
},
{
"code": " df = df.dropna('columns')# drop columns with NaN df = df[[col for col in df if df[col].nunique() > 1]]# keep columns where there are more than 1 unique values corr = df.corr() plt.figure(figsize =(15, 12)) sns.heatmap(corr) plt.show() ",
"e": 7060,
"s": 6816,
"text": null
},
{
"code": null,
"e": 7068,
"s": 7060,
"text": "Output:"
},
{
"code": null,
"e": 7074,
"s": 7068,
"text": "Code:"
},
{
"code": " # This variable is highly correlated with num_compromised and should be ignored for analysis.#(Correlation = 0.9938277978738366)df.drop('num_root', axis = 1, inplace = True) # This variable is highly correlated with serror_rate and should be ignored for analysis.#(Correlation = 0.9983615072725952)df.drop('srv_serror_rate', axis = 1, inplace = True) # This variable is highly correlated with rerror_rate and should be ignored for analysis.#(Correlation = 0.9947309539817937)df.drop('srv_rerror_rate', axis = 1, inplace = True) # This variable is highly correlated with srv_serror_rate and should be ignored for analysis.#(Correlation = 0.9993041091850098)df.drop('dst_host_srv_serror_rate', axis = 1, inplace = True) # This variable is highly correlated with rerror_rate and should be ignored for analysis.#(Correlation = 0.9869947924956001)df.drop('dst_host_serror_rate', axis = 1, inplace = True) # This variable is highly correlated with srv_rerror_rate and should be ignored for analysis.#(Correlation = 0.9821663427308375)df.drop('dst_host_rerror_rate', axis = 1, inplace = True) # This variable is highly correlated with rerror_rate and should be ignored for analysis.#(Correlation = 0.9851995540751249)df.drop('dst_host_srv_rerror_rate', axis = 1, inplace = True) # This variable is highly correlated with srv_rerror_rate and should be ignored for analysis.#(Correlation = 0.9865705438845669)df.drop('dst_host_same_srv_rate', axis = 1, inplace = True) ",
"e": 8545,
"s": 7074,
"text": null
},
{
"code": null,
"e": 8553,
"s": 8545,
"text": "Output:"
},
{
"code": null,
"e": 8647,
"s": 8553,
"text": "Code: Feature Mapping – Apply feature mapping on features such as : ‘protocol_type’ & ‘flag’."
},
{
"code": " # protocol_type feature mappingpmap = {'icmp':0, 'tcp':1, 'udp':2}df['protocol_type'] = df['protocol_type'].map(pmap)",
"e": 8766,
"s": 8647,
"text": null
},
{
"code": null,
"e": 8772,
"s": 8766,
"text": "Code:"
},
{
"code": " # flag feature mappingfmap = {'SF':0, 'S0':1, 'REJ':2, 'RSTR':3, 'RSTO':4, 'SH':5, 'S1':6, 'S2':7, 'RSTOS0':8, 'S3':9, 'OTH':10}df['flag'] = df['flag'].map(fmap) ",
"e": 8936,
"s": 8772,
"text": null
},
{
"code": null,
"e": 8944,
"s": 8936,
"text": "Output:"
},
{
"code": null,
"e": 9012,
"s": 8944,
"text": "Code: Remove irrelevant features such as ‘service’ before modelling"
},
{
"code": " df.drop('service', axis = 1, inplace = True)",
"e": 9058,
"s": 9012,
"text": null
},
{
"code": null,
"e": 9077,
"s": 9058,
"text": "Step 2 – Modelling"
},
{
"code": null,
"e": 9129,
"s": 9077,
"text": "Code: Importing libraries and splitting the dataset"
},
{
"code": " from sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import MinMaxScaler ",
"e": 9230,
"s": 9129,
"text": null
},
{
"code": null,
"e": 9236,
"s": 9230,
"text": "Code:"
},
{
"code": " # Splitting the datasetdf = df.drop(['target', ], axis = 1)print(df.shape) # Target variable and train sety = df[['Attack Type']]X = df.drop(['Attack Type', ], axis = 1) sc = MinMaxScaler()X = sc.fit_transform(X) # Split test and train data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state = 42)print(X_train.shape, X_test.shape)print(y_train.shape, y_test.shape) ",
"e": 9645,
"s": 9236,
"text": null
},
{
"code": null,
"e": 9653,
"s": 9645,
"text": "Output:"
},
{
"code": null,
"e": 9716,
"s": 9653,
"text": "(494021, 31)\n(330994, 30) (163027, 30)\n(330994, 1) (163027, 1)"
},
{
"code": null,
"e": 9897,
"s": 9716,
"text": "Apply various machine learning classification algorithms such as Support Vector Machines, Random Forest, Naive Bayes, Decision Tree, Logistic Regression to create different models."
},
{
"code": null,
"e": 9949,
"s": 9897,
"text": "Code: Python implementation of Gaussian Naive Bayes"
},
{
"code": " # Gaussian Naive Bayesfrom sklearn.naive_bayes import GaussianNBfrom sklearn.metrics import accuracy_score clfg = GaussianNB()start_time = time.time()clfg.fit(X_train, y_train.values.ravel())end_time = time.time()print(\"Training time: \", end_time-start_time) ",
"e": 10211,
"s": 9949,
"text": null
},
{
"code": null,
"e": 10219,
"s": 10211,
"text": "Output:"
},
{
"code": null,
"e": 10254,
"s": 10219,
"text": "Training time: 1.1145250797271729"
},
{
"code": null,
"e": 10260,
"s": 10254,
"text": "Code:"
},
{
"code": " start_time = time.time()y_test_pred = clfg.predict(X_train)end_time = time.time()print(\"Testing time: \", end_time-start_time) ",
"e": 10388,
"s": 10260,
"text": null
},
{
"code": null,
"e": 10396,
"s": 10388,
"text": "Output:"
},
{
"code": null,
"e": 10429,
"s": 10396,
"text": "Testing time: 1.543299674987793"
},
{
"code": null,
"e": 10435,
"s": 10429,
"text": "Code:"
},
{
"code": " print(\"Train score is:\", clfg.score(X_train, y_train))print(\"Test score is:\", clfg.score(X_test, y_test)) ",
"e": 10543,
"s": 10435,
"text": null
},
{
"code": null,
"e": 10551,
"s": 10543,
"text": "Output:"
},
{
"code": null,
"e": 10620,
"s": 10551,
"text": "Train score is: 0.8795114110829804\nTest score is: 0.8790384414851528"
},
{
"code": null,
"e": 10665,
"s": 10620,
"text": "Code: Python implementation of Decision Tree"
},
{
"code": " # Decision Tree from sklearn.tree import DecisionTreeClassifier clfd = DecisionTreeClassifier(criterion =\"entropy\", max_depth = 4)start_time = time.time()clfd.fit(X_train, y_train.values.ravel())end_time = time.time()print(\"Training time: \", end_time-start_time) ",
"e": 10931,
"s": 10665,
"text": null
},
{
"code": null,
"e": 10939,
"s": 10931,
"text": "Output:"
},
{
"code": null,
"e": 10975,
"s": 10939,
"text": " Training time: 2.4408750534057617"
},
{
"code": " start_time = time.time()y_test_pred = clfd.predict(X_train)end_time = time.time()print(\"Testing time: \", end_time-start_time) ",
"e": 11103,
"s": 10975,
"text": null
},
{
"code": null,
"e": 11111,
"s": 11103,
"text": "Output:"
},
{
"code": null,
"e": 11145,
"s": 11111,
"text": "Testing time: 0.1487727165222168"
},
{
"code": " print(\"Train score is:\", clfd.score(X_train, y_train))print(\"Test score is:\", clfd.score(X_test, y_test)) ",
"e": 11253,
"s": 11145,
"text": null
},
{
"code": null,
"e": 11261,
"s": 11253,
"text": "Output:"
},
{
"code": null,
"e": 11330,
"s": 11261,
"text": "Train score is: 0.9905829108684749\nTest score is: 0.9905230421954646"
},
{
"code": null,
"e": 11380,
"s": 11330,
"text": "Code: Python code implementation of Random Forest"
},
{
"code": " from sklearn.ensemble import RandomForestClassifier clfr = RandomForestClassifier(n_estimators = 30)start_time = time.time()clfr.fit(X_train, y_train.values.ravel())end_time = time.time()print(\"Training time: \", end_time-start_time) ",
"e": 11616,
"s": 11380,
"text": null
},
{
"code": null,
"e": 11624,
"s": 11616,
"text": "Output:"
},
{
"code": null,
"e": 11660,
"s": 11624,
"text": " Training time: 17.084914684295654"
},
{
"code": " start_time = time.time()y_test_pred = clfr.predict(X_train)end_time = time.time()print(\"Testing time: \", end_time-start_time) ",
"e": 11788,
"s": 11660,
"text": null
},
{
"code": null,
"e": 11796,
"s": 11788,
"text": "Output:"
},
{
"code": null,
"e": 11830,
"s": 11796,
"text": "Testing time: 0.1487727165222168"
},
{
"code": " print(\"Train score is:\", clfr.score(X_train, y_train))print(\"Test score is:\", clfr.score(X_test, y_test)) ",
"e": 11938,
"s": 11830,
"text": null
},
{
"code": null,
"e": 11946,
"s": 11938,
"text": "Output:"
},
{
"code": null,
"e": 12013,
"s": 11946,
"text": "Train score is: 0.99997583037759\nTest score is: 0.9996933023364228"
},
{
"code": null,
"e": 12070,
"s": 12013,
"text": "Code: Python implementation of Support Vector Classifier"
},
{
"code": " from sklearn.svm import SVC clfs = SVC(gamma = 'scale')start_time = time.time()clfs.fit(X_train, y_train.values.ravel())end_time = time.time()print(\"Training time: \", end_time-start_time) ",
"e": 12261,
"s": 12070,
"text": null
},
{
"code": null,
"e": 12269,
"s": 12261,
"text": "Output:"
},
{
"code": null,
"e": 12304,
"s": 12269,
"text": "Training time: 218.26840996742249"
},
{
"code": null,
"e": 12310,
"s": 12304,
"text": "Code:"
},
{
"code": " start_time = time.time()y_test_pred = clfs.predict(X_train)end_time = time.time()print(\"Testing time: \", end_time-start_time) ",
"e": 12438,
"s": 12310,
"text": null
},
{
"code": null,
"e": 12446,
"s": 12438,
"text": "Output:"
},
{
"code": null,
"e": 12479,
"s": 12446,
"text": "Testing time: 126.5087513923645"
},
{
"code": null,
"e": 12485,
"s": 12479,
"text": "Code:"
},
{
"code": " print(\"Train score is:\", clfs.score(X_train, y_train))print(\"Test score is:\", clfs.score(X_test, y_test)) ",
"e": 12593,
"s": 12485,
"text": null
},
{
"code": null,
"e": 12601,
"s": 12593,
"text": "Output:"
},
{
"code": null,
"e": 12670,
"s": 12601,
"text": "Train score is: 0.9987552644458811\nTest score is: 0.9987916112055059"
},
{
"code": null,
"e": 12721,
"s": 12670,
"text": "Code: Python implementation of Logistic Regression"
},
{
"code": " from sklearn.linear_model import LogisticRegression clfl = LogisticRegression(max_iter = 1200000)start_time = time.time()clfl.fit(X_train, y_train.values.ravel())end_time = time.time()print(\"Training time: \", end_time-start_time) ",
"e": 12954,
"s": 12721,
"text": null
},
{
"code": null,
"e": 12962,
"s": 12954,
"text": "Output:"
},
{
"code": null,
"e": 12996,
"s": 12962,
"text": "Training time: 92.94222283363342"
},
{
"code": null,
"e": 13002,
"s": 12996,
"text": "Code:"
},
{
"code": " start_time = time.time()y_test_pred = clfl.predict(X_train)end_time = time.time()print(\"Testing time: \", end_time-start_time) ",
"e": 13130,
"s": 13002,
"text": null
},
{
"code": null,
"e": 13138,
"s": 13130,
"text": "Output:"
},
{
"code": null,
"e": 13173,
"s": 13138,
"text": "Testing time: 0.09605908393859863"
},
{
"code": null,
"e": 13179,
"s": 13173,
"text": "Code:"
},
{
"code": " print(\"Train score is:\", clfl.score(X_train, y_train))print(\"Test score is:\", clfl.score(X_test, y_test)) ",
"e": 13287,
"s": 13179,
"text": null
},
{
"code": null,
"e": 13295,
"s": 13287,
"text": "Output:"
},
{
"code": null,
"e": 13364,
"s": 13295,
"text": "Train score is: 0.9935285835997028\nTest score is: 0.9935286792985211"
},
{
"code": null,
"e": 13412,
"s": 13364,
"text": "Code: Python implementation of Gradient Descent"
},
{
"code": " from sklearn.ensemble import GradientBoostingClassifier clfg = GradientBoostingClassifier(random_state = 0)start_time = time.time()clfg.fit(X_train, y_train.values.ravel())end_time = time.time()print(\"Training time: \", end_time-start_time) ",
"e": 13655,
"s": 13412,
"text": null
},
{
"code": null,
"e": 13663,
"s": 13655,
"text": "Output:"
},
{
"code": null,
"e": 13697,
"s": 13663,
"text": "Training time: 633.2290260791779"
},
{
"code": " start_time = time.time()y_test_pred = clfg.predict(X_train)end_time = time.time()print(\"Testing time: \", end_time-start_time) ",
"e": 13825,
"s": 13697,
"text": null
},
{
"code": null,
"e": 13833,
"s": 13825,
"text": "Output:"
},
{
"code": null,
"e": 13867,
"s": 13833,
"text": "Testing time: 2.9503915309906006"
},
{
"code": " print(\"Train score is:\", clfg.score(X_train, y_train))print(\"Test score is:\", clfg.score(X_test, y_test)) ",
"e": 13975,
"s": 13867,
"text": null
},
{
"code": null,
"e": 13983,
"s": 13975,
"text": "Output:"
},
{
"code": null,
"e": 14052,
"s": 13983,
"text": "Train score is: 0.9979304760811374\nTest score is: 0.9977181693829856"
},
{
"code": null,
"e": 14115,
"s": 14052,
"text": "Code: Analyse the training and testing accuracy of each model."
},
{
"code": " names = ['NB', 'DT', 'RF', 'SVM', 'LR', 'GB']values = [87.951, 99.058, 99.997, 99.875, 99.352, 99.793]f = plt.figure(figsize =(15, 3), num = 10)plt.subplot(131)plt.bar(names, values)",
"e": 14299,
"s": 14115,
"text": null
},
{
"code": null,
"e": 14307,
"s": 14299,
"text": "Output:"
},
{
"code": null,
"e": 14313,
"s": 14307,
"text": "Code:"
},
{
"code": " names = ['NB', 'DT', 'RF', 'SVM', 'LR', 'GB']values = [87.903, 99.052, 99.969, 99.879, 99.352, 99.771]f = plt.figure(figsize =(15, 3), num = 10)plt.subplot(131)plt.bar(names, values) ",
"e": 14498,
"s": 14313,
"text": null
},
{
"code": null,
"e": 14506,
"s": 14498,
"text": "Output:"
},
{
"code": null,
"e": 14565,
"s": 14506,
"text": "Code: Analyse the training and testing time of each model."
},
{
"code": " names = ['NB', 'DT', 'RF', 'SVM', 'LR', 'GB']values = [1.11452, 2.44087, 17.08491, 218.26840, 92.94222, 633.229]f = plt.figure(figsize =(15, 3), num = 10)plt.subplot(131)plt.bar(names, values) ",
"e": 14760,
"s": 14565,
"text": null
},
{
"code": null,
"e": 14768,
"s": 14760,
"text": "Output:"
},
{
"code": null,
"e": 14774,
"s": 14768,
"text": "Code:"
},
{
"code": " names = ['NB', 'DT', 'RF', 'SVM', 'LR', 'GB']values = [1.54329, 0.14877, 0.199471, 126.50875, 0.09605, 2.95039]f = plt.figure(figsize =(15, 3), num = 10)plt.subplot(131)plt.bar(names, values) ",
"e": 14968,
"s": 14774,
"text": null
},
{
"code": null,
"e": 14976,
"s": 14968,
"text": "Output:"
},
{
"code": null,
"e": 15078,
"s": 14976,
"text": "Implementation Link: https://github.com/mudgalabhay/intrusion-detection-system/blob/master/main.ipynb"
},
{
"code": null,
"e": 15231,
"s": 15078,
"text": "Conclusion: The above analysis of different models states that the Decision Tree model best fits our data considering both accuracy and time complexity."
},
{
"code": null,
"e": 15349,
"s": 15231,
"text": "Links: The complete code is uploaded on my github account – https://github.com/mudgalabhay/intrusion-detection-system"
},
{
"code": null,
"e": 15362,
"s": 15349,
"text": "simmytarika5"
},
{
"code": null,
"e": 15379,
"s": 15362,
"text": "Machine Learning"
},
{
"code": null,
"e": 15386,
"s": 15379,
"text": "Python"
},
{
"code": null,
"e": 15403,
"s": 15386,
"text": "Machine Learning"
},
{
"code": null,
"e": 15501,
"s": 15403,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15542,
"s": 15501,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 15578,
"s": 15542,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 15611,
"s": 15578,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 15635,
"s": 15611,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 15686,
"s": 15635,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 15714,
"s": 15686,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 15764,
"s": 15714,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 15786,
"s": 15764,
"text": "Python map() function"
}
] |
How to convert an array into JavaScript string?
|
To convert an array into JavaScript string, use the toString() method. JavaScript array toString() method returns a string representing the source code of the specified array and its elements.
You can try to run the following code to convert an array into a string −
Live Demo
<html>
<head>
<title>JavaScript Array toString Method</title>
</head>
<body>
<script>
var arr = new Array("time", "money", "work");
var str = arr.toString();
document.write("Returned string is : " + str );
</script>
</body>
</html>
Returned string is : time,money,work
|
[
{
"code": null,
"e": 1255,
"s": 1062,
"text": "To convert an array into JavaScript string, use the toString() method. JavaScript array toString() method returns a string representing the source code of the specified array and its elements."
},
{
"code": null,
"e": 1329,
"s": 1255,
"text": "You can try to run the following code to convert an array into a string −"
},
{
"code": null,
"e": 1339,
"s": 1329,
"text": "Live Demo"
},
{
"code": null,
"e": 1628,
"s": 1339,
"text": "<html>\n <head>\n <title>JavaScript Array toString Method</title>\n </head>\n <body>\n <script>\n var arr = new Array(\"time\", \"money\", \"work\");\n var str = arr.toString();\n document.write(\"Returned string is : \" + str );\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 1665,
"s": 1628,
"text": "Returned string is : time,money,work"
}
] |
Constrain a number within a given range in Arduino
|
The constrain() function in Arduino helps to, as the name suggests, constrain a number between an upper bound and a lower bound.
constrain(val, min, max)
where, val is the number to be constrained, min is the lower bound value, and max is the upper bound value
If val is less than min, this function will return min. If val is greater than max, this function will return max. As long as val is between min and max, this function will return val.
The following example illustrates the use of this function −
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println();
int a = 200;
Serial.println(constrain(a, 5, 210));
Serial.println(constrain(a, 300, 400));
Serial.println(constrain(a, 100, 150));
}
void loop() {
// put your main code here, to run repeatedly:
}
The Serial Monitor output is shown below −
As you can see, in the first case, the integer a was within bounds, so it got returned. In the second case, a was less than the lower bound, hence the lower bound got returned, and in the third case, a was higher than the upper bound, hence the upper bound was returned.
Please note that as per Arduino’s documentation (https://www.arduino.cc/reference/en/language/functions/math/constrain/) it is recommended to avoid using another function within constrain.
This constrain (analogRead(A0), 10,50); may yield incorrect results. Instead, you can try −
int a = analogRead(A0);
int a_constr = constrain(a, 10, 50);
|
[
{
"code": null,
"e": 1191,
"s": 1062,
"text": "The constrain() function in Arduino helps to, as the name suggests, constrain a number between an upper bound and a lower bound."
},
{
"code": null,
"e": 1216,
"s": 1191,
"text": "constrain(val, min, max)"
},
{
"code": null,
"e": 1323,
"s": 1216,
"text": "where, val is the number to be constrained, min is the lower bound value, and max is the upper bound value"
},
{
"code": null,
"e": 1508,
"s": 1323,
"text": "If val is less than min, this function will return min. If val is greater than max, this function will return max. As long as val is between min and max, this function will return val."
},
{
"code": null,
"e": 1569,
"s": 1508,
"text": "The following example illustrates the use of this function −"
},
{
"code": null,
"e": 1886,
"s": 1569,
"text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n\n int a = 200;\n Serial.println(constrain(a, 5, 210));\n Serial.println(constrain(a, 300, 400));\n Serial.println(constrain(a, 100, 150));\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n}"
},
{
"code": null,
"e": 1929,
"s": 1886,
"text": "The Serial Monitor output is shown below −"
},
{
"code": null,
"e": 2200,
"s": 1929,
"text": "As you can see, in the first case, the integer a was within bounds, so it got returned. In the second case, a was less than the lower bound, hence the lower bound got returned, and in the third case, a was higher than the upper bound, hence the upper bound was returned."
},
{
"code": null,
"e": 2389,
"s": 2200,
"text": "Please note that as per Arduino’s documentation (https://www.arduino.cc/reference/en/language/functions/math/constrain/) it is recommended to avoid using another function within constrain."
},
{
"code": null,
"e": 2481,
"s": 2389,
"text": "This constrain (analogRead(A0), 10,50); may yield incorrect results. Instead, you can try −"
},
{
"code": null,
"e": 2542,
"s": 2481,
"text": "int a = analogRead(A0);\nint a_constr = constrain(a, 10, 50);"
}
] |
Rotate by 90 degree | Practice | GeeksforGeeks
|
Given a square matrix of size N x N. The task is to rotate it by 90 degrees in anti-clockwise direction without using any extra space.
Example 1:
Input:
N = 3
matrix[][] = {{1, 2, 3},
{4, 5, 6}
{7, 8, 9}}
Output:
Rotated Matrix:
3 6 9
2 5 8
1 4 7
Example 2:
Input:
N = 2
matrix[][] = {{1, 2},
{3, 4}}
Output:
Rotated Matrix:
2 4
1 3
Your Task:
You dont need to read input or print anything. Complete the function rotateby90() which takes the matrix as input parameter and rotates it by 90 degrees in anti-clockwise direction without using any extra space. You have to modify the input matrix in-place.
Expected Time Complexity: O(N2)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 100
1 <= matrix[][] <= 1000
-1
mannukhurana103974 days ago
java
static void rotateby90(int arr[][], int n)
{
for(int i=0; i<n-1; i++){
for(int j=i+1; j<n; j++){
int temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
for(int i=0; i<n; i++){
int z = n-1;
for(int j=0; j<n/2; j++){
int temp = arr[j][i] ;
arr[j][i] = arr[z-j][i];
arr[z-j][i] = temp;
}
}
}
0
20bd5a05201 week ago
static void rotateby90(int arr[][], int n) { // code here for(int i=0;i<arr.length;i++) { for(int j=i;j<arr[i].length;j++) { int temp=arr[i][j]; arr[i][j]=arr[j][i]; arr[j][i]=temp; } } for(int i=0;i<arr[0].length;i++) { int x=0; int j=0; while(j<arr.length/2) { int swap=arr[x][i]; arr[x][i]=arr[arr.length-1-j][i]; arr[arr.length-1-j][i]=swap; j++; x++; } } }
+1
vikasnayakmmmut1 week ago
do in simple way:-
void rotateby90(vector<vector<int> >& matrix, int n) { for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++) { int t=matrix[i][j]; matrix[i][j]=matrix[j][i]; matrix[j][i]=t; } } reverse(matrix.begin(),matrix.end()); }
+4
sharma9897akash1 week ago
FIRST DO TRANSPOSESWAP UPPPERMOST ROW WITH LOWERMOST ROW CONTINUE UNTILL ALL ROWS ARE NOT SWAPPED
FIRST DO TRANSPOSE
SWAP UPPPERMOST ROW WITH LOWERMOST ROW CONTINUE UNTILL ALL ROWS ARE NOT SWAPPED
0
devashishsharma2602 weeks ago
JAVA SOLUTION
static void rotateby90(int matrix[][], int n){ // code here for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ int temp=matrix[i][j]; matrix[i][j]=matrix[j][i]; matrix[j][i]=temp; } } for (int i = 0; i < n; i++) { int start = 0; int end = n - 1; while (start < end) { matrix = swap(matrix,start,i,end,i); start++; end--; } }} static int[][] swap(int[][] arr, int start, int i, int end, int j){ int temp = arr[start][i]; arr[start][i] = arr[end][j]; arr[end][j] = temp; return arr;}
0
rg_19992 weeks ago
Simple C++ solution:time complexity - O(n*n)space complexity - O(1) (in place)
class Solution
{
public:
void transpose(vector<vector<int>>&mat, int n)
{
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
swap(mat[i][j], mat[j][i]);
}
}
}
void reverse_col(vector<vector<int>>&mat, int n)
{
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
swap(mat[i], mat[j]);
}
}
}
void rotateby90(vector<vector<int> >& matrix, int n)
{
// code here
transpose(matrix, n);
reverse_col(matrix, n);
}
};
+1
aloksinghbais023 weeks ago
C++ solution having time complexity as O(n*n) and space complexity as O(n*n) is as follows :-
Execution Time :- 0.09 / 1.1 sec
void rotateby90(vector<vector<int> >& matrix, int n) { vector<vector<int>> temp(n,vector<int>(n)); for(int i1 = 0,j = n - 1; j >= 0; i1++,j--){ for(int j1 = 0,i = 0; i < n; j1++,i++){ temp[i1][j1] = matrix[i][j]; } } for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ matrix[i][j] = temp[i][j]; } } }
0
rathirao053 weeks ago
static void rotateby90(int[,] matrix) { for(int j = 2; j>= 0; j--) { for (int i = 0; i <= 2; i++) { Console.Write(matrix[i,j]); Console.Write('\t'); } Console.WriteLine(); } }
+1
amrit4604 weeks ago
void rotateby90(vector<vector<int> >& matrix, int n)
{
// code here
for (int i=0; i<n-1; i++)
{
for (int j=i+1; j<n; j++)
{
swap(matrix[i][j],matrix[j][i]);
}
}
reverse(matrix.begin(),matrix.end());
}
0
sunboykenneth1 month ago
class Solution
{
private:
void swap(int& t1, int& t2) {
int tmp = t1;
t1 = t2;
t2 = tmp;
}
public:
//Function to rotate matrix anticlockwise by 90 degrees.
void rotateby90(vector<vector<int> >& matrix, int n)
{
if (n < 2) {
return;
}
int midIndex = (n / 2) - 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= midIndex; j++) {
swap(matrix[i][j], matrix[i][n - 1 - j]);
}
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
swap(matrix[i][j], matrix[j][i]);
}
}
}
};
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": 386,
"s": 238,
"text": "Given a square matrix of size N x N. The task is to rotate it by 90 degrees in anti-clockwise direction without using any extra space. \n\nExample 1:"
},
{
"code": null,
"e": 518,
"s": 386,
"text": "Input:\nN = 3 \nmatrix[][] = {{1, 2, 3},\n {4, 5, 6}\n {7, 8, 9}}\nOutput: \nRotated Matrix:\n3 6 9\n2 5 8\n1 4 7\n"
},
{
"code": null,
"e": 529,
"s": 518,
"text": "Example 2:"
},
{
"code": null,
"e": 620,
"s": 529,
"text": "Input:\nN = 2\nmatrix[][] = {{1, 2},\n {3, 4}}\nOutput: \nRotated Matrix:\n2 4\n1 3\n"
},
{
"code": null,
"e": 1005,
"s": 620,
"text": "\nYour Task:\nYou dont need to read input or print anything. Complete the function rotateby90() which takes the matrix as input parameter and rotates it by 90 degrees in anti-clockwise direction without using any extra space. You have to modify the input matrix in-place. \n\nExpected Time Complexity: O(N2)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1 ≤ N ≤ 100\n1 <= matrix[][] <= 1000"
},
{
"code": null,
"e": 1008,
"s": 1005,
"text": "-1"
},
{
"code": null,
"e": 1036,
"s": 1008,
"text": "mannukhurana103974 days ago"
},
{
"code": null,
"e": 1042,
"s": 1036,
"text": "java "
},
{
"code": null,
"e": 1553,
"s": 1044,
"text": "static void rotateby90(int arr[][], int n) \n { \n for(int i=0; i<n-1; i++){\n for(int j=i+1; j<n; j++){\n int temp = arr[i][j];\n arr[i][j] = arr[j][i];\n arr[j][i] = temp;\n }\n }\n \n for(int i=0; i<n; i++){\n int z = n-1;\n for(int j=0; j<n/2; j++){\n int temp = arr[j][i] ;\n arr[j][i] = arr[z-j][i];\n arr[z-j][i] = temp;\n }\n }\n }"
},
{
"code": null,
"e": 1555,
"s": 1553,
"text": "0"
},
{
"code": null,
"e": 1576,
"s": 1555,
"text": "20bd5a05201 week ago"
},
{
"code": null,
"e": 2202,
"s": 1576,
"text": "static void rotateby90(int arr[][], int n) { // code here for(int i=0;i<arr.length;i++) { for(int j=i;j<arr[i].length;j++) { int temp=arr[i][j]; arr[i][j]=arr[j][i]; arr[j][i]=temp; } } for(int i=0;i<arr[0].length;i++) { int x=0; int j=0; while(j<arr.length/2) { int swap=arr[x][i]; arr[x][i]=arr[arr.length-1-j][i]; arr[arr.length-1-j][i]=swap; j++; x++; } } }"
},
{
"code": null,
"e": 2205,
"s": 2202,
"text": "+1"
},
{
"code": null,
"e": 2231,
"s": 2205,
"text": "vikasnayakmmmut1 week ago"
},
{
"code": null,
"e": 2250,
"s": 2231,
"text": "do in simple way:-"
},
{
"code": null,
"e": 2557,
"s": 2250,
"text": " void rotateby90(vector<vector<int> >& matrix, int n) { for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++) { int t=matrix[i][j]; matrix[i][j]=matrix[j][i]; matrix[j][i]=t; } } reverse(matrix.begin(),matrix.end()); } "
},
{
"code": null,
"e": 2560,
"s": 2557,
"text": "+4"
},
{
"code": null,
"e": 2586,
"s": 2560,
"text": "sharma9897akash1 week ago"
},
{
"code": null,
"e": 2685,
"s": 2586,
"text": "FIRST DO TRANSPOSESWAP UPPPERMOST ROW WITH LOWERMOST ROW CONTINUE UNTILL ALL ROWS ARE NOT SWAPPED"
},
{
"code": null,
"e": 2704,
"s": 2685,
"text": "FIRST DO TRANSPOSE"
},
{
"code": null,
"e": 2785,
"s": 2704,
"text": "SWAP UPPPERMOST ROW WITH LOWERMOST ROW CONTINUE UNTILL ALL ROWS ARE NOT SWAPPED"
},
{
"code": null,
"e": 2787,
"s": 2785,
"text": "0"
},
{
"code": null,
"e": 2817,
"s": 2787,
"text": "devashishsharma2602 weeks ago"
},
{
"code": null,
"e": 2831,
"s": 2817,
"text": "JAVA SOLUTION"
},
{
"code": null,
"e": 3474,
"s": 2831,
"text": "static void rotateby90(int matrix[][], int n){ // code here for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ int temp=matrix[i][j]; matrix[i][j]=matrix[j][i]; matrix[j][i]=temp; } } for (int i = 0; i < n; i++) { int start = 0; int end = n - 1; while (start < end) { matrix = swap(matrix,start,i,end,i); start++; end--; } }} static int[][] swap(int[][] arr, int start, int i, int end, int j){ int temp = arr[start][i]; arr[start][i] = arr[end][j]; arr[end][j] = temp; return arr;}"
},
{
"code": null,
"e": 3476,
"s": 3474,
"text": "0"
},
{
"code": null,
"e": 3495,
"s": 3476,
"text": "rg_19992 weeks ago"
},
{
"code": null,
"e": 3575,
"s": 3495,
"text": "Simple C++ solution:time complexity - O(n*n)space complexity - O(1) (in place) "
},
{
"code": null,
"e": 4169,
"s": 3575,
"text": "class Solution\n{ \n public:\n void transpose(vector<vector<int>>&mat, int n)\n {\n for(int i=0;i<n;i++)\n {\n for(int j=i;j<n;j++)\n {\n swap(mat[i][j], mat[j][i]);\n }\n }\n }\n void reverse_col(vector<vector<int>>&mat, int n)\n {\n for(int i=0;i<n;i++)\n {\n for(int j=i;j<n;j++)\n {\n swap(mat[i], mat[j]);\n }\n }\n }\n void rotateby90(vector<vector<int> >& matrix, int n) \n { \n // code here \n transpose(matrix, n);\n reverse_col(matrix, n);\n } \n};"
},
{
"code": null,
"e": 4172,
"s": 4169,
"text": "+1"
},
{
"code": null,
"e": 4199,
"s": 4172,
"text": "aloksinghbais023 weeks ago"
},
{
"code": null,
"e": 4294,
"s": 4199,
"text": "C++ solution having time complexity as O(n*n) and space complexity as O(n*n) is as follows :- "
},
{
"code": null,
"e": 4329,
"s": 4296,
"text": "Execution Time :- 0.09 / 1.1 sec"
},
{
"code": null,
"e": 4748,
"s": 4331,
"text": "void rotateby90(vector<vector<int> >& matrix, int n) { vector<vector<int>> temp(n,vector<int>(n)); for(int i1 = 0,j = n - 1; j >= 0; i1++,j--){ for(int j1 = 0,i = 0; i < n; j1++,i++){ temp[i1][j1] = matrix[i][j]; } } for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ matrix[i][j] = temp[i][j]; } } } "
},
{
"code": null,
"e": 4750,
"s": 4748,
"text": "0"
},
{
"code": null,
"e": 4772,
"s": 4750,
"text": "rathirao053 weeks ago"
},
{
"code": null,
"e": 4965,
"s": 4772,
"text": "static void rotateby90(int[,] matrix) { for(int j = 2; j>= 0; j--) { for (int i = 0; i <= 2; i++) { Console.Write(matrix[i,j]); Console.Write('\\t'); } Console.WriteLine(); } }"
},
{
"code": null,
"e": 4968,
"s": 4965,
"text": "+1"
},
{
"code": null,
"e": 4988,
"s": 4968,
"text": "amrit4604 weeks ago"
},
{
"code": null,
"e": 5292,
"s": 4988,
"text": "void rotateby90(vector<vector<int> >& matrix, int n) \n { \n // code here \n for (int i=0; i<n-1; i++)\n {\n for (int j=i+1; j<n; j++)\n {\n swap(matrix[i][j],matrix[j][i]);\n }\n }\n reverse(matrix.begin(),matrix.end());\n }"
},
{
"code": null,
"e": 5294,
"s": 5292,
"text": "0"
},
{
"code": null,
"e": 5319,
"s": 5294,
"text": "sunboykenneth1 month ago"
},
{
"code": null,
"e": 6035,
"s": 5319,
"text": "class Solution\n{ \n private:\n void swap(int& t1, int& t2) {\n int tmp = t1;\n t1 = t2;\n t2 = tmp;\n }\n \n public:\n //Function to rotate matrix anticlockwise by 90 degrees.\n void rotateby90(vector<vector<int> >& matrix, int n) \n { \n if (n < 2) {\n return;\n }\n \n int midIndex = (n / 2) - 1;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j <= midIndex; j++) {\n swap(matrix[i][j], matrix[i][n - 1 - j]);\n }\n }\n \n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n swap(matrix[i][j], matrix[j][i]);\n }\n }\n } \n};"
},
{
"code": null,
"e": 6181,
"s": 6035,
"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": 6217,
"s": 6181,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6227,
"s": 6217,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6237,
"s": 6227,
"text": "\nContest\n"
},
{
"code": null,
"e": 6300,
"s": 6237,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6448,
"s": 6300,
"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": 6656,
"s": 6448,
"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": 6762,
"s": 6656,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Program to print solid and hollow square patterns in C
|
In geometry, a square is a regular quadrilateral, which means that it has four equal sides and four equal angles.
Solid and Hollow Square will appear as shown below
For Solid Square −
Accept the Number of Rows from the user to draw the Solid Square
For each Row, Print * for each Column to draw the Solid Square
For Hollow Square −
Accept the Number of Rows from the user to draw the Hollow Square
For the First and Last Row, Print * for each Column
For the Remaining Rows, Print * for the first and Last Column.
/* Program to print hollow and Solid Square pattern */
#include <stdio.h>
int main(){
int r, c, rows; //Hollow Rhombus
int r1,c1, rows1; //Solid Rhombus
clrscr();
/* Hollow Square */
printf("Enter the Number of rows for Hollow Square: ");
scanf("%d", &rows);
printf("\n");
for (r=1; r<=rows; r++){
if (r==1 || r==rows){
for (c=1; c<=rows; c++){
printf("*");
}
}
else{
for (c=1; c<=rows; c++){
if (c==1 || c==rows){
printf("*");
}
else{
printf(" ");
}
}
}
printf("\n");
}
printf("\n");
/* Solid Square */
printf("Enter the Number of rows for Solid Square: ");
scanf("%d", &rows1);
printf("\n");
for (r1=1; r1<=rows1; r1++){
for (c1=1; c1<=rows1; c1++){
printf("*");
}
printf("\n");
}
getch();
return 0;
}
|
[
{
"code": null,
"e": 1176,
"s": 1062,
"text": "In geometry, a square is a regular quadrilateral, which means that it has four equal sides and four equal angles."
},
{
"code": null,
"e": 1227,
"s": 1176,
"text": "Solid and Hollow Square will appear as shown below"
},
{
"code": null,
"e": 1246,
"s": 1227,
"text": "For Solid Square −"
},
{
"code": null,
"e": 1374,
"s": 1246,
"text": "Accept the Number of Rows from the user to draw the Solid Square\nFor each Row, Print * for each Column to draw the Solid Square"
},
{
"code": null,
"e": 1394,
"s": 1374,
"text": "For Hollow Square −"
},
{
"code": null,
"e": 1575,
"s": 1394,
"text": "Accept the Number of Rows from the user to draw the Hollow Square\nFor the First and Last Row, Print * for each Column\nFor the Remaining Rows, Print * for the first and Last Column."
},
{
"code": null,
"e": 2516,
"s": 1575,
"text": "/* Program to print hollow and Solid Square pattern */\n#include <stdio.h>\nint main(){\n int r, c, rows; //Hollow Rhombus\n int r1,c1, rows1; //Solid Rhombus\n clrscr();\n /* Hollow Square */\n printf(\"Enter the Number of rows for Hollow Square: \");\n scanf(\"%d\", &rows);\n printf(\"\\n\");\n for (r=1; r<=rows; r++){\n if (r==1 || r==rows){\n for (c=1; c<=rows; c++){\n printf(\"*\");\n }\n }\n else{\n for (c=1; c<=rows; c++){\n if (c==1 || c==rows){\n printf(\"*\");\n }\n else{\n printf(\" \");\n }\n }\n }\n printf(\"\\n\");\n }\n printf(\"\\n\");\n /* Solid Square */\n printf(\"Enter the Number of rows for Solid Square: \");\n scanf(\"%d\", &rows1);\n printf(\"\\n\");\n for (r1=1; r1<=rows1; r1++){\n for (c1=1; c1<=rows1; c1++){\n printf(\"*\");\n }\n printf(\"\\n\");\n }\n getch();\n return 0;\n}"
}
] |
XOR of two Binary Strings
|
30 Apr, 2021
Given two binary strings A and B of equal lengths, the task is to print a string which is the XOR of Binary Strings A and B.Examples:
Input: A = “0001”, B = “0010” Output: 0011Input: A = “1010”, B = “0101” Output: 1111
Approach: The idea is to iterate over both the string character by character and if the character mismatched then add “1” as the character in the answer string otherwise add “0” to the answer string to generate the XOR string.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Implementation to find the// XOR of the two Binary Strings#include<bits/stdc++.h>using namespace std; // Function to find the// XOR of the two Binary Stringsstring xoring(string a, string b, int n){string ans = ""; // Loop to iterate over the // Binary Strings for (int i = 0; i < n; i++) { // If the Character matches if (a[i] == b[i]) ans += "0"; else ans += "1"; } return ans;} // Driver Codeint main(){ string a = "1010"; string b = "1101"; int n = a.length(); string c = xoring(a, b, n); cout << c << endl;} // This code is contributed by Surendra_Gangwar
// Java Implementation to find the// XOR of the two Binary Stringsimport java.io.*; class GFG { // Function to find the // XOR of the two Binary Strings static String xoring(String a, String b, int n){ String ans = ""; // Loop to iterate over the // Binary Strings for (int i = 0; i < n; i++) { // If the Character matches if (a.charAt(i) == b.charAt(i)) ans += "0"; else ans += "1"; } return ans; } // Driver Code public static void main (String[] args) { String a = "1010"; String b = "1101"; int n = a.length(); String c = xoring(a, b, n); System.out.println(c); }} // This code is contributed by shubhamsingh10
# Python Implementation to find the# XOR of the two Binary Strings # Function to find the# XOR of the two Binary Stringsdef xor(a, b, n): ans = "" # Loop to iterate over the # Binary Strings for i in range(n): # If the Character matches if (a[i] == b[i]): ans += "0" else: ans += "1" return ans # Driver Codeif __name__ == "__main__": a = "1010" b = "1101" n = len(a) c = xor(a, b, n) print(c)
// C# Implementation to find the// XOR of the two Binary Stringsusing System; class GFG{ // Function to find the // XOR of the two Binary Strings static string xoring(string a, string b, int n){ string ans = ""; // Loop to iterate over the // Binary Strings for (int i = 0; i < n; i++) { // If the Character matches if (a[i] == b[i]) ans += "0"; else ans += "1"; } return ans; } // Driver Code static public void Main () { string a = "1010"; string b = "1101"; int n = a.Length; string c = xoring(a, b, n); Console.WriteLine(c); }} // This code is contributed by shubhamsingh10
<script> // Javascript Implementation to find the// XOR of the two Binary Strings // Function to find the// XOR of the two Binary Stringsfunction xoring(a, b, n){let ans = ""; // Loop to iterate over the // Binary Strings for (let i = 0; i < n; i++) { // If the Character matches if (a[i] == b[i]) ans += "0"; else ans += "1"; } return ans;} // Driver Code let a = "1010"; let b = "1101"; let n = a.length; let c = xoring(a, b, n); document.write(c); </script>
Output:
0111
SURENDRA_GANGWAR
SHUBHAMSINGH10
rishavmahato348
Bitwise-XOR
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Program to find GCD or HCF of two numbers
Find minimum number of coins that make a given value
Write a program to reverse an array or string
Reverse a string in Java
Different Methods to Reverse a String in C++
Check for Balanced Brackets in an expression (well-formedness) using Stack
Longest Common Subsequence | DP-4
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 188,
"s": 52,
"text": "Given two binary strings A and B of equal lengths, the task is to print a string which is the XOR of Binary Strings A and B.Examples: "
},
{
"code": null,
"e": 275,
"s": 188,
"text": "Input: A = “0001”, B = “0010” Output: 0011Input: A = “1010”, B = “0101” Output: 1111 "
},
{
"code": null,
"e": 505,
"s": 277,
"text": "Approach: The idea is to iterate over both the string character by character and if the character mismatched then add “1” as the character in the answer string otherwise add “0” to the answer string to generate the XOR string. "
},
{
"code": null,
"e": 557,
"s": 505,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 561,
"s": 557,
"text": "C++"
},
{
"code": null,
"e": 566,
"s": 561,
"text": "Java"
},
{
"code": null,
"e": 574,
"s": 566,
"text": "Python3"
},
{
"code": null,
"e": 577,
"s": 574,
"text": "C#"
},
{
"code": null,
"e": 588,
"s": 577,
"text": "Javascript"
},
{
"code": "// C++ Implementation to find the// XOR of the two Binary Strings#include<bits/stdc++.h>using namespace std; // Function to find the// XOR of the two Binary Stringsstring xoring(string a, string b, int n){string ans = \"\"; // Loop to iterate over the // Binary Strings for (int i = 0; i < n; i++) { // If the Character matches if (a[i] == b[i]) ans += \"0\"; else ans += \"1\"; } return ans;} // Driver Codeint main(){ string a = \"1010\"; string b = \"1101\"; int n = a.length(); string c = xoring(a, b, n); cout << c << endl;} // This code is contributed by Surendra_Gangwar",
"e": 1237,
"s": 588,
"text": null
},
{
"code": "// Java Implementation to find the// XOR of the two Binary Stringsimport java.io.*; class GFG { // Function to find the // XOR of the two Binary Strings static String xoring(String a, String b, int n){ String ans = \"\"; // Loop to iterate over the // Binary Strings for (int i = 0; i < n; i++) { // If the Character matches if (a.charAt(i) == b.charAt(i)) ans += \"0\"; else ans += \"1\"; } return ans; } // Driver Code public static void main (String[] args) { String a = \"1010\"; String b = \"1101\"; int n = a.length(); String c = xoring(a, b, n); System.out.println(c); }} // This code is contributed by shubhamsingh10",
"e": 2034,
"s": 1237,
"text": null
},
{
"code": "# Python Implementation to find the# XOR of the two Binary Strings # Function to find the# XOR of the two Binary Stringsdef xor(a, b, n): ans = \"\" # Loop to iterate over the # Binary Strings for i in range(n): # If the Character matches if (a[i] == b[i]): ans += \"0\" else: ans += \"1\" return ans # Driver Codeif __name__ == \"__main__\": a = \"1010\" b = \"1101\" n = len(a) c = xor(a, b, n) print(c)",
"e": 2515,
"s": 2034,
"text": null
},
{
"code": "// C# Implementation to find the// XOR of the two Binary Stringsusing System; class GFG{ // Function to find the // XOR of the two Binary Strings static string xoring(string a, string b, int n){ string ans = \"\"; // Loop to iterate over the // Binary Strings for (int i = 0; i < n; i++) { // If the Character matches if (a[i] == b[i]) ans += \"0\"; else ans += \"1\"; } return ans; } // Driver Code static public void Main () { string a = \"1010\"; string b = \"1101\"; int n = a.Length; string c = xoring(a, b, n); Console.WriteLine(c); }} // This code is contributed by shubhamsingh10",
"e": 3274,
"s": 2515,
"text": null
},
{
"code": "<script> // Javascript Implementation to find the// XOR of the two Binary Strings // Function to find the// XOR of the two Binary Stringsfunction xoring(a, b, n){let ans = \"\"; // Loop to iterate over the // Binary Strings for (let i = 0; i < n; i++) { // If the Character matches if (a[i] == b[i]) ans += \"0\"; else ans += \"1\"; } return ans;} // Driver Code let a = \"1010\"; let b = \"1101\"; let n = a.length; let c = xoring(a, b, n); document.write(c); </script>",
"e": 3816,
"s": 3274,
"text": null
},
{
"code": null,
"e": 3824,
"s": 3816,
"text": "Output:"
},
{
"code": null,
"e": 3829,
"s": 3824,
"text": "0111"
},
{
"code": null,
"e": 3846,
"s": 3829,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 3861,
"s": 3846,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 3877,
"s": 3861,
"text": "rishavmahato348"
},
{
"code": null,
"e": 3889,
"s": 3877,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 3902,
"s": 3889,
"text": "Mathematical"
},
{
"code": null,
"e": 3910,
"s": 3902,
"text": "Strings"
},
{
"code": null,
"e": 3918,
"s": 3910,
"text": "Strings"
},
{
"code": null,
"e": 3931,
"s": 3918,
"text": "Mathematical"
},
{
"code": null,
"e": 4029,
"s": 3931,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4053,
"s": 4029,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 4074,
"s": 4053,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 4088,
"s": 4074,
"text": "Prime Numbers"
},
{
"code": null,
"e": 4130,
"s": 4088,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 4183,
"s": 4130,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 4229,
"s": 4183,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 4254,
"s": 4229,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 4299,
"s": 4254,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 4374,
"s": 4299,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
Sum of XOR of all possible subsets
|
07 Jul, 2022
Given an array arr[] of size n, we need to find the sum of all the values that come from XORing all the elements of the subsets.
Input : arr[] = {1, 5, 6}
Output : 28
Total Subsets = 23
1 = 1
5 = 5
6 = 6
1 ^ 5 = 4
1 ^ 6 = 7
5 ^ 6 = 3
1 ^ 5 ^ 6 = 2
0(empty subset)
Now SUM of all these XORs = 1 + 5 + 6 + 4 +
7 + 3 + 2 + 0
= 28
Input : arr[] = {1, 2}
Output : 6
A Naive approach is to take the XOR all possible combinations of array[] elements and then perform the summation of all values. Time complexity of this approach grows exponentially so it would not be better for a large value of n.
Implementation: Recursive Code for the Naive Approach
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;int rec(int i, int x, int arr[], int size){ // return the current xor sum if we reach the end of // array if (i == size) return x; // first choice can be to include the i-th element in // the subset and thus we take its xor int choice1 = rec(i + 1, x ^ arr[i], arr, size); // second choice can be to include the i-th element in // the subset and thus we take its xor int choice2 = rec(i + 1, x, arr, size); // return sum of both the choices as we need to find the // sum of xor of all subsets return choice1 + choice2;}// Returns sum of XORs of all subsetsint xorSum(int arr[], int size){ return rec(0, 0, arr, size);}// Driver codeint main(){ int arr[] = { 1, 5, 6 }; int size = sizeof(arr) / sizeof(arr[0]); cout << xorSum(arr, size);}
// Java program to implement the approachclass GFG { static int rec(int i, int x, int arr[], int size) { // return the current xor sum if we reach the end of // array if (i == size) return x; // first choice can be to include the i-th element // in the subset and thus we take its xor int choice1 = rec(i + 1, x ^ arr[i], arr, size); // second choice can be to include the i-th element // in the subset and thus we take its xor int choice2 = rec(i + 1, x, arr, size); // return sum of both the choices as we need to find // the sum of xor of all subsets return choice1 + choice2; } // Returns sum of XORs of all subsets static int xorSum(int arr[], int size) { return rec(0, 0, arr, size); } // Driver code public static void main(String[] args) { int arr[] = { 1, 5, 6 }; int size = arr.length; //Function call System.out.println(xorSum(arr, size)); }} // This code is contributed by phasing17
# Python3 program to implement the approachdef rec(i, x, arr, size): # return the current xor sum if we reach the end of # array if (i == size): return x # first choice can be to include the i-th element in # the subset and thus we take its xor choice1 = rec(i + 1, x ^ arr[i], arr, size) # second choice can be to include the i-th element in # the subset and thus we take its xor choice2 = rec(i + 1, x, arr, size) # return sum of both the choices as we need to find the # sum of xor of all subsets return choice1 + choice2 # Returns sum of XORs of all subsetsdef xorSum(arr, size): return rec(0, 0, arr, size) # Driver codearr = [1, 5, 6]size = len(arr) # Function callprint(xorSum(arr, size)) # This code is contributed by phasing17
// C# program to implement the approach using System; class GFG { static int rec(int i, int x, int[] arr, int size) { // return the current xor sum if we reach the end of // array if (i == size) return x; // first choice can be to include the i-th element // in the subset and thus we take its xor int choice1 = rec(i + 1, x ^ arr[i], arr, size); // second choice can be to include the i-th element // in the subset and thus we take its xor int choice2 = rec(i + 1, x, arr, size); // return sum of both the choices as we need to find // the sum of xor of all subsets return choice1 + choice2; } // Returns sum of XORs of all subsets static int xorSum(int[] arr, int size) { return rec(0, 0, arr, size); } // Driver code public static void Main(string[] args) { int[] arr = { 1, 5, 6 }; int size = arr.Length; // Function call Console.WriteLine(xorSum(arr, size)); }} // This code is contributed by phasing17
<script> function rec(i, x, arr, size) { // Return the current xor sum if we reach the end of // array if (i == size) return x; // First choice can be to include the i-th element in // the subset and thus we take its xor let choice1 = rec(i + 1, x ^ arr[i], arr, size); // Second choice can be to include the i-th element in // the subset and thus we take its xor let choice2 = rec(i + 1, x, arr, size); // Return sum of both the choices as we need to find the // sum of xor of all subsets return choice1 + choice2; } // Returns sum of XORs of all subsets function xorSum(arr, size) { return rec(0, 0, arr, size); } // Driver code let arr = [ 1, 5, 6 ]; let size = arr.length; document.write(xorSum(arr, size)); // This code is contributed by AshokJaiswal.</script>
28
An Efficient approach is to find the pattern with respect to the property of XOR. Now again consider the subset in binary form like:
1 = 001
5 = 101
6 = 110
1 ^ 5 = 100
1 ^ 6 = 111
5 ^ 6 = 011
1^5^6 = 010
So if we analyze all these binary numbers of the XORs, we can observe that set bit occurs at all the positions of i(0 to n-1) will exactly contribute to half of 2n. So we can easily impose these two conditions at each such position of i.
If there is any value of arr[] that has set ith bit set, then exactly half of 2n subsets will be of the form, so they will contribute to 2n-1+i to the final sum.
If there is no value of arr[] that ith bit set, then we can say that there will be no term in all subsets that have a ith bit set.
The proof of the above point is as follows:
Case 1:
Lets assume there are k elements in the array with ith bit set and k is not zero.
So, to have a subset with ith bit set in its xor, we need it to have odd number of elements with ith bit set.
Number of ways to choose elements with ith bit not set = 2(n-k)
Number of ways to choose elements with ith bit set = kC1 + kC3 + kC5 .... = 2(k-1)
Total number of ways = 2(n-1)
Thus, the contribution towards sum becomes, 2(n+i-1)
Case 2:
f no element has ith bit set, i.e. k = 0, the contribution of ith bit towards total sum remains 0.
Now the question boils down to check which position of element of the arr[] will be set or not. But here is some trick that we will not iterate for all elements one by one in spite of that we can simple take the OR of all such values and multiply with 2n-1,
For example
Take a OR of all arr[] elements, we get
= 1 | 5 | 6
= 001 | 101 | 110
= 111
Now to find final summation, we can write it down as:-
= 1*2n-1+2 + 1*2n-1+1 + 1*2n-1+0
= 2n-1 * (1*22 + 1*21 + 1*20 )
= 2n-1 * (1112)
= 2n-1 * 7
Put n = 3, we get
= 28
So at last for any value of n and array elements, we can simple say that the final sum will be 2n-1 times the bitwise OR of all the inputs.
C++
Java
Python3
C#
PHP
Javascript
// Below is C++ approach to finding the XOR_SUM#include<bits/stdc++.h>using namespace std; // Returns sum of XORs of all subsetsint xorSum(int arr[], int n){ int bits = 0; // Finding bitwise OR of all elements for (int i=0; i < n; ++i) bits |= arr[i]; int ans = bits * pow(2, n-1); return ans;} // Driver codeint main(){ int arr[] = {1, 5, 6}; int size = sizeof(arr) / sizeof(arr[0]); cout << xorSum(arr, size);}
// Java approach to finding the XOR_SUMclass GFG { // Returns sum of XORs of all subsets static int xorSum(int arr[], int n) { int bits = 0; // Finding bitwise OR of all elements for (int i = 0; i < n; ++i) bits |= arr[i]; int ans = bits * (int)Math.pow(2, n-1); return ans; } // Driver method public static void main(String[] args) { int arr[] = {1, 5, 6}; int size = arr.length; System.out.print(xorSum(arr, size)); }} // This code is contributed by Anant Agarwal.
# Python3 approach to finding the XOR_SUM # Returns sum of XORs of all subsetsdef xorSum(arr, n): bits = 0 # Finding bitwise OR of all elements for i in range(n): bits |= arr[i] ans = bits * pow(2, n-1) return ans # Driver Codearr = [1, 5, 6]size = len(arr)print(xorSum(arr, size)) # This code is contributed by Anant Agarwal.
// C# approach to finding the XOR_SUMusing System; class GFG { // Returns sum of XORs of all subsets static int xorSum(int []arr, int n) { int bits = 0; // Finding bitwise OR of all elements for (int i = 0; i < n; ++i) bits |= arr[i]; int ans = bits * (int)Math.Pow(2, n - 1); return ans; } // Driver code public static void Main() { int []arr = {1, 5, 6}; int size = arr.Length; Console.Write(xorSum(arr, size)); }} // This code is contributed by Nitin Mittal.
<?php// PHP program to finding the XOR_SUM// Returns sum of XORs of all subsets function xorSum($arr, $n){ $bits = 0; // Finding bitwise OR // of all elements for ($i = 0; $i < $n; ++$i) $bits |= $arr[$i]; $ans = $bits * pow(2, $n - 1); return $ans;} // Driver code $arr = array(1, 5, 6); $size = sizeof($arr); echo xorSum($arr, $size); // This code is contributed by nitin mittal.?>
<script>// Below is JavaScript approach to finding the XOR_SUM // Returns sum of XORs of all subsetsfunction xorSum(arr, n){ let bits = 0; // Finding bitwise OR of all elements for (let i=0; i < n; ++i) bits |= arr[i]; let ans = bits * Math.pow(2, n-1); return ans;} // Driver code let arr = [1, 5, 6]; let size = arr.length; document.write(xorSum(arr, size)); // This code is contributed by Surbhi Tyagi. </script>
28
Time complexity: O(n) Auxiliary space: O(1)
Related Problems: Given a set, find XOR of the XOR’s of all subsets. Find sum of sum of all sub-sequences
This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
nitin mittal
DivyanshuShekhar1
surbhityagi15
shaiksarfraj14
dwivediyash
AshokJaiswal
phasing17
hardikkoriintern
Bitwise-XOR
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 184,
"s": 54,
"text": "Given an array arr[] of size n, we need to find the sum of all the values that come from XORing all the elements of the subsets. "
},
{
"code": null,
"e": 474,
"s": 184,
"text": "Input : arr[] = {1, 5, 6}\nOutput : 28\nTotal Subsets = 23\n1 = 1\n5 = 5\n6 = 6\n1 ^ 5 = 4\n1 ^ 6 = 7\n5 ^ 6 = 3\n1 ^ 5 ^ 6 = 2\n0(empty subset)\nNow SUM of all these XORs = 1 + 5 + 6 + 4 +\n 7 + 3 + 2 + 0\n = 28\n\nInput : arr[] = {1, 2}\nOutput : 6\n "
},
{
"code": null,
"e": 705,
"s": 474,
"text": "A Naive approach is to take the XOR all possible combinations of array[] elements and then perform the summation of all values. Time complexity of this approach grows exponentially so it would not be better for a large value of n."
},
{
"code": null,
"e": 759,
"s": 705,
"text": "Implementation: Recursive Code for the Naive Approach"
},
{
"code": null,
"e": 763,
"s": 759,
"text": "C++"
},
{
"code": null,
"e": 768,
"s": 763,
"text": "Java"
},
{
"code": null,
"e": 776,
"s": 768,
"text": "Python3"
},
{
"code": null,
"e": 779,
"s": 776,
"text": "C#"
},
{
"code": null,
"e": 790,
"s": 779,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;int rec(int i, int x, int arr[], int size){ // return the current xor sum if we reach the end of // array if (i == size) return x; // first choice can be to include the i-th element in // the subset and thus we take its xor int choice1 = rec(i + 1, x ^ arr[i], arr, size); // second choice can be to include the i-th element in // the subset and thus we take its xor int choice2 = rec(i + 1, x, arr, size); // return sum of both the choices as we need to find the // sum of xor of all subsets return choice1 + choice2;}// Returns sum of XORs of all subsetsint xorSum(int arr[], int size){ return rec(0, 0, arr, size);}// Driver codeint main(){ int arr[] = { 1, 5, 6 }; int size = sizeof(arr) / sizeof(arr[0]); cout << xorSum(arr, size);}",
"e": 1629,
"s": 790,
"text": null
},
{
"code": "// Java program to implement the approachclass GFG { static int rec(int i, int x, int arr[], int size) { // return the current xor sum if we reach the end of // array if (i == size) return x; // first choice can be to include the i-th element // in the subset and thus we take its xor int choice1 = rec(i + 1, x ^ arr[i], arr, size); // second choice can be to include the i-th element // in the subset and thus we take its xor int choice2 = rec(i + 1, x, arr, size); // return sum of both the choices as we need to find // the sum of xor of all subsets return choice1 + choice2; } // Returns sum of XORs of all subsets static int xorSum(int arr[], int size) { return rec(0, 0, arr, size); } // Driver code public static void main(String[] args) { int arr[] = { 1, 5, 6 }; int size = arr.length; //Function call System.out.println(xorSum(arr, size)); }} // This code is contributed by phasing17",
"e": 2707,
"s": 1629,
"text": null
},
{
"code": "# Python3 program to implement the approachdef rec(i, x, arr, size): # return the current xor sum if we reach the end of # array if (i == size): return x # first choice can be to include the i-th element in # the subset and thus we take its xor choice1 = rec(i + 1, x ^ arr[i], arr, size) # second choice can be to include the i-th element in # the subset and thus we take its xor choice2 = rec(i + 1, x, arr, size) # return sum of both the choices as we need to find the # sum of xor of all subsets return choice1 + choice2 # Returns sum of XORs of all subsetsdef xorSum(arr, size): return rec(0, 0, arr, size) # Driver codearr = [1, 5, 6]size = len(arr) # Function callprint(xorSum(arr, size)) # This code is contributed by phasing17",
"e": 3499,
"s": 2707,
"text": null
},
{
"code": "// C# program to implement the approach using System; class GFG { static int rec(int i, int x, int[] arr, int size) { // return the current xor sum if we reach the end of // array if (i == size) return x; // first choice can be to include the i-th element // in the subset and thus we take its xor int choice1 = rec(i + 1, x ^ arr[i], arr, size); // second choice can be to include the i-th element // in the subset and thus we take its xor int choice2 = rec(i + 1, x, arr, size); // return sum of both the choices as we need to find // the sum of xor of all subsets return choice1 + choice2; } // Returns sum of XORs of all subsets static int xorSum(int[] arr, int size) { return rec(0, 0, arr, size); } // Driver code public static void Main(string[] args) { int[] arr = { 1, 5, 6 }; int size = arr.Length; // Function call Console.WriteLine(xorSum(arr, size)); }} // This code is contributed by phasing17",
"e": 4576,
"s": 3499,
"text": null
},
{
"code": "<script> function rec(i, x, arr, size) { // Return the current xor sum if we reach the end of // array if (i == size) return x; // First choice can be to include the i-th element in // the subset and thus we take its xor let choice1 = rec(i + 1, x ^ arr[i], arr, size); // Second choice can be to include the i-th element in // the subset and thus we take its xor let choice2 = rec(i + 1, x, arr, size); // Return sum of both the choices as we need to find the // sum of xor of all subsets return choice1 + choice2; } // Returns sum of XORs of all subsets function xorSum(arr, size) { return rec(0, 0, arr, size); } // Driver code let arr = [ 1, 5, 6 ]; let size = arr.length; document.write(xorSum(arr, size)); // This code is contributed by AshokJaiswal.</script>",
"e": 5476,
"s": 4576,
"text": null
},
{
"code": null,
"e": 5479,
"s": 5476,
"text": "28"
},
{
"code": null,
"e": 5613,
"s": 5479,
"text": "An Efficient approach is to find the pattern with respect to the property of XOR. Now again consider the subset in binary form like: "
},
{
"code": null,
"e": 5697,
"s": 5613,
"text": " 1 = 001\n 5 = 101\n 6 = 110\n1 ^ 5 = 100\n1 ^ 6 = 111\n5 ^ 6 = 011\n1^5^6 = 010"
},
{
"code": null,
"e": 5936,
"s": 5697,
"text": "So if we analyze all these binary numbers of the XORs, we can observe that set bit occurs at all the positions of i(0 to n-1) will exactly contribute to half of 2n. So we can easily impose these two conditions at each such position of i. "
},
{
"code": null,
"e": 6098,
"s": 5936,
"text": "If there is any value of arr[] that has set ith bit set, then exactly half of 2n subsets will be of the form, so they will contribute to 2n-1+i to the final sum."
},
{
"code": null,
"e": 6229,
"s": 6098,
"text": "If there is no value of arr[] that ith bit set, then we can say that there will be no term in all subsets that have a ith bit set."
},
{
"code": null,
"e": 6273,
"s": 6229,
"text": "The proof of the above point is as follows:"
},
{
"code": null,
"e": 6282,
"s": 6273,
"text": "Case 1: "
},
{
"code": null,
"e": 6365,
"s": 6282,
"text": "Lets assume there are k elements in the array with ith bit set and k is not zero. "
},
{
"code": null,
"e": 6475,
"s": 6365,
"text": "So, to have a subset with ith bit set in its xor, we need it to have odd number of elements with ith bit set."
},
{
"code": null,
"e": 6540,
"s": 6475,
"text": "Number of ways to choose elements with ith bit not set = 2(n-k) "
},
{
"code": null,
"e": 6623,
"s": 6540,
"text": "Number of ways to choose elements with ith bit set = kC1 + kC3 + kC5 .... = 2(k-1)"
},
{
"code": null,
"e": 6654,
"s": 6623,
"text": "Total number of ways = 2(n-1) "
},
{
"code": null,
"e": 6707,
"s": 6654,
"text": "Thus, the contribution towards sum becomes, 2(n+i-1)"
},
{
"code": null,
"e": 6716,
"s": 6707,
"text": "Case 2: "
},
{
"code": null,
"e": 6815,
"s": 6716,
"text": "f no element has ith bit set, i.e. k = 0, the contribution of ith bit towards total sum remains 0."
},
{
"code": null,
"e": 7074,
"s": 6815,
"text": "Now the question boils down to check which position of element of the arr[] will be set or not. But here is some trick that we will not iterate for all elements one by one in spite of that we can simple take the OR of all such values and multiply with 2n-1, "
},
{
"code": null,
"e": 7087,
"s": 7074,
"text": "For example "
},
{
"code": null,
"e": 7336,
"s": 7087,
"text": "Take a OR of all arr[] elements, we get \n= 1 | 5 | 6\n= 001 | 101 | 110\n= 111\n\nNow to find final summation, we can write it down as:-\n= 1*2n-1+2 + 1*2n-1+1 + 1*2n-1+0\n= 2n-1 * (1*22 + 1*21 + 1*20 )\n= 2n-1 * (1112)\n= 2n-1 * 7\n\nPut n = 3, we get\n= 28"
},
{
"code": null,
"e": 7476,
"s": 7336,
"text": "So at last for any value of n and array elements, we can simple say that the final sum will be 2n-1 times the bitwise OR of all the inputs."
},
{
"code": null,
"e": 7480,
"s": 7476,
"text": "C++"
},
{
"code": null,
"e": 7485,
"s": 7480,
"text": "Java"
},
{
"code": null,
"e": 7493,
"s": 7485,
"text": "Python3"
},
{
"code": null,
"e": 7496,
"s": 7493,
"text": "C#"
},
{
"code": null,
"e": 7500,
"s": 7496,
"text": "PHP"
},
{
"code": null,
"e": 7511,
"s": 7500,
"text": "Javascript"
},
{
"code": "// Below is C++ approach to finding the XOR_SUM#include<bits/stdc++.h>using namespace std; // Returns sum of XORs of all subsetsint xorSum(int arr[], int n){ int bits = 0; // Finding bitwise OR of all elements for (int i=0; i < n; ++i) bits |= arr[i]; int ans = bits * pow(2, n-1); return ans;} // Driver codeint main(){ int arr[] = {1, 5, 6}; int size = sizeof(arr) / sizeof(arr[0]); cout << xorSum(arr, size);}",
"e": 7958,
"s": 7511,
"text": null
},
{
"code": "// Java approach to finding the XOR_SUMclass GFG { // Returns sum of XORs of all subsets static int xorSum(int arr[], int n) { int bits = 0; // Finding bitwise OR of all elements for (int i = 0; i < n; ++i) bits |= arr[i]; int ans = bits * (int)Math.pow(2, n-1); return ans; } // Driver method public static void main(String[] args) { int arr[] = {1, 5, 6}; int size = arr.length; System.out.print(xorSum(arr, size)); }} // This code is contributed by Anant Agarwal.",
"e": 8568,
"s": 7958,
"text": null
},
{
"code": "# Python3 approach to finding the XOR_SUM # Returns sum of XORs of all subsetsdef xorSum(arr, n): bits = 0 # Finding bitwise OR of all elements for i in range(n): bits |= arr[i] ans = bits * pow(2, n-1) return ans # Driver Codearr = [1, 5, 6]size = len(arr)print(xorSum(arr, size)) # This code is contributed by Anant Agarwal.",
"e": 8921,
"s": 8568,
"text": null
},
{
"code": "// C# approach to finding the XOR_SUMusing System; class GFG { // Returns sum of XORs of all subsets static int xorSum(int []arr, int n) { int bits = 0; // Finding bitwise OR of all elements for (int i = 0; i < n; ++i) bits |= arr[i]; int ans = bits * (int)Math.Pow(2, n - 1); return ans; } // Driver code public static void Main() { int []arr = {1, 5, 6}; int size = arr.Length; Console.Write(xorSum(arr, size)); }} // This code is contributed by Nitin Mittal.",
"e": 9526,
"s": 8921,
"text": null
},
{
"code": "<?php// PHP program to finding the XOR_SUM// Returns sum of XORs of all subsets function xorSum($arr, $n){ $bits = 0; // Finding bitwise OR // of all elements for ($i = 0; $i < $n; ++$i) $bits |= $arr[$i]; $ans = $bits * pow(2, $n - 1); return $ans;} // Driver code $arr = array(1, 5, 6); $size = sizeof($arr); echo xorSum($arr, $size); // This code is contributed by nitin mittal.?>",
"e": 9951,
"s": 9526,
"text": null
},
{
"code": "<script>// Below is JavaScript approach to finding the XOR_SUM // Returns sum of XORs of all subsetsfunction xorSum(arr, n){ let bits = 0; // Finding bitwise OR of all elements for (let i=0; i < n; ++i) bits |= arr[i]; let ans = bits * Math.pow(2, n-1); return ans;} // Driver code let arr = [1, 5, 6]; let size = arr.length; document.write(xorSum(arr, size)); // This code is contributed by Surbhi Tyagi. </script>",
"e": 10402,
"s": 9951,
"text": null
},
{
"code": null,
"e": 10405,
"s": 10402,
"text": "28"
},
{
"code": null,
"e": 10449,
"s": 10405,
"text": "Time complexity: O(n) Auxiliary space: O(1)"
},
{
"code": null,
"e": 10555,
"s": 10449,
"text": "Related Problems: Given a set, find XOR of the XOR’s of all subsets. Find sum of sum of all sub-sequences"
},
{
"code": null,
"e": 10854,
"s": 10555,
"text": "This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 10867,
"s": 10854,
"text": "nitin mittal"
},
{
"code": null,
"e": 10885,
"s": 10867,
"text": "DivyanshuShekhar1"
},
{
"code": null,
"e": 10899,
"s": 10885,
"text": "surbhityagi15"
},
{
"code": null,
"e": 10914,
"s": 10899,
"text": "shaiksarfraj14"
},
{
"code": null,
"e": 10926,
"s": 10914,
"text": "dwivediyash"
},
{
"code": null,
"e": 10939,
"s": 10926,
"text": "AshokJaiswal"
},
{
"code": null,
"e": 10949,
"s": 10939,
"text": "phasing17"
},
{
"code": null,
"e": 10966,
"s": 10949,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 10978,
"s": 10966,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 10985,
"s": 10978,
"text": "Arrays"
},
{
"code": null,
"e": 10992,
"s": 10985,
"text": "Arrays"
}
] |
Find all the numbers in a string using regular expression in Python
|
29 Dec, 2020
Given a string str containing numbers and alphabets, the task is to find all the numbers in str using regular expression.
Examples:
Input: abcd11gdf15hnnn678hh4Output: 11 15 678 4
Input: 1abcd133hhe0Output: 1 133 0
Approach: The idea is to use Python re library to extract the sub-strings from the given string which match the pattern [0-9]+. This pattern will extract all the characters which match from 0 to 9 and the + sign indicates one or more occurrence of the continuous characters.
Below is the implementation of the above approach:
# Python3 program to extract all the numbers from a stringimport re # Function to extract all the numbers from the given stringdef getNumbers(str): array = re.findall(r'[0-9]+', str) return array # Driver codestr = "adbv345hj43hvb42"array = getNumbers(str)print(*array)
345 43 42
Python Regex-programs
python-regex
Arrays
Python
Python Programs
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Read JSON file using Python
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 150,
"s": 28,
"text": "Given a string str containing numbers and alphabets, the task is to find all the numbers in str using regular expression."
},
{
"code": null,
"e": 160,
"s": 150,
"text": "Examples:"
},
{
"code": null,
"e": 208,
"s": 160,
"text": "Input: abcd11gdf15hnnn678hh4Output: 11 15 678 4"
},
{
"code": null,
"e": 243,
"s": 208,
"text": "Input: 1abcd133hhe0Output: 1 133 0"
},
{
"code": null,
"e": 518,
"s": 243,
"text": "Approach: The idea is to use Python re library to extract the sub-strings from the given string which match the pattern [0-9]+. This pattern will extract all the characters which match from 0 to 9 and the + sign indicates one or more occurrence of the continuous characters."
},
{
"code": null,
"e": 569,
"s": 518,
"text": "Below is the implementation of the above approach:"
},
{
"code": "# Python3 program to extract all the numbers from a stringimport re # Function to extract all the numbers from the given stringdef getNumbers(str): array = re.findall(r'[0-9]+', str) return array # Driver codestr = \"adbv345hj43hvb42\"array = getNumbers(str)print(*array)",
"e": 847,
"s": 569,
"text": null
},
{
"code": null,
"e": 858,
"s": 847,
"text": "345 43 42\n"
},
{
"code": null,
"e": 880,
"s": 858,
"text": "Python Regex-programs"
},
{
"code": null,
"e": 893,
"s": 880,
"text": "python-regex"
},
{
"code": null,
"e": 900,
"s": 893,
"text": "Arrays"
},
{
"code": null,
"e": 907,
"s": 900,
"text": "Python"
},
{
"code": null,
"e": 923,
"s": 907,
"text": "Python Programs"
},
{
"code": null,
"e": 930,
"s": 923,
"text": "Arrays"
},
{
"code": null,
"e": 1028,
"s": 930,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1096,
"s": 1028,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 1140,
"s": 1096,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 1172,
"s": 1140,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 1220,
"s": 1172,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 1234,
"s": 1220,
"text": "Linear Search"
},
{
"code": null,
"e": 1262,
"s": 1234,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 1284,
"s": 1262,
"text": "Python map() function"
},
{
"code": null,
"e": 1302,
"s": 1284,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1346,
"s": 1302,
"text": "How to get column names in Pandas dataframe"
}
] |
Logging in Python
|
29 Dec, 2021
Logging is a means of tracking events that happen when some software runs. Logging is important for software developing, debugging, and running. If you don’t have any logging record and your program crashes, there are very few chances that you detect the cause of the problem. And if you detect the cause, it will consume a lot of time. With logging, you can leave a trail of breadcrumbs so that if something goes wrong, we can determine the cause of the problem.
There are a number of situations like if you are expecting an integer, you have been given a float and you can a cloud API, the service is down for maintenance, and much more. Such problems are out of control and are hard to determine.
Some developers use the concept of printing the statements to validate if the statements are executed correctly or some error has occurred. But printing is not a good idea. It may solve your issues for simple scripts but for complex scripts, the printing approach will fail.Python has a built-in module logging which allows writing status messages to a file or any other output streams. The file can contain the information on which part of the code is executed and what problems have been arisen.
There are five built-in levels of the log message.
Debug : These are used to give Detailed information, typically of interest only when diagnosing problems.
Info : These are used to confirm that things are working as expected
Warning : These are used an indication that something unexpected happened, or is indicative of some problem in the near future
Error : This tells that due to a more serious problem, the software has not been able to perform some function
Critical : This tells serious error, indicating that the program itself may be unable to continue running
If required, developers have the option to create more levels but these are sufficient enough to handle every possible situation. Each built-in level has been assigned its numeric value.
Logging module is packed with several features. It has several constants, classes, and methods. The items with all caps are constant, the capitalize items are classes and the items which start with lowercase letters are methods.
There are several logger objects offered by the module itself.
Logger.info(msg) : This will log a message with level INFO on this logger.
Logger.warning(msg) : This will log a message with a level WARNING on this logger.
Logger.error(msg) : This will log a message with level ERROR on this logger.
Logger.critical(msg) : This will log a message with level CRITICAL on this logger.
Logger.log(lvl,msg) : This will Logs a message with integer level lvl on this logger.
Logger.exception(msg) : This will log a message with level ERROR on this logger.
Logger.setLevel(lvl) : This function sets the threshold of this logger to lvl. This means that all the messages below this level will be ignored.
Logger.addFilter(filt) : This adds a specific filter filt into this logger.
Logger.removeFilter(filt) : This removes a specific filter filt into this logger.
Logger.filter(record) : This method applies the logger’s filter to the record provided and returns True if the record is to be processed. Else, it will return False.
Logger.addHandler(hdlr) : This adds a specific handler hdlr to this logger.
Logger.removeHandler(hdlr) : This removes a specific handler hdlr into this logger.
Logger.hasHandlers() : This checks if the logger has any handler configured or not.
Basics of using the logging module to record the events in a file are very simple.
For that, simply import the module from the library.
Create and configure the logger. It can have several parameters. But importantly, pass the name of the file in which you want to record the events.Here the format of the logger can also be set. By default, the file works in append mode but we can change that to write mode if required.Also, the level of the logger can be set which acts as the threshold for tracking based on the numeric values assigned to each level. There are several attributes which can be passed as parameters.The list of all those parameters is given in Python Library. The user can choose the required attribute according to the requirement.After that, create an object and use the various methods as shown in the example.
Create and configure the logger. It can have several parameters. But importantly, pass the name of the file in which you want to record the events.
Here the format of the logger can also be set. By default, the file works in append mode but we can change that to write mode if required.
Also, the level of the logger can be set which acts as the threshold for tracking based on the numeric values assigned to each level. There are several attributes which can be passed as parameters.
The list of all those parameters is given in Python Library. The user can choose the required attribute according to the requirement.After that, create an object and use the various methods as shown in the example.
Python
# importing moduleimport logging # Create and configure loggerlogging.basicConfig(filename="newfile.log", format='%(asctime)s %(message)s', filemode='w') # Creating an objectlogger = logging.getLogger() # Setting the threshold of logger to DEBUGlogger.setLevel(logging.DEBUG) # Test messageslogger.debug("Harmless debug Message")logger.info("Just an information")logger.warning("Its a Warning")logger.error("Did you try to divide by zero")logger.critical("Internet is down")
The above code will generate a file with the provided name and if we open the file, the file contains the following data.
This article is contributed by Rishabh Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
gv24365
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Dec, 2021"
},
{
"code": null,
"e": 519,
"s": 54,
"text": "Logging is a means of tracking events that happen when some software runs. Logging is important for software developing, debugging, and running. If you don’t have any logging record and your program crashes, there are very few chances that you detect the cause of the problem. And if you detect the cause, it will consume a lot of time. With logging, you can leave a trail of breadcrumbs so that if something goes wrong, we can determine the cause of the problem. "
},
{
"code": null,
"e": 756,
"s": 519,
"text": "There are a number of situations like if you are expecting an integer, you have been given a float and you can a cloud API, the service is down for maintenance, and much more. Such problems are out of control and are hard to determine. "
},
{
"code": null,
"e": 1256,
"s": 756,
"text": "Some developers use the concept of printing the statements to validate if the statements are executed correctly or some error has occurred. But printing is not a good idea. It may solve your issues for simple scripts but for complex scripts, the printing approach will fail.Python has a built-in module logging which allows writing status messages to a file or any other output streams. The file can contain the information on which part of the code is executed and what problems have been arisen. "
},
{
"code": null,
"e": 1309,
"s": 1256,
"text": "There are five built-in levels of the log message. "
},
{
"code": null,
"e": 1415,
"s": 1309,
"text": "Debug : These are used to give Detailed information, typically of interest only when diagnosing problems."
},
{
"code": null,
"e": 1484,
"s": 1415,
"text": "Info : These are used to confirm that things are working as expected"
},
{
"code": null,
"e": 1611,
"s": 1484,
"text": "Warning : These are used an indication that something unexpected happened, or is indicative of some problem in the near future"
},
{
"code": null,
"e": 1722,
"s": 1611,
"text": "Error : This tells that due to a more serious problem, the software has not been able to perform some function"
},
{
"code": null,
"e": 1828,
"s": 1722,
"text": "Critical : This tells serious error, indicating that the program itself may be unable to continue running"
},
{
"code": null,
"e": 2015,
"s": 1828,
"text": "If required, developers have the option to create more levels but these are sufficient enough to handle every possible situation. Each built-in level has been assigned its numeric value."
},
{
"code": null,
"e": 2245,
"s": 2015,
"text": "Logging module is packed with several features. It has several constants, classes, and methods. The items with all caps are constant, the capitalize items are classes and the items which start with lowercase letters are methods. "
},
{
"code": null,
"e": 2310,
"s": 2245,
"text": "There are several logger objects offered by the module itself. "
},
{
"code": null,
"e": 2385,
"s": 2310,
"text": "Logger.info(msg) : This will log a message with level INFO on this logger."
},
{
"code": null,
"e": 2468,
"s": 2385,
"text": "Logger.warning(msg) : This will log a message with a level WARNING on this logger."
},
{
"code": null,
"e": 2545,
"s": 2468,
"text": "Logger.error(msg) : This will log a message with level ERROR on this logger."
},
{
"code": null,
"e": 2628,
"s": 2545,
"text": "Logger.critical(msg) : This will log a message with level CRITICAL on this logger."
},
{
"code": null,
"e": 2714,
"s": 2628,
"text": "Logger.log(lvl,msg) : This will Logs a message with integer level lvl on this logger."
},
{
"code": null,
"e": 2795,
"s": 2714,
"text": "Logger.exception(msg) : This will log a message with level ERROR on this logger."
},
{
"code": null,
"e": 2941,
"s": 2795,
"text": "Logger.setLevel(lvl) : This function sets the threshold of this logger to lvl. This means that all the messages below this level will be ignored."
},
{
"code": null,
"e": 3017,
"s": 2941,
"text": "Logger.addFilter(filt) : This adds a specific filter filt into this logger."
},
{
"code": null,
"e": 3099,
"s": 3017,
"text": "Logger.removeFilter(filt) : This removes a specific filter filt into this logger."
},
{
"code": null,
"e": 3265,
"s": 3099,
"text": "Logger.filter(record) : This method applies the logger’s filter to the record provided and returns True if the record is to be processed. Else, it will return False."
},
{
"code": null,
"e": 3341,
"s": 3265,
"text": "Logger.addHandler(hdlr) : This adds a specific handler hdlr to this logger."
},
{
"code": null,
"e": 3425,
"s": 3341,
"text": "Logger.removeHandler(hdlr) : This removes a specific handler hdlr into this logger."
},
{
"code": null,
"e": 3510,
"s": 3425,
"text": "Logger.hasHandlers() : This checks if the logger has any handler configured or not. "
},
{
"code": null,
"e": 3594,
"s": 3510,
"text": "Basics of using the logging module to record the events in a file are very simple. "
},
{
"code": null,
"e": 3649,
"s": 3594,
"text": "For that, simply import the module from the library. "
},
{
"code": null,
"e": 4346,
"s": 3649,
"text": "Create and configure the logger. It can have several parameters. But importantly, pass the name of the file in which you want to record the events.Here the format of the logger can also be set. By default, the file works in append mode but we can change that to write mode if required.Also, the level of the logger can be set which acts as the threshold for tracking based on the numeric values assigned to each level. There are several attributes which can be passed as parameters.The list of all those parameters is given in Python Library. The user can choose the required attribute according to the requirement.After that, create an object and use the various methods as shown in the example."
},
{
"code": null,
"e": 4494,
"s": 4346,
"text": "Create and configure the logger. It can have several parameters. But importantly, pass the name of the file in which you want to record the events."
},
{
"code": null,
"e": 4633,
"s": 4494,
"text": "Here the format of the logger can also be set. By default, the file works in append mode but we can change that to write mode if required."
},
{
"code": null,
"e": 4831,
"s": 4633,
"text": "Also, the level of the logger can be set which acts as the threshold for tracking based on the numeric values assigned to each level. There are several attributes which can be passed as parameters."
},
{
"code": null,
"e": 5046,
"s": 4831,
"text": "The list of all those parameters is given in Python Library. The user can choose the required attribute according to the requirement.After that, create an object and use the various methods as shown in the example."
},
{
"code": null,
"e": 5053,
"s": 5046,
"text": "Python"
},
{
"code": "# importing moduleimport logging # Create and configure loggerlogging.basicConfig(filename=\"newfile.log\", format='%(asctime)s %(message)s', filemode='w') # Creating an objectlogger = logging.getLogger() # Setting the threshold of logger to DEBUGlogger.setLevel(logging.DEBUG) # Test messageslogger.debug(\"Harmless debug Message\")logger.info(\"Just an information\")logger.warning(\"Its a Warning\")logger.error(\"Did you try to divide by zero\")logger.critical(\"Internet is down\")",
"e": 5566,
"s": 5053,
"text": null
},
{
"code": null,
"e": 5689,
"s": 5566,
"text": "The above code will generate a file with the provided name and if we open the file, the file contains the following data. "
},
{
"code": null,
"e": 5987,
"s": 5689,
"text": "This article is contributed by Rishabh Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 6112,
"s": 5987,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 6120,
"s": 6112,
"text": "gv24365"
},
{
"code": null,
"e": 6127,
"s": 6120,
"text": "Python"
}
] |
Write you own Power without using multiplication(*) and division(/) operators
|
11 Jun, 2022
Method 1 (Using Nested Loops)We can calculate power by using repeated addition. For example to calculate 5^6. 1) First 5 times add 5, we get 25. (5^2) 2) Then 5 times add 25, we get 125. (5^3) 3) Then 5 times add 125, we get 625 (5^4) 4) Then 5 times add 625, we get 3125 (5^5) 5) Then 5 times add 3125, we get 15625 (5^6)
C++
C
Java
Python
C#
PHP
Javascript
// C++ code for power function#include <bits/stdc++.h>using namespace std; /* Works only if a >= 0 and b >= 0 */int pow(int a, int b){ if (b == 0) return 1; int answer = a; int increment = a; int i, j; for(i = 1; i < b; i++) { for(j = 1; j < a; j++) { answer += increment; } increment = answer; } return answer;} // Driver Codeint main(){ cout << pow(5, 3); return 0;} // This code is contributed// by rathbhupendra
#include<stdio.h>/* Works only if a >= 0 and b >= 0 */int pow(int a, int b){ //base case : anything raised to the power 0 is 1 if (b == 0) return 1; int answer = a; int increment = a; int i, j; for(i = 1; i < b; i++) { for(j = 1; j < a; j++) { answer += increment; } increment = answer; } return answer;} /* driver program to test above function */int main(){ printf("\n %d", pow(5, 3)); getchar(); return 0;}
import java.io.*; class GFG { /* Works only if a >= 0 and b >= 0 */ static int pow(int a, int b) { if (b == 0) return 1; int answer = a; int increment = a; int i, j; for (i = 1; i < b; i++) { for (j = 1; j < a; j++) { answer += increment; } increment = answer; } return answer; } // driver program to test above function public static void main(String[] args) { System.out.println(pow(5, 3)); }} // This code is contributed by vt_m.
# Python 3 code for power# function # Works only if a >= 0 and b >= 0def pow(a,b): if(b==0): return 1 answer=a increment=a for i in range(1,b): for j in range (1,a): answer+=increment increment=answer return answer # driver codeprint(pow(5,3)) # this code is contributed# by Sam007
using System; class GFG{ /* Works only if a >= 0 and b >= 0 */ static int pow(int a, int b) { if (b == 0) return 1; int answer = a; int increment = a; int i, j; for (i = 1; i < b; i++) { for (j = 1; j < a; j++) { answer += increment; } increment = answer; } return answer; } // driver program to test // above function public static void Main() { Console.Write(pow(5, 3)); }} // This code is contributed by Sam007
<?php // Works only if a >= 0// and b >= 0function poww($a, $b){ if ($b == 0) return 1; $answer = $a; $increment = $a; $i; $j; for($i = 1; $i < $b; $i++) { for($j = 1; $j < $a; $j++) { $answer += $increment; } $increment = $answer; } return $answer;} // Driver Code echo( poww(5, 3)); // This code is contributed by nitin mittal.?>
<script> /* Works only if a >= 0 and b >= 0 */function pow(a , b){ if (b == 0) return 1; var answer = a; var increment = a; var i, j; for (i = 1; i < b; i++) { for (j = 1; j < a; j++) { answer += increment; } increment = answer; } return answer;} // driver program to test above functiondocument.write(pow(5, 3)); // This code is contributed by shikhasingrajput</script>
Output :
125
Time Complexity: O(a * b)
Auxiliary Space: O(1)
Method 2 (Using Recursion) Recursively add a to get the multiplication of two numbers. And recursively multiply to get a raise to the power b.
C++
C
Java
Python3
C#
PHP
Javascript
#include<bits/stdc++.h>using namespace std; /* A recursive function to get x*y */int multiply(int x, int y){ if(y) return (x + multiply(x, y - 1)); else return 0;} /* A recursive function to get a^bWorks only if a >= 0 and b >= 0 */int pow(int a, int b){ if(b) return multiply(a, pow(a, b - 1)); else return 1;} // Driver Codeint main(){ cout << pow(5, 3); getchar(); return 0;} // This code is contributed// by Akanksha Rai
#include<stdio.h>/* A recursive function to get a^b Works only if a >= 0 and b >= 0 */int pow(int a, int b){ if(b) return multiply(a, pow(a, b-1)); else return 1;} /* A recursive function to get x*y */int multiply(int x, int y){ if(y) return (x + multiply(x, y-1)); else return 0;} /* driver program to test above functions */int main(){ printf("\n %d", pow(5, 3)); getchar(); return 0;}
import java.io.*; class GFG { /* A recursive function to get a^b Works only if a >= 0 and b >= 0 */ static int pow(int a, int b) { if (b > 0) return multiply(a, pow(a, b - 1)); else return 1; } /* A recursive function to get x*y */ static int multiply(int x, int y) { if (y > 0) return (x + multiply(x, y - 1)); else return 0; } /* driver program to test above functions */ public static void main(String[] args) { System.out.println(pow(5, 3)); }} // This code is contributed by vt_m.
def pow(a,b): if(b): return multiply(a, pow(a, b-1)); else: return 1; # A recursive function to get x*y *def multiply(x, y): if (y): return (x + multiply(x, y-1)); else: return 0; # driver program to test above functions *print(pow(5, 3)); # This code is contributed# by Sam007
using System; class GFG{ /* A recursive function to get a^b Works only if a >= 0 and b >= 0 */ static int pow(int a, int b) { if (b > 0) return multiply(a, pow(a, b - 1)); else return 1; } /* A recursive function to get x*y */ static int multiply(int x, int y) { if (y > 0) return (x + multiply(x, y - 1)); else return 0; } /* driver program to test above functions */ public static void Main() { Console.Write(pow(5, 3)); }} // This code is contributed by Sam007
<?php /* A recursive function to get a^b Works only if a >= 0 and b >= 0 */function p_ow( $a, $b){ if($b) return multiply($a, p_ow($a, $b - 1)); else return 1;} /* A recursive function to get x*y */function multiply($x, $y){ if($y) return ($x + multiply($x, $y - 1)); else return 0;} // Driver Codeecho pow(5, 3); // This code is contributed by anuj_67.?>
<script> // A recursive function to get a^b// Works only if a >= 0 and b >= 0function pow(a, b){ if (b > 0) return multiply(a, pow(a, b - 1)); else return 1;} // A recursive function to get x*yfunction multiply(x, y){ if (y > 0) return (x + multiply(x, y - 1)); else return 0;} // Driver codedocument.write(pow(5, 3)); // This code is contributed by gauravrajput1 </script>
Output :
125
Time Complexity: O(b)
Auxiliary Space: O(b)
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Method 3 (Using bit masking)
approach
we can a^n (let’s say 3^5) as 3^4 * 3^0 * 3^1 = 3^, so we can represent 5 as its binary i.e. 101
t
C++
C
Java
Python3
C#
Javascript
#include <iostream>using namespace std; //function calculating powerlong long pow(int a, int n){ int ans=1; while(n>0){ // calculate last bit(right most) bit of n int last_bit = n&1; //if last bit is 1 then multiply ans and a if(last_bit){ ans = ans*a; } //make a equal to square of a as on every succeeding bit it got squared like a^0, a^1, a^2, a^4, a^8 a = a*a; n = n >> 1; } return ans;} //driver codeint main() { cout<<pow(3,5); return 0;}
#include <stdio.h> // function calculating powerlong long pow_(int a, int n){ int ans = 1; while(n > 0) { // calculate last bit(right most) bit of n int last_bit = n&1; // if last bit is 1 then multiply ans and a if(last_bit){ ans = ans*a; } //make a equal to square of a as on every succeeding bit it got squared like a^0, a^1, a^2, a^4, a^8 a = a*a; n = n >> 1; } return ans;} // driver codeint main(){ // pow is an inbuilt function so I have used pow_ as a function name printf("%lld",pow_(3,5)); return 0;} // This code is contributed by akashish_.
// Java program for the above approachimport java.io.*;import java.util.*; class GFG{ // function calculating powerstatic int pow(int a, int n){ int ans = 1; while(n > 0) { // calculate last bit(right most) bit of n int last_bit = n&1; //if last bit is 1 then multiply ans and a if(last_bit != 0){ ans = ans*a; } //make a equal to square of a as on every succeeding bit it got squared like a^0, a^1, a^2, a^4, a^8 a = a*a; n = n >> 1; } return ans;} // Driver Codepublic static void main(String[] args){ System.out.print(pow(3,5));}} // This code is contributed by code_hunt.
# function calculating powerdef pow(a, n): ans = 1 while(n > 0): # calculate last bit(right most) bit of n last_bit = n&1 # if last bit is 1 then multiply ans and a if(last_bit): ans = ans*a # make a equal to square of a as on # every succeeding bit it got squared # like a^0, a^1, a^2, a^4, a^8 a = a*a n = n >> 1 return ans # driver codeprint(pow(3, 5)) # This code is contributed by shinjanpatra
// C# code to implement the approachusing System;using System.Numerics;using System.Collections.Generic; public class GFG { // function calculating powerstatic int pow(int a, int n){ int ans = 1; while(n > 0) { // calculate last bit(right most) bit of n int last_bit = n&1; //if last bit is 1 then multiply ans and a if(last_bit != 0){ ans = ans*a; } //make a equal to square of a as on every succeeding bit it got squared like a^0, a^1, a^2, a^4, a^8 a = a*a; n = n >> 1; } return ans;} // Driver Codepublic static void Main(string[] args){ Console.Write(pow(3,5));}} // This code is contributed by sanjoy_62.
<script> // function calculating powerfunction pow(a, n){ let ans = 1; while(n > 0) { // calculate last bit(right most) bit of n let last_bit = n&1; // if last bit is 1 then multiply ans and a if(last_bit) { ans = ans*a; } // make a equal to square of a as on // every succeeding bit it got squared // like a^0, a^1, a^2, a^4, a^8 a = a*a; n = n >> 1; } return ans;} // driver codedocument.write(pow(3,5),"</br>"); // This code is contributed by shinjanpatra </script>
Time Complexity: O(log n)
Auxiliary Space: O(1)
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=OIgpvFAew6k" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.
nitin mittal
vt_m
rathbhupendra
Akanksha_Rai
dkp1903
nidhi_biet
shikhasingrajput
GauravRajput1
subhammahato348
subham348
kkunalguptaaa
shinjanpatra
kashishsoda
sweetyty
sanjoy_62
code_hunt
akashish__
Divide and Conquer
Mathematical
Mathematical
Divide and Conquer
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge Sort
QuickSort
Binary Search
Count Inversions in an array | Set 1 (Using Merge Sort)
Median of two sorted arrays of different sizes
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": "\n11 Jun, 2022"
},
{
"code": null,
"e": 376,
"s": 52,
"text": "Method 1 (Using Nested Loops)We can calculate power by using repeated addition. For example to calculate 5^6. 1) First 5 times add 5, we get 25. (5^2) 2) Then 5 times add 25, we get 125. (5^3) 3) Then 5 times add 125, we get 625 (5^4) 4) Then 5 times add 625, we get 3125 (5^5) 5) Then 5 times add 3125, we get 15625 (5^6) "
},
{
"code": null,
"e": 380,
"s": 376,
"text": "C++"
},
{
"code": null,
"e": 382,
"s": 380,
"text": "C"
},
{
"code": null,
"e": 387,
"s": 382,
"text": "Java"
},
{
"code": null,
"e": 394,
"s": 387,
"text": "Python"
},
{
"code": null,
"e": 397,
"s": 394,
"text": "C#"
},
{
"code": null,
"e": 401,
"s": 397,
"text": "PHP"
},
{
"code": null,
"e": 412,
"s": 401,
"text": "Javascript"
},
{
"code": "// C++ code for power function#include <bits/stdc++.h>using namespace std; /* Works only if a >= 0 and b >= 0 */int pow(int a, int b){ if (b == 0) return 1; int answer = a; int increment = a; int i, j; for(i = 1; i < b; i++) { for(j = 1; j < a; j++) { answer += increment; } increment = answer; } return answer;} // Driver Codeint main(){ cout << pow(5, 3); return 0;} // This code is contributed// by rathbhupendra",
"e": 904,
"s": 412,
"text": null
},
{
"code": "#include<stdio.h>/* Works only if a >= 0 and b >= 0 */int pow(int a, int b){ //base case : anything raised to the power 0 is 1 if (b == 0) return 1; int answer = a; int increment = a; int i, j; for(i = 1; i < b; i++) { for(j = 1; j < a; j++) { answer += increment; } increment = answer; } return answer;} /* driver program to test above function */int main(){ printf(\"\\n %d\", pow(5, 3)); getchar(); return 0;}",
"e": 1353,
"s": 904,
"text": null
},
{
"code": "import java.io.*; class GFG { /* Works only if a >= 0 and b >= 0 */ static int pow(int a, int b) { if (b == 0) return 1; int answer = a; int increment = a; int i, j; for (i = 1; i < b; i++) { for (j = 1; j < a; j++) { answer += increment; } increment = answer; } return answer; } // driver program to test above function public static void main(String[] args) { System.out.println(pow(5, 3)); }} // This code is contributed by vt_m.",
"e": 1962,
"s": 1353,
"text": null
},
{
"code": "# Python 3 code for power# function # Works only if a >= 0 and b >= 0def pow(a,b): if(b==0): return 1 answer=a increment=a for i in range(1,b): for j in range (1,a): answer+=increment increment=answer return answer # driver codeprint(pow(5,3)) # this code is contributed# by Sam007",
"e": 2305,
"s": 1962,
"text": null
},
{
"code": "using System; class GFG{ /* Works only if a >= 0 and b >= 0 */ static int pow(int a, int b) { if (b == 0) return 1; int answer = a; int increment = a; int i, j; for (i = 1; i < b; i++) { for (j = 1; j < a; j++) { answer += increment; } increment = answer; } return answer; } // driver program to test // above function public static void Main() { Console.Write(pow(5, 3)); }} // This code is contributed by Sam007",
"e": 2893,
"s": 2305,
"text": null
},
{
"code": "<?php // Works only if a >= 0// and b >= 0function poww($a, $b){ if ($b == 0) return 1; $answer = $a; $increment = $a; $i; $j; for($i = 1; $i < $b; $i++) { for($j = 1; $j < $a; $j++) { $answer += $increment; } $increment = $answer; } return $answer;} // Driver Code echo( poww(5, 3)); // This code is contributed by nitin mittal.?>",
"e": 3306,
"s": 2893,
"text": null
},
{
"code": "<script> /* Works only if a >= 0 and b >= 0 */function pow(a , b){ if (b == 0) return 1; var answer = a; var increment = a; var i, j; for (i = 1; i < b; i++) { for (j = 1; j < a; j++) { answer += increment; } increment = answer; } return answer;} // driver program to test above functiondocument.write(pow(5, 3)); // This code is contributed by shikhasingrajput</script>",
"e": 3769,
"s": 3306,
"text": null
},
{
"code": null,
"e": 3779,
"s": 3769,
"text": "Output : "
},
{
"code": null,
"e": 3783,
"s": 3779,
"text": "125"
},
{
"code": null,
"e": 3809,
"s": 3783,
"text": "Time Complexity: O(a * b)"
},
{
"code": null,
"e": 3831,
"s": 3809,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3974,
"s": 3831,
"text": "Method 2 (Using Recursion) Recursively add a to get the multiplication of two numbers. And recursively multiply to get a raise to the power b."
},
{
"code": null,
"e": 3978,
"s": 3974,
"text": "C++"
},
{
"code": null,
"e": 3980,
"s": 3978,
"text": "C"
},
{
"code": null,
"e": 3985,
"s": 3980,
"text": "Java"
},
{
"code": null,
"e": 3993,
"s": 3985,
"text": "Python3"
},
{
"code": null,
"e": 3996,
"s": 3993,
"text": "C#"
},
{
"code": null,
"e": 4000,
"s": 3996,
"text": "PHP"
},
{
"code": null,
"e": 4011,
"s": 4000,
"text": "Javascript"
},
{
"code": "#include<bits/stdc++.h>using namespace std; /* A recursive function to get x*y */int multiply(int x, int y){ if(y) return (x + multiply(x, y - 1)); else return 0;} /* A recursive function to get a^bWorks only if a >= 0 and b >= 0 */int pow(int a, int b){ if(b) return multiply(a, pow(a, b - 1)); else return 1;} // Driver Codeint main(){ cout << pow(5, 3); getchar(); return 0;} // This code is contributed// by Akanksha Rai",
"e": 4485,
"s": 4011,
"text": null
},
{
"code": "#include<stdio.h>/* A recursive function to get a^b Works only if a >= 0 and b >= 0 */int pow(int a, int b){ if(b) return multiply(a, pow(a, b-1)); else return 1;} /* A recursive function to get x*y */int multiply(int x, int y){ if(y) return (x + multiply(x, y-1)); else return 0;} /* driver program to test above functions */int main(){ printf(\"\\n %d\", pow(5, 3)); getchar(); return 0;}",
"e": 4904,
"s": 4485,
"text": null
},
{
"code": "import java.io.*; class GFG { /* A recursive function to get a^b Works only if a >= 0 and b >= 0 */ static int pow(int a, int b) { if (b > 0) return multiply(a, pow(a, b - 1)); else return 1; } /* A recursive function to get x*y */ static int multiply(int x, int y) { if (y > 0) return (x + multiply(x, y - 1)); else return 0; } /* driver program to test above functions */ public static void main(String[] args) { System.out.println(pow(5, 3)); }} // This code is contributed by vt_m.",
"e": 5533,
"s": 4904,
"text": null
},
{
"code": "def pow(a,b): if(b): return multiply(a, pow(a, b-1)); else: return 1; # A recursive function to get x*y *def multiply(x, y): if (y): return (x + multiply(x, y-1)); else: return 0; # driver program to test above functions *print(pow(5, 3)); # This code is contributed# by Sam007",
"e": 5867,
"s": 5533,
"text": null
},
{
"code": "using System; class GFG{ /* A recursive function to get a^b Works only if a >= 0 and b >= 0 */ static int pow(int a, int b) { if (b > 0) return multiply(a, pow(a, b - 1)); else return 1; } /* A recursive function to get x*y */ static int multiply(int x, int y) { if (y > 0) return (x + multiply(x, y - 1)); else return 0; } /* driver program to test above functions */ public static void Main() { Console.Write(pow(5, 3)); }} // This code is contributed by Sam007",
"e": 6469,
"s": 5867,
"text": null
},
{
"code": "<?php /* A recursive function to get a^b Works only if a >= 0 and b >= 0 */function p_ow( $a, $b){ if($b) return multiply($a, p_ow($a, $b - 1)); else return 1;} /* A recursive function to get x*y */function multiply($x, $y){ if($y) return ($x + multiply($x, $y - 1)); else return 0;} // Driver Codeecho pow(5, 3); // This code is contributed by anuj_67.?>",
"e": 6878,
"s": 6469,
"text": null
},
{
"code": "<script> // A recursive function to get a^b// Works only if a >= 0 and b >= 0function pow(a, b){ if (b > 0) return multiply(a, pow(a, b - 1)); else return 1;} // A recursive function to get x*yfunction multiply(x, y){ if (y > 0) return (x + multiply(x, y - 1)); else return 0;} // Driver codedocument.write(pow(5, 3)); // This code is contributed by gauravrajput1 </script>",
"e": 7292,
"s": 6878,
"text": null
},
{
"code": null,
"e": 7302,
"s": 7292,
"text": "Output : "
},
{
"code": null,
"e": 7306,
"s": 7302,
"text": "125"
},
{
"code": null,
"e": 7328,
"s": 7306,
"text": "Time Complexity: O(b)"
},
{
"code": null,
"e": 7351,
"s": 7328,
"text": "Auxiliary Space: O(b) "
},
{
"code": null,
"e": 7360,
"s": 7351,
"text": "Chapters"
},
{
"code": null,
"e": 7387,
"s": 7360,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 7437,
"s": 7387,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 7460,
"s": 7437,
"text": "captions off, selected"
},
{
"code": null,
"e": 7468,
"s": 7460,
"text": "English"
},
{
"code": null,
"e": 7492,
"s": 7468,
"text": "This is a modal window."
},
{
"code": null,
"e": 7561,
"s": 7492,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 7583,
"s": 7561,
"text": "End of dialog window."
},
{
"code": null,
"e": 7613,
"s": 7583,
"text": "Method 3 (Using bit masking) "
},
{
"code": null,
"e": 7622,
"s": 7613,
"text": "approach"
},
{
"code": null,
"e": 7719,
"s": 7622,
"text": "we can a^n (let’s say 3^5) as 3^4 * 3^0 * 3^1 = 3^, so we can represent 5 as its binary i.e. 101"
},
{
"code": null,
"e": 7721,
"s": 7719,
"text": "t"
},
{
"code": null,
"e": 7725,
"s": 7721,
"text": "C++"
},
{
"code": null,
"e": 7727,
"s": 7725,
"text": "C"
},
{
"code": null,
"e": 7732,
"s": 7727,
"text": "Java"
},
{
"code": null,
"e": 7740,
"s": 7732,
"text": "Python3"
},
{
"code": null,
"e": 7743,
"s": 7740,
"text": "C#"
},
{
"code": null,
"e": 7754,
"s": 7743,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; //function calculating powerlong long pow(int a, int n){ int ans=1; while(n>0){ // calculate last bit(right most) bit of n int last_bit = n&1; //if last bit is 1 then multiply ans and a if(last_bit){ ans = ans*a; } //make a equal to square of a as on every succeeding bit it got squared like a^0, a^1, a^2, a^4, a^8 a = a*a; n = n >> 1; } return ans;} //driver codeint main() { cout<<pow(3,5); return 0;}",
"e": 8307,
"s": 7754,
"text": null
},
{
"code": "#include <stdio.h> // function calculating powerlong long pow_(int a, int n){ int ans = 1; while(n > 0) { // calculate last bit(right most) bit of n int last_bit = n&1; // if last bit is 1 then multiply ans and a if(last_bit){ ans = ans*a; } //make a equal to square of a as on every succeeding bit it got squared like a^0, a^1, a^2, a^4, a^8 a = a*a; n = n >> 1; } return ans;} // driver codeint main(){ // pow is an inbuilt function so I have used pow_ as a function name printf(\"%lld\",pow_(3,5)); return 0;} // This code is contributed by akashish_.",
"e": 8905,
"s": 8307,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.*; class GFG{ // function calculating powerstatic int pow(int a, int n){ int ans = 1; while(n > 0) { // calculate last bit(right most) bit of n int last_bit = n&1; //if last bit is 1 then multiply ans and a if(last_bit != 0){ ans = ans*a; } //make a equal to square of a as on every succeeding bit it got squared like a^0, a^1, a^2, a^4, a^8 a = a*a; n = n >> 1; } return ans;} // Driver Codepublic static void main(String[] args){ System.out.print(pow(3,5));}} // This code is contributed by code_hunt.",
"e": 9601,
"s": 8905,
"text": null
},
{
"code": "# function calculating powerdef pow(a, n): ans = 1 while(n > 0): # calculate last bit(right most) bit of n last_bit = n&1 # if last bit is 1 then multiply ans and a if(last_bit): ans = ans*a # make a equal to square of a as on # every succeeding bit it got squared # like a^0, a^1, a^2, a^4, a^8 a = a*a n = n >> 1 return ans # driver codeprint(pow(3, 5)) # This code is contributed by shinjanpatra",
"e": 10109,
"s": 9601,
"text": null
},
{
"code": "// C# code to implement the approachusing System;using System.Numerics;using System.Collections.Generic; public class GFG { // function calculating powerstatic int pow(int a, int n){ int ans = 1; while(n > 0) { // calculate last bit(right most) bit of n int last_bit = n&1; //if last bit is 1 then multiply ans and a if(last_bit != 0){ ans = ans*a; } //make a equal to square of a as on every succeeding bit it got squared like a^0, a^1, a^2, a^4, a^8 a = a*a; n = n >> 1; } return ans;} // Driver Codepublic static void Main(string[] args){ Console.Write(pow(3,5));}} // This code is contributed by sanjoy_62.",
"e": 10840,
"s": 10109,
"text": null
},
{
"code": "<script> // function calculating powerfunction pow(a, n){ let ans = 1; while(n > 0) { // calculate last bit(right most) bit of n let last_bit = n&1; // if last bit is 1 then multiply ans and a if(last_bit) { ans = ans*a; } // make a equal to square of a as on // every succeeding bit it got squared // like a^0, a^1, a^2, a^4, a^8 a = a*a; n = n >> 1; } return ans;} // driver codedocument.write(pow(3,5),\"</br>\"); // This code is contributed by shinjanpatra </script>",
"e": 11435,
"s": 10840,
"text": null
},
{
"code": null,
"e": 11461,
"s": 11435,
"text": "Time Complexity: O(log n)"
},
{
"code": null,
"e": 11483,
"s": 11461,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 11775,
"s": 11483,
"text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=OIgpvFAew6k\" 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": 11893,
"s": 11775,
"text": "Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem. "
},
{
"code": null,
"e": 11906,
"s": 11893,
"text": "nitin mittal"
},
{
"code": null,
"e": 11911,
"s": 11906,
"text": "vt_m"
},
{
"code": null,
"e": 11925,
"s": 11911,
"text": "rathbhupendra"
},
{
"code": null,
"e": 11938,
"s": 11925,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 11946,
"s": 11938,
"text": "dkp1903"
},
{
"code": null,
"e": 11957,
"s": 11946,
"text": "nidhi_biet"
},
{
"code": null,
"e": 11974,
"s": 11957,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 11988,
"s": 11974,
"text": "GauravRajput1"
},
{
"code": null,
"e": 12004,
"s": 11988,
"text": "subhammahato348"
},
{
"code": null,
"e": 12014,
"s": 12004,
"text": "subham348"
},
{
"code": null,
"e": 12028,
"s": 12014,
"text": "kkunalguptaaa"
},
{
"code": null,
"e": 12041,
"s": 12028,
"text": "shinjanpatra"
},
{
"code": null,
"e": 12053,
"s": 12041,
"text": "kashishsoda"
},
{
"code": null,
"e": 12062,
"s": 12053,
"text": "sweetyty"
},
{
"code": null,
"e": 12072,
"s": 12062,
"text": "sanjoy_62"
},
{
"code": null,
"e": 12082,
"s": 12072,
"text": "code_hunt"
},
{
"code": null,
"e": 12093,
"s": 12082,
"text": "akashish__"
},
{
"code": null,
"e": 12112,
"s": 12093,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 12125,
"s": 12112,
"text": "Mathematical"
},
{
"code": null,
"e": 12138,
"s": 12125,
"text": "Mathematical"
},
{
"code": null,
"e": 12157,
"s": 12138,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 12255,
"s": 12157,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12266,
"s": 12255,
"text": "Merge Sort"
},
{
"code": null,
"e": 12276,
"s": 12266,
"text": "QuickSort"
},
{
"code": null,
"e": 12290,
"s": 12276,
"text": "Binary Search"
},
{
"code": null,
"e": 12346,
"s": 12290,
"text": "Count Inversions in an array | Set 1 (Using Merge Sort)"
},
{
"code": null,
"e": 12393,
"s": 12346,
"text": "Median of two sorted arrays of different sizes"
},
{
"code": null,
"e": 12423,
"s": 12393,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 12466,
"s": 12423,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 12526,
"s": 12466,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 12541,
"s": 12526,
"text": "C++ Data Types"
}
] |
Python | Sentiment Analysis using VADER
|
07 Oct, 2021
Sentiment Analysis is the process of ‘computationally’ determining whether a piece of writing is positive, negative or neutral. It’s also known as opinion mining, deriving the opinion or attitude of a speaker.Why sentiment analysis?
Business: In marketing field companies use it to develop their strategies, to understand customers’ feelings towards products or brand, how people respond to their campaigns or product launches and why consumers don’t buy some products.
Politics: In the political field, it is used to keep track of political view, to detect consistency and inconsistency between statements and actions at the government level. It can be used to predict election results as well! .
Public Actions: Sentiment analysis also is used to monitor and analyse social phenomena, for the spotting of potentially dangerous situations and determining the general mood of the blogosphere.
Command to install vaderSentiment :
pip install vaderSentiment
VADER Sentiment Analysis :VADER (Valence Aware Dictionary and sEntiment Reasoner) is a lexicon and rule-based sentiment analysis tool that is specifically attuned to sentiments expressed in social media. VADER uses a combination of A sentiment lexicon is a list of lexical features (e.g., words) which are generally labeled according to their semantic orientation as either positive or negative. VADER not only tells about the Positivity and Negativity score but also tells us about how positive or negative a sentiment is.Below is the code:
Python3
# import SentimentIntensityAnalyzer class# from vaderSentiment.vaderSentiment module.from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer # function to print sentiments# of the sentence.def sentiment_scores(sentence): # Create a SentimentIntensityAnalyzer object. sid_obj = SentimentIntensityAnalyzer() # polarity_scores method of SentimentIntensityAnalyzer # object gives a sentiment dictionary. # which contains pos, neg, neu, and compound scores. sentiment_dict = sid_obj.polarity_scores(sentence) print("Overall sentiment dictionary is : ", sentiment_dict) print("sentence was rated as ", sentiment_dict['neg']*100, "% Negative") print("sentence was rated as ", sentiment_dict['neu']*100, "% Neutral") print("sentence was rated as ", sentiment_dict['pos']*100, "% Positive") print("Sentence Overall Rated As", end = " ") # decide sentiment as positive, negative and neutral if sentiment_dict['compound'] >= 0.05 : print("Positive") elif sentiment_dict['compound'] <= - 0.05 : print("Negative") else : print("Neutral") # Driver codeif __name__ == "__main__" : print("\n1st statement :") sentence = "Geeks For Geeks is the best portal for \ the computer science engineering students." # function calling sentiment_scores(sentence) print("\n2nd Statement :") sentence = "study is going on as usual" sentiment_scores(sentence) print("\n3rd Statement :") sentence = "I am very sad today." sentiment_scores(sentence)
Output :
The Compound score is a metric that calculates the sum of all the lexicon ratings which have been normalized between -1(most extreme negative) and +1 (most extreme positive).positive sentiment : (compound score >= 0.05) neutral sentiment : (compound score > -0.05) and (compound score < 0.05) negative sentiment : (compound score <= -0.05)
surinderdawra388
sumitgumber28
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 289,
"s": 54,
"text": "Sentiment Analysis is the process of ‘computationally’ determining whether a piece of writing is positive, negative or neutral. It’s also known as opinion mining, deriving the opinion or attitude of a speaker.Why sentiment analysis? "
},
{
"code": null,
"e": 528,
"s": 289,
"text": "Business: In marketing field companies use it to develop their strategies, to understand customers’ feelings towards products or brand, how people respond to their campaigns or product launches and why consumers don’t buy some products. "
},
{
"code": null,
"e": 756,
"s": 528,
"text": "Politics: In the political field, it is used to keep track of political view, to detect consistency and inconsistency between statements and actions at the government level. It can be used to predict election results as well! ."
},
{
"code": null,
"e": 953,
"s": 756,
"text": "Public Actions: Sentiment analysis also is used to monitor and analyse social phenomena, for the spotting of potentially dangerous situations and determining the general mood of the blogosphere. "
},
{
"code": null,
"e": 991,
"s": 953,
"text": "Command to install vaderSentiment : "
},
{
"code": null,
"e": 1018,
"s": 991,
"text": "pip install vaderSentiment"
},
{
"code": null,
"e": 1564,
"s": 1018,
"text": " VADER Sentiment Analysis :VADER (Valence Aware Dictionary and sEntiment Reasoner) is a lexicon and rule-based sentiment analysis tool that is specifically attuned to sentiments expressed in social media. VADER uses a combination of A sentiment lexicon is a list of lexical features (e.g., words) which are generally labeled according to their semantic orientation as either positive or negative. VADER not only tells about the Positivity and Negativity score but also tells us about how positive or negative a sentiment is.Below is the code: "
},
{
"code": null,
"e": 1572,
"s": 1564,
"text": "Python3"
},
{
"code": "# import SentimentIntensityAnalyzer class# from vaderSentiment.vaderSentiment module.from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer # function to print sentiments# of the sentence.def sentiment_scores(sentence): # Create a SentimentIntensityAnalyzer object. sid_obj = SentimentIntensityAnalyzer() # polarity_scores method of SentimentIntensityAnalyzer # object gives a sentiment dictionary. # which contains pos, neg, neu, and compound scores. sentiment_dict = sid_obj.polarity_scores(sentence) print(\"Overall sentiment dictionary is : \", sentiment_dict) print(\"sentence was rated as \", sentiment_dict['neg']*100, \"% Negative\") print(\"sentence was rated as \", sentiment_dict['neu']*100, \"% Neutral\") print(\"sentence was rated as \", sentiment_dict['pos']*100, \"% Positive\") print(\"Sentence Overall Rated As\", end = \" \") # decide sentiment as positive, negative and neutral if sentiment_dict['compound'] >= 0.05 : print(\"Positive\") elif sentiment_dict['compound'] <= - 0.05 : print(\"Negative\") else : print(\"Neutral\") # Driver codeif __name__ == \"__main__\" : print(\"\\n1st statement :\") sentence = \"Geeks For Geeks is the best portal for \\ the computer science engineering students.\" # function calling sentiment_scores(sentence) print(\"\\n2nd Statement :\") sentence = \"study is going on as usual\" sentiment_scores(sentence) print(\"\\n3rd Statement :\") sentence = \"I am very sad today.\" sentiment_scores(sentence)",
"e": 3133,
"s": 1572,
"text": null
},
{
"code": null,
"e": 3144,
"s": 3133,
"text": "Output : "
},
{
"code": null,
"e": 3485,
"s": 3144,
"text": "The Compound score is a metric that calculates the sum of all the lexicon ratings which have been normalized between -1(most extreme negative) and +1 (most extreme positive).positive sentiment : (compound score >= 0.05) neutral sentiment : (compound score > -0.05) and (compound score < 0.05) negative sentiment : (compound score <= -0.05) "
},
{
"code": null,
"e": 3502,
"s": 3485,
"text": "surinderdawra388"
},
{
"code": null,
"e": 3516,
"s": 3502,
"text": "sumitgumber28"
},
{
"code": null,
"e": 3531,
"s": 3516,
"text": "python-utility"
},
{
"code": null,
"e": 3538,
"s": 3531,
"text": "Python"
},
{
"code": null,
"e": 3636,
"s": 3538,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3678,
"s": 3636,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3700,
"s": 3678,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3726,
"s": 3700,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3758,
"s": 3726,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3787,
"s": 3758,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3814,
"s": 3787,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3835,
"s": 3814,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3871,
"s": 3835,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 3894,
"s": 3871,
"text": "Introduction To PYTHON"
}
] |
How to create footer to stay at the bottom of a Web page?
|
30 Jul, 2021
To create a footer to stay at the bottom of a web page We can fix the position of it at the bottom of the webpage so that, if you scroll down that webpage you can still view the footer from any position at the page.To make a footer fixed at the bottom of the webpage, you could use position: fixed.
Syntax:
#footer {
position:absolute;
bottom:0;
width:100%;
height:60px; /* Height of the footer */
background:#6cf;
}
Example:
<html> <head> <style> #footer { position: fixed; padding: 10px 10px 0px 10px; bottom: 0; width: 100%; /* Height of the footer*/ height: 40px; background: grey; } </style> <head> <body> <center> <div id="container"> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <div id="footer">This is a footer. This stays at the bottom of the page. </div> </div> </center> </body> <html>
Output:
CSS is the foundation of webpages, 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.
CSS-Misc
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
How to Upload Image into Database and Display it using PHP ?
Build a Survey Form using HTML and CSS
CSS | :not(:last-child):after Selector
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 353,
"s": 54,
"text": "To create a footer to stay at the bottom of a web page We can fix the position of it at the bottom of the webpage so that, if you scroll down that webpage you can still view the footer from any position at the page.To make a footer fixed at the bottom of the webpage, you could use position: fixed."
},
{
"code": null,
"e": 361,
"s": 353,
"text": "Syntax:"
},
{
"code": null,
"e": 489,
"s": 361,
"text": "#footer {\n position:absolute;\n bottom:0;\n width:100%;\n height:60px; /* Height of the footer */\n background:#6cf;\n}\n"
},
{
"code": null,
"e": 498,
"s": 489,
"text": "Example:"
},
{
"code": "<html> <head> <style> #footer { position: fixed; padding: 10px 10px 0px 10px; bottom: 0; width: 100%; /* Height of the footer*/ height: 40px; background: grey; } </style> <head> <body> <center> <div id=\"container\"> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <div id=\"footer\">This is a footer. This stays at the bottom of the page. </div> </div> </center> </body> <html>",
"e": 1565,
"s": 498,
"text": null
},
{
"code": null,
"e": 1573,
"s": 1565,
"text": "Output:"
},
{
"code": null,
"e": 1759,
"s": 1573,
"text": "CSS is the foundation of webpages, 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": 1768,
"s": 1759,
"text": "CSS-Misc"
},
{
"code": null,
"e": 1775,
"s": 1768,
"text": "Picked"
},
{
"code": null,
"e": 1779,
"s": 1775,
"text": "CSS"
},
{
"code": null,
"e": 1796,
"s": 1779,
"text": "Web Technologies"
},
{
"code": null,
"e": 1894,
"s": 1796,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1933,
"s": 1894,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 1972,
"s": 1933,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2033,
"s": 1972,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 2072,
"s": 2033,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 2111,
"s": 2072,
"text": "CSS | :not(:last-child):after Selector"
},
{
"code": null,
"e": 2144,
"s": 2111,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2205,
"s": 2144,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2248,
"s": 2205,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2320,
"s": 2248,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Node.js Process unhandledPromiseRejection Event
|
03 Nov, 2021
The process is the global object in Node.js that keeps track of and contains all the information of the particular node.js process that is executing at a particular time on the machine.
The unhandledRejection event is emitted whenever a promise rejection is not handled. NodeJS warns the console about UnhandledPromiseRejectionWarning and immediately terminates the process. The NodeJS process global has an unhandledRejection event. This event is fire when unhandledRejection occurs and no handler to handle it in the promise chain.
Syntax:
process.on("unhandledRejection", callbackfunction)
Parameters: This method takes the following two parameters.
unhandledRejection: It is the name of the emit event in the process.
callbackfunction: It is the event handler of the event.
Return Type: The return type of this method is void.
Example 1: Basic example to register an unhandledRejection listener.
index.js
// The unhandledRejection listenerprocess.on('unhandledRejection', error => { console.error('unhandledRejection', error);}); // Reject a promisePromise.reject('Invalid password');
Run index.js file using the following command:
node index.js
Output:
unhandledRejection Invalid password
Example 2: To demonstrate that the unhandledRejection listener will only execute when there is no promise rejection handler in your chain.
index.js
// The unhandledRejection listenerprocess.on('unhandledRejection', error => { // Won't execute console.error('unhandledRejection', error);}); // Reject a promisePromise.reject('Invalid password') .catch(err => console.error(err))
Run index.js file using the following command:
node index.js
Output:
Invalid password
Note: If you handle unhandledRejection with the listener or consumer function then the default warning to the console (the UnhandledPromiseRejectionWarning from the above examples) will not print to the console.
Reference: https://nodejs.org/api/process.html#process_event_unhandledrejection
simmytarika5
NodeJS-Process
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Nov, 2021"
},
{
"code": null,
"e": 214,
"s": 28,
"text": "The process is the global object in Node.js that keeps track of and contains all the information of the particular node.js process that is executing at a particular time on the machine."
},
{
"code": null,
"e": 563,
"s": 214,
"text": "The unhandledRejection event is emitted whenever a promise rejection is not handled. NodeJS warns the console about UnhandledPromiseRejectionWarning and immediately terminates the process. The NodeJS process global has an unhandledRejection event. This event is fire when unhandledRejection occurs and no handler to handle it in the promise chain. "
},
{
"code": null,
"e": 571,
"s": 563,
"text": "Syntax:"
},
{
"code": null,
"e": 622,
"s": 571,
"text": "process.on(\"unhandledRejection\", callbackfunction)"
},
{
"code": null,
"e": 682,
"s": 622,
"text": "Parameters: This method takes the following two parameters."
},
{
"code": null,
"e": 751,
"s": 682,
"text": "unhandledRejection: It is the name of the emit event in the process."
},
{
"code": null,
"e": 807,
"s": 751,
"text": "callbackfunction: It is the event handler of the event."
},
{
"code": null,
"e": 860,
"s": 807,
"text": "Return Type: The return type of this method is void."
},
{
"code": null,
"e": 930,
"s": 860,
"text": "Example 1: Basic example to register an unhandledRejection listener. "
},
{
"code": null,
"e": 939,
"s": 930,
"text": "index.js"
},
{
"code": "// The unhandledRejection listenerprocess.on('unhandledRejection', error => { console.error('unhandledRejection', error);}); // Reject a promisePromise.reject('Invalid password');",
"e": 1123,
"s": 939,
"text": null
},
{
"code": null,
"e": 1170,
"s": 1123,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 1184,
"s": 1170,
"text": "node index.js"
},
{
"code": null,
"e": 1192,
"s": 1184,
"text": "Output:"
},
{
"code": null,
"e": 1228,
"s": 1192,
"text": "unhandledRejection Invalid password"
},
{
"code": null,
"e": 1368,
"s": 1228,
"text": "Example 2: To demonstrate that the unhandledRejection listener will only execute when there is no promise rejection handler in your chain. "
},
{
"code": null,
"e": 1377,
"s": 1368,
"text": "index.js"
},
{
"code": "// The unhandledRejection listenerprocess.on('unhandledRejection', error => { // Won't execute console.error('unhandledRejection', error);}); // Reject a promisePromise.reject('Invalid password') .catch(err => console.error(err))",
"e": 1617,
"s": 1377,
"text": null
},
{
"code": null,
"e": 1664,
"s": 1617,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 1678,
"s": 1664,
"text": "node index.js"
},
{
"code": null,
"e": 1686,
"s": 1678,
"text": "Output:"
},
{
"code": null,
"e": 1703,
"s": 1686,
"text": "Invalid password"
},
{
"code": null,
"e": 1916,
"s": 1703,
"text": "Note: If you handle unhandledRejection with the listener or consumer function then the default warning to the console (the UnhandledPromiseRejectionWarning from the above examples) will not print to the console. "
},
{
"code": null,
"e": 1996,
"s": 1916,
"text": "Reference: https://nodejs.org/api/process.html#process_event_unhandledrejection"
},
{
"code": null,
"e": 2009,
"s": 1996,
"text": "simmytarika5"
},
{
"code": null,
"e": 2024,
"s": 2009,
"text": "NodeJS-Process"
},
{
"code": null,
"e": 2031,
"s": 2024,
"text": "Picked"
},
{
"code": null,
"e": 2039,
"s": 2031,
"text": "Node.js"
},
{
"code": null,
"e": 2056,
"s": 2039,
"text": "Web Technologies"
},
{
"code": null,
"e": 2154,
"s": 2056,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2186,
"s": 2154,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 2221,
"s": 2186,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 2291,
"s": 2221,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 2318,
"s": 2291,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 2343,
"s": 2318,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 2405,
"s": 2343,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2466,
"s": 2405,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2516,
"s": 2466,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2559,
"s": 2516,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Voice Assistant using python
|
13 Jun, 2022
As we know Python is a suitable language for scriptwriters and developers. Let’s write a script for Voice Assistant using Python. The query for the assistant can be manipulated as per the user’s need. Speech recognition is the process of converting audio into text. This is commonly used in voice assistants like Alexa, Siri, etc. Python provides an API called SpeechRecognition to allow us to convert audio into text for further processing. In this article, we will look at converting large or long audio files into text using the SpeechRecognition API in python.
Subprocess:- This module is used to get system subprocess details used in various commands i.e Shutdown, Sleep, etc. This module comes built-in with Python.
WolframAlpha:- It is used to compute expert-level answers using Wolfram’s algorithms, knowledgebase and AI technology. To install this module type the below command in the terminal.
pip install wolframalpha
Pyttsx3:- This module is used for the conversion of text to speech in a program it works offline. To install this module type the below command in the terminal.pip install pyttsx3
Tkinter:- This module is used for building GUI and comes inbuilt with Python. This module comes built-in with Python.
Wikipedia:- As we all know Wikipedia is a great source of knowledge just like GeeksforGeeks we have used the Wikipedia module to get information from Wikipedia or to perform a Wikipedia search. To install this module type the below command in the terminal.
pip install wikipedia
Speech Recognition:- Since we’re building an Application of voice assistant, one of the most important things in this is that your assistant recognizes your voice (means what you want to say/ ask). To install this module type the below command in the terminal.
pip install SpeechRecognition
Web browser:- To perform Web Search. This module comes built-in with Python.
Ecapture:- To capture images from your Camera. To install this module type the below command in the terminal.
pip install ecapture
Pyjokes:- Pyjokes is used for the collection of Python Jokes over the Internet. To install this module type the below command in the terminal.pip install pyjokes
Datetime:- Date and Time are used to showing Date and Time. This module comes built-in with Python.
Twilio:- Twilio is used for making calls and messages. To install this module type the below command in the terminal.
pip install twilio
Requests: Requests is used for making GET and POST requests. To install this module type the below command in the terminal.pip install requests
BeautifulSoup: Beautiful Soup is a library that makes it easy to scrape information from web pages. To install this module type the below command in the terminal.
pip install beautifulsoup4
Note: You can remove some of the import files if you don’t want to get that feature as here Twilio for making calls and messages if you don’t want to use that you can simply remove that function.
Python3
import subprocessimport wolframalphaimport pyttsx3import tkinterimport jsonimport randomimport operatorimport speech_recognition as srimport datetimeimport wikipediaimport webbrowserimport osimport winshellimport pyjokesimport feedparserimport smtplibimport ctypesimport timeimport requestsimport shutilfrom twilio.rest import Clientfrom clint.textui import progressfrom ecapture import ecapture as ecfrom bs4 import BeautifulSoupimport win32com.client as winclfrom urllib.request import urlopen
Now we will set our engine to Pyttsx3 which is used for text to speech in Python and sapi5 is a Microsoft speech application platform interface we will be using this for text to speech function.
Python3
engine = pyttsx3.init('sapi5')voices = engine.getProperty('voices')engine.setProperty('voice', voices[1].id)
You can change the voice Id to “0” for the Male voice while using assistant here we are using a Female voice for all text to speech
Python3
def speak(audio): engine.say(audio) engine.runAndWait() def wishMe(): hour = int(datetime.datetime.now().hour) if hour>= 0 and hour<12: speak("Good Morning Sir !") elif hour>= 12 and hour<18: speak("Good Afternoon Sir !") else: speak("Good Evening Sir !") assname =("Jarvis 1 point o") speak("I am your Assistant") speak(assname) def username(): speak("What should i call you sir") uname = takeCommand() speak("Welcome Mister") speak(uname) columns = shutil.get_terminal_size().columns print("#####################".center(columns)) print("Welcome Mr.", uname.center(columns)) print("#####################".center(columns)) speak("How can i Help you, Sir") def takeCommand(): r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 audio = r.listen(source) try: print("Recognizing...") query = r.recognize_google(audio, language ='en-in') print(f"User said: {query}\n") except Exception as e: print(e) print("Unable to Recognize your voice.") return "None" return query def sendEmail(to, content): server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() # Enable low security in gmail server.login('your email id', 'your email password') server.sendmail('your email id', to, content) server.close()
Main Function starts here, we will now call all these functions in the main function.
Python3
if __name__ == '__main__': clear = lambda: os.system('cls') # This Function will clean any # command before execution of this python file clear() wishMe() username() while True: query = takeCommand().lower() # All the commands said by user will be # stored here in 'query' and will be # converted to lower case for easily # recognition of command if 'wikipedia' in query: speak('Searching Wikipedia...') query = query.replace("wikipedia", "") results = wikipedia.summary(query, sentences = 3) speak("According to Wikipedia") print(results) speak(results) elif 'open youtube' in query: speak("Here you go to Youtube\n") webbrowser.open("youtube.com") elif 'open google' in query: speak("Here you go to Google\n") webbrowser.open("google.com") elif 'open stackoverflow' in query: speak("Here you go to Stack Over flow.Happy coding") webbrowser.open("stackoverflow.com") elif 'play music' in query or "play song" in query: speak("Here you go with music") # music_dir = "G:\\Song" music_dir = "C:\\Users\\GAURAV\\Music" songs = os.listdir(music_dir) print(songs) random = os.startfile(os.path.join(music_dir, songs[1])) elif 'the time' in query: strTime = datetime.datetime.now().strftime("% H:% M:% S") speak(f"Sir, the time is {strTime}") elif 'open opera' in query: codePath = r"C:\\Users\\GAURAV\\AppData\\Local\\Programs\\Opera\\launcher.exe" os.startfile(codePath) elif 'email to gaurav' in query: try: speak("What should I say?") content = takeCommand() to = "Receiver email address" sendEmail(to, content) speak("Email has been sent !") except Exception as e: print(e) speak("I am not able to send this email") elif 'send a mail' in query: try: speak("What should I say?") content = takeCommand() speak("whome should i send") to = input() sendEmail(to, content) speak("Email has been sent !") except Exception as e: print(e) speak("I am not able to send this email") elif 'how are you' in query: speak("I am fine, Thank you") speak("How are you, Sir") elif 'fine' in query or "good" in query: speak("It's good to know that your fine") elif "change my name to" in query: query = query.replace("change my name to", "") assname = query elif "change name" in query: speak("What would you like to call me, Sir ") assname = takeCommand() speak("Thanks for naming me") elif "what's your name" in query or "What is your name" in query: speak("My friends call me") speak(assname) print("My friends call me", assname) elif 'exit' in query: speak("Thanks for giving me your time") exit() elif "who made you" in query or "who created you" in query: speak("I have been created by Gaurav.") elif 'joke' in query: speak(pyjokes.get_joke()) elif "calculate" in query: app_id = "Wolframalpha api id" client = wolframalpha.Client(app_id) indx = query.lower().split().index('calculate') query = query.split()[indx + 1:] res = client.query(' '.join(query)) answer = next(res.results).text print("The answer is " + answer) speak("The answer is " + answer) elif 'search' in query or 'play' in query: query = query.replace("search", "") query = query.replace("play", "") webbrowser.open(query) elif "who i am" in query: speak("If you talk then definitely your human.") elif "why you came to world" in query: speak("Thanks to Gaurav. further It's a secret") elif 'power point presentation' in query: speak("opening Power Point presentation") power = r"C:\\Users\\GAURAV\\Desktop\\Minor Project\\Presentation\\Voice Assistant.pptx" os.startfile(power) elif 'is love' in query: speak("It is 7th sense that destroy all other senses") elif "who are you" in query: speak("I am your virtual assistant created by Gaurav") elif 'reason for you' in query: speak("I was created as a Minor project by Mister Gaurav ") elif 'change background' in query: ctypes.windll.user32.SystemParametersInfoW(20, 0, "Location of wallpaper", 0) speak("Background changed successfully") elif 'open bluestack' in query: appli = r"C:\\ProgramData\\BlueStacks\\Client\\Bluestacks.exe" os.startfile(appli) elif 'news' in query: try: jsonObj = urlopen('''https://newsapi.org / v1 / articles?source = the-times-of-india&sortBy = top&apiKey =\\times of India Api key\\''') data = json.load(jsonObj) i = 1 speak('here are some top news from the times of india') print('''=============== TIMES OF INDIA ============'''+ '\n') for item in data['articles']: print(str(i) + '. ' + item['title'] + '\n') print(item['description'] + '\n') speak(str(i) + '. ' + item['title'] + '\n') i += 1 except Exception as e: print(str(e)) elif 'lock window' in query: speak("locking the device") ctypes.windll.user32.LockWorkStation() elif 'shutdown system' in query: speak("Hold On a Sec ! Your system is on its way to shut down") subprocess.call('shutdown / p /f') elif 'empty recycle bin' in query: winshell.recycle_bin().empty(confirm = False, show_progress = False, sound = True) speak("Recycle Bin Recycled") elif "don't listen" in query or "stop listening" in query: speak("for how much time you want to stop jarvis from listening commands") a = int(takeCommand()) time.sleep(a) print(a) elif "where is" in query: query = query.replace("where is", "") location = query speak("User asked to Locate") speak(location) webbrowser.open("https://www.google.nl / maps / place/" + location + "") elif "camera" in query or "take a photo" in query: ec.capture(0, "Jarvis Camera ", "img.jpg") elif "restart" in query: subprocess.call(["shutdown", "/r"]) elif "hibernate" in query or "sleep" in query: speak("Hibernating") subprocess.call("shutdown / h") elif "log off" in query or "sign out" in query: speak("Make sure all the application are closed before sign-out") time.sleep(5) subprocess.call(["shutdown", "/l"]) elif "write a note" in query: speak("What should i write, sir") note = takeCommand() file = open('jarvis.txt', 'w') speak("Sir, Should i include date and time") snfm = takeCommand() if 'yes' in snfm or 'sure' in snfm: strTime = datetime.datetime.now().strftime("% H:% M:% S") file.write(strTime) file.write(" :- ") file.write(note) else: file.write(note) elif "show note" in query: speak("Showing Notes") file = open("jarvis.txt", "r") print(file.read()) speak(file.read(6)) elif "update assistant" in query: speak("After downloading file please replace this file with the downloaded one") url = '# url after uploading file' r = requests.get(url, stream = True) with open("Voice.py", "wb") as Pypdf: total_length = int(r.headers.get('content-length')) for ch in progress.bar(r.iter_content(chunk_size = 2391975), expected_size =(total_length / 1024) + 1): if ch: Pypdf.write(ch) # NPPR9-FWDCX-D2C8J-H872K-2YT43 elif "jarvis" in query: wishMe() speak("Jarvis 1 point o in your service Mister") speak(assname) elif "weather" in query: # Google Open weather website # to get API of Open weather api_key = "Api key" base_url = "http://api.openweathermap.org / data / 2.5 / weather?" speak(" City name ") print("City name : ") city_name = takeCommand() complete_url = base_url + "appid =" + api_key + "&q =" + city_name response = requests.get(complete_url) x = response.json() if x["cod"] != "404": y = x["main"] current_temperature = y["temp"] current_pressure = y["pressure"] current_humidiy = y["humidity"] z = x["weather"] weather_description = z[0]["description"] print(" Temperature (in kelvin unit) = " +str(current_temperature)+"\n atmospheric pressure (in hPa unit) ="+str(current_pressure) +"\n humidity (in percentage) = " +str(current_humidiy) +"\n description = " +str(weather_description)) else: speak(" City Not Found ") elif "send message " in query: # You need to create an account on Twilio to use this service account_sid = 'Account Sid key' auth_token = 'Auth token' client = Client(account_sid, auth_token) message = client.messages \ .create( body = takeCommand(), from_='Sender No', to ='Receiver No' ) print(message.sid) elif "wikipedia" in query: webbrowser.open("wikipedia.com") elif "Good Morning" in query: speak("A warm" +query) speak("How are you Mister") speak(assname) # most asked question from google Assistant elif "will you be my gf" in query or "will you be my bf" in query: speak("I'm not sure about, may be you should give me some time") elif "how are you" in query: speak("I'm fine, glad you me that") elif "i love you" in query: speak("It's hard to understand") elif "what is" in query or "who is" in query: # Use the same API key # that we have generated earlier client = wolframalpha.Client("API_ID") res = client.query(query) try: print (next(res.results).text) speak (next(res.results).text) except StopIteration: print ("No results") # elif "" in query: # Command go here # For adding more commands
Output:
Listening... Recognizing... User said: Gaurav##################### Welcome Mr. Gaurav ##################### Listening... Recognizing... User said: yes(‘As the history majors among you here today know all too well, when people in power invent their own facts and attack those who question them, it can mark the beginning of the end of a free society. That is not hyperbole. It is what authoritarian regimes throughout history have done. They attempt to control reality. Not just our laws and our rights and our budgets, but our thoughts and beliefs.’, ‘Hillary Clinton’) Listening... Recognizing... User said: Gaurav in WikipediaGaurav is an Indian and Nepalese male name. The name literally means pride.== Notable people named Gaurav == Gaurav S Bajaj, Indian television actor Gaurav Bhatt, Indian Music Director, singer, songwriter. Listening... Recognizing... User said: open YouTubeListening... Recognizing...Unable to Recognizing your voice. Listening... Recognizing... User said: exit
nsarvajith007
simranarora5sos
clintra
ruhelaa48
kashishsoda
germanshephered48
subrat1729
sachinchatterjee31796
Python-projects
python-utility
Technical Scripter 2019
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 620,
"s": 54,
"text": "As we know Python is a suitable language for scriptwriters and developers. Let’s write a script for Voice Assistant using Python. The query for the assistant can be manipulated as per the user’s need. Speech recognition is the process of converting audio into text. This is commonly used in voice assistants like Alexa, Siri, etc. Python provides an API called SpeechRecognition to allow us to convert audio into text for further processing. In this article, we will look at converting large or long audio files into text using the SpeechRecognition API in python. "
},
{
"code": null,
"e": 779,
"s": 620,
"text": "Subprocess:- This module is used to get system subprocess details used in various commands i.e Shutdown, Sleep, etc. This module comes built-in with Python. "
},
{
"code": null,
"e": 961,
"s": 779,
"text": "WolframAlpha:- It is used to compute expert-level answers using Wolfram’s algorithms, knowledgebase and AI technology. To install this module type the below command in the terminal."
},
{
"code": null,
"e": 986,
"s": 961,
"text": "pip install wolframalpha"
},
{
"code": null,
"e": 1167,
"s": 986,
"text": "Pyttsx3:- This module is used for the conversion of text to speech in a program it works offline. To install this module type the below command in the terminal.pip install pyttsx3 "
},
{
"code": null,
"e": 1287,
"s": 1167,
"text": "Tkinter:- This module is used for building GUI and comes inbuilt with Python. This module comes built-in with Python. "
},
{
"code": null,
"e": 1544,
"s": 1287,
"text": "Wikipedia:- As we all know Wikipedia is a great source of knowledge just like GeeksforGeeks we have used the Wikipedia module to get information from Wikipedia or to perform a Wikipedia search. To install this module type the below command in the terminal."
},
{
"code": null,
"e": 1566,
"s": 1544,
"text": "pip install wikipedia"
},
{
"code": null,
"e": 1827,
"s": 1566,
"text": "Speech Recognition:- Since we’re building an Application of voice assistant, one of the most important things in this is that your assistant recognizes your voice (means what you want to say/ ask). To install this module type the below command in the terminal."
},
{
"code": null,
"e": 1857,
"s": 1827,
"text": "pip install SpeechRecognition"
},
{
"code": null,
"e": 1936,
"s": 1857,
"text": "Web browser:- To perform Web Search. This module comes built-in with Python. "
},
{
"code": null,
"e": 2046,
"s": 1936,
"text": "Ecapture:- To capture images from your Camera. To install this module type the below command in the terminal."
},
{
"code": null,
"e": 2067,
"s": 2046,
"text": "pip install ecapture"
},
{
"code": null,
"e": 2230,
"s": 2067,
"text": "Pyjokes:- Pyjokes is used for the collection of Python Jokes over the Internet. To install this module type the below command in the terminal.pip install pyjokes "
},
{
"code": null,
"e": 2332,
"s": 2230,
"text": "Datetime:- Date and Time are used to showing Date and Time. This module comes built-in with Python. "
},
{
"code": null,
"e": 2450,
"s": 2332,
"text": "Twilio:- Twilio is used for making calls and messages. To install this module type the below command in the terminal."
},
{
"code": null,
"e": 2469,
"s": 2450,
"text": "pip install twilio"
},
{
"code": null,
"e": 2615,
"s": 2469,
"text": "Requests: Requests is used for making GET and POST requests. To install this module type the below command in the terminal.pip install requests "
},
{
"code": null,
"e": 2778,
"s": 2615,
"text": "BeautifulSoup: Beautiful Soup is a library that makes it easy to scrape information from web pages. To install this module type the below command in the terminal."
},
{
"code": null,
"e": 2805,
"s": 2778,
"text": "pip install beautifulsoup4"
},
{
"code": null,
"e": 3002,
"s": 2805,
"text": "Note: You can remove some of the import files if you don’t want to get that feature as here Twilio for making calls and messages if you don’t want to use that you can simply remove that function. "
},
{
"code": null,
"e": 3010,
"s": 3002,
"text": "Python3"
},
{
"code": "import subprocessimport wolframalphaimport pyttsx3import tkinterimport jsonimport randomimport operatorimport speech_recognition as srimport datetimeimport wikipediaimport webbrowserimport osimport winshellimport pyjokesimport feedparserimport smtplibimport ctypesimport timeimport requestsimport shutilfrom twilio.rest import Clientfrom clint.textui import progressfrom ecapture import ecapture as ecfrom bs4 import BeautifulSoupimport win32com.client as winclfrom urllib.request import urlopen",
"e": 3506,
"s": 3010,
"text": null
},
{
"code": null,
"e": 3702,
"s": 3506,
"text": "Now we will set our engine to Pyttsx3 which is used for text to speech in Python and sapi5 is a Microsoft speech application platform interface we will be using this for text to speech function. "
},
{
"code": null,
"e": 3710,
"s": 3702,
"text": "Python3"
},
{
"code": "engine = pyttsx3.init('sapi5')voices = engine.getProperty('voices')engine.setProperty('voice', voices[1].id)",
"e": 3819,
"s": 3710,
"text": null
},
{
"code": null,
"e": 3952,
"s": 3819,
"text": "You can change the voice Id to “0” for the Male voice while using assistant here we are using a Female voice for all text to speech "
},
{
"code": null,
"e": 3960,
"s": 3952,
"text": "Python3"
},
{
"code": "def speak(audio): engine.say(audio) engine.runAndWait() def wishMe(): hour = int(datetime.datetime.now().hour) if hour>= 0 and hour<12: speak(\"Good Morning Sir !\") elif hour>= 12 and hour<18: speak(\"Good Afternoon Sir !\") else: speak(\"Good Evening Sir !\") assname =(\"Jarvis 1 point o\") speak(\"I am your Assistant\") speak(assname) def username(): speak(\"What should i call you sir\") uname = takeCommand() speak(\"Welcome Mister\") speak(uname) columns = shutil.get_terminal_size().columns print(\"#####################\".center(columns)) print(\"Welcome Mr.\", uname.center(columns)) print(\"#####################\".center(columns)) speak(\"How can i Help you, Sir\") def takeCommand(): r = sr.Recognizer() with sr.Microphone() as source: print(\"Listening...\") r.pause_threshold = 1 audio = r.listen(source) try: print(\"Recognizing...\") query = r.recognize_google(audio, language ='en-in') print(f\"User said: {query}\\n\") except Exception as e: print(e) print(\"Unable to Recognize your voice.\") return \"None\" return query def sendEmail(to, content): server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() # Enable low security in gmail server.login('your email id', 'your email password') server.sendmail('your email id', to, content) server.close()",
"e": 5459,
"s": 3960,
"text": null
},
{
"code": null,
"e": 5546,
"s": 5459,
"text": "Main Function starts here, we will now call all these functions in the main function. "
},
{
"code": null,
"e": 5554,
"s": 5546,
"text": "Python3"
},
{
"code": "if __name__ == '__main__': clear = lambda: os.system('cls') # This Function will clean any # command before execution of this python file clear() wishMe() username() while True: query = takeCommand().lower() # All the commands said by user will be # stored here in 'query' and will be # converted to lower case for easily # recognition of command if 'wikipedia' in query: speak('Searching Wikipedia...') query = query.replace(\"wikipedia\", \"\") results = wikipedia.summary(query, sentences = 3) speak(\"According to Wikipedia\") print(results) speak(results) elif 'open youtube' in query: speak(\"Here you go to Youtube\\n\") webbrowser.open(\"youtube.com\") elif 'open google' in query: speak(\"Here you go to Google\\n\") webbrowser.open(\"google.com\") elif 'open stackoverflow' in query: speak(\"Here you go to Stack Over flow.Happy coding\") webbrowser.open(\"stackoverflow.com\") elif 'play music' in query or \"play song\" in query: speak(\"Here you go with music\") # music_dir = \"G:\\\\Song\" music_dir = \"C:\\\\Users\\\\GAURAV\\\\Music\" songs = os.listdir(music_dir) print(songs) random = os.startfile(os.path.join(music_dir, songs[1])) elif 'the time' in query: strTime = datetime.datetime.now().strftime(\"% H:% M:% S\") speak(f\"Sir, the time is {strTime}\") elif 'open opera' in query: codePath = r\"C:\\\\Users\\\\GAURAV\\\\AppData\\\\Local\\\\Programs\\\\Opera\\\\launcher.exe\" os.startfile(codePath) elif 'email to gaurav' in query: try: speak(\"What should I say?\") content = takeCommand() to = \"Receiver email address\" sendEmail(to, content) speak(\"Email has been sent !\") except Exception as e: print(e) speak(\"I am not able to send this email\") elif 'send a mail' in query: try: speak(\"What should I say?\") content = takeCommand() speak(\"whome should i send\") to = input() sendEmail(to, content) speak(\"Email has been sent !\") except Exception as e: print(e) speak(\"I am not able to send this email\") elif 'how are you' in query: speak(\"I am fine, Thank you\") speak(\"How are you, Sir\") elif 'fine' in query or \"good\" in query: speak(\"It's good to know that your fine\") elif \"change my name to\" in query: query = query.replace(\"change my name to\", \"\") assname = query elif \"change name\" in query: speak(\"What would you like to call me, Sir \") assname = takeCommand() speak(\"Thanks for naming me\") elif \"what's your name\" in query or \"What is your name\" in query: speak(\"My friends call me\") speak(assname) print(\"My friends call me\", assname) elif 'exit' in query: speak(\"Thanks for giving me your time\") exit() elif \"who made you\" in query or \"who created you\" in query: speak(\"I have been created by Gaurav.\") elif 'joke' in query: speak(pyjokes.get_joke()) elif \"calculate\" in query: app_id = \"Wolframalpha api id\" client = wolframalpha.Client(app_id) indx = query.lower().split().index('calculate') query = query.split()[indx + 1:] res = client.query(' '.join(query)) answer = next(res.results).text print(\"The answer is \" + answer) speak(\"The answer is \" + answer) elif 'search' in query or 'play' in query: query = query.replace(\"search\", \"\") query = query.replace(\"play\", \"\") webbrowser.open(query) elif \"who i am\" in query: speak(\"If you talk then definitely your human.\") elif \"why you came to world\" in query: speak(\"Thanks to Gaurav. further It's a secret\") elif 'power point presentation' in query: speak(\"opening Power Point presentation\") power = r\"C:\\\\Users\\\\GAURAV\\\\Desktop\\\\Minor Project\\\\Presentation\\\\Voice Assistant.pptx\" os.startfile(power) elif 'is love' in query: speak(\"It is 7th sense that destroy all other senses\") elif \"who are you\" in query: speak(\"I am your virtual assistant created by Gaurav\") elif 'reason for you' in query: speak(\"I was created as a Minor project by Mister Gaurav \") elif 'change background' in query: ctypes.windll.user32.SystemParametersInfoW(20, 0, \"Location of wallpaper\", 0) speak(\"Background changed successfully\") elif 'open bluestack' in query: appli = r\"C:\\\\ProgramData\\\\BlueStacks\\\\Client\\\\Bluestacks.exe\" os.startfile(appli) elif 'news' in query: try: jsonObj = urlopen('''https://newsapi.org / v1 / articles?source = the-times-of-india&sortBy = top&apiKey =\\\\times of India Api key\\\\''') data = json.load(jsonObj) i = 1 speak('here are some top news from the times of india') print('''=============== TIMES OF INDIA ============'''+ '\\n') for item in data['articles']: print(str(i) + '. ' + item['title'] + '\\n') print(item['description'] + '\\n') speak(str(i) + '. ' + item['title'] + '\\n') i += 1 except Exception as e: print(str(e)) elif 'lock window' in query: speak(\"locking the device\") ctypes.windll.user32.LockWorkStation() elif 'shutdown system' in query: speak(\"Hold On a Sec ! Your system is on its way to shut down\") subprocess.call('shutdown / p /f') elif 'empty recycle bin' in query: winshell.recycle_bin().empty(confirm = False, show_progress = False, sound = True) speak(\"Recycle Bin Recycled\") elif \"don't listen\" in query or \"stop listening\" in query: speak(\"for how much time you want to stop jarvis from listening commands\") a = int(takeCommand()) time.sleep(a) print(a) elif \"where is\" in query: query = query.replace(\"where is\", \"\") location = query speak(\"User asked to Locate\") speak(location) webbrowser.open(\"https://www.google.nl / maps / place/\" + location + \"\") elif \"camera\" in query or \"take a photo\" in query: ec.capture(0, \"Jarvis Camera \", \"img.jpg\") elif \"restart\" in query: subprocess.call([\"shutdown\", \"/r\"]) elif \"hibernate\" in query or \"sleep\" in query: speak(\"Hibernating\") subprocess.call(\"shutdown / h\") elif \"log off\" in query or \"sign out\" in query: speak(\"Make sure all the application are closed before sign-out\") time.sleep(5) subprocess.call([\"shutdown\", \"/l\"]) elif \"write a note\" in query: speak(\"What should i write, sir\") note = takeCommand() file = open('jarvis.txt', 'w') speak(\"Sir, Should i include date and time\") snfm = takeCommand() if 'yes' in snfm or 'sure' in snfm: strTime = datetime.datetime.now().strftime(\"% H:% M:% S\") file.write(strTime) file.write(\" :- \") file.write(note) else: file.write(note) elif \"show note\" in query: speak(\"Showing Notes\") file = open(\"jarvis.txt\", \"r\") print(file.read()) speak(file.read(6)) elif \"update assistant\" in query: speak(\"After downloading file please replace this file with the downloaded one\") url = '# url after uploading file' r = requests.get(url, stream = True) with open(\"Voice.py\", \"wb\") as Pypdf: total_length = int(r.headers.get('content-length')) for ch in progress.bar(r.iter_content(chunk_size = 2391975), expected_size =(total_length / 1024) + 1): if ch: Pypdf.write(ch) # NPPR9-FWDCX-D2C8J-H872K-2YT43 elif \"jarvis\" in query: wishMe() speak(\"Jarvis 1 point o in your service Mister\") speak(assname) elif \"weather\" in query: # Google Open weather website # to get API of Open weather api_key = \"Api key\" base_url = \"http://api.openweathermap.org / data / 2.5 / weather?\" speak(\" City name \") print(\"City name : \") city_name = takeCommand() complete_url = base_url + \"appid =\" + api_key + \"&q =\" + city_name response = requests.get(complete_url) x = response.json() if x[\"cod\"] != \"404\": y = x[\"main\"] current_temperature = y[\"temp\"] current_pressure = y[\"pressure\"] current_humidiy = y[\"humidity\"] z = x[\"weather\"] weather_description = z[0][\"description\"] print(\" Temperature (in kelvin unit) = \" +str(current_temperature)+\"\\n atmospheric pressure (in hPa unit) =\"+str(current_pressure) +\"\\n humidity (in percentage) = \" +str(current_humidiy) +\"\\n description = \" +str(weather_description)) else: speak(\" City Not Found \") elif \"send message \" in query: # You need to create an account on Twilio to use this service account_sid = 'Account Sid key' auth_token = 'Auth token' client = Client(account_sid, auth_token) message = client.messages \\ .create( body = takeCommand(), from_='Sender No', to ='Receiver No' ) print(message.sid) elif \"wikipedia\" in query: webbrowser.open(\"wikipedia.com\") elif \"Good Morning\" in query: speak(\"A warm\" +query) speak(\"How are you Mister\") speak(assname) # most asked question from google Assistant elif \"will you be my gf\" in query or \"will you be my bf\" in query: speak(\"I'm not sure about, may be you should give me some time\") elif \"how are you\" in query: speak(\"I'm fine, glad you me that\") elif \"i love you\" in query: speak(\"It's hard to understand\") elif \"what is\" in query or \"who is\" in query: # Use the same API key # that we have generated earlier client = wolframalpha.Client(\"API_ID\") res = client.query(query) try: print (next(res.results).text) speak (next(res.results).text) except StopIteration: print (\"No results\") # elif \"\" in query: # Command go here # For adding more commands",
"e": 17650,
"s": 5554,
"text": null
},
{
"code": null,
"e": 17659,
"s": 17650,
"text": "Output: "
},
{
"code": null,
"e": 18651,
"s": 17659,
"text": "Listening... Recognizing... User said: Gaurav##################### Welcome Mr. Gaurav ##################### Listening... Recognizing... User said: yes(‘As the history majors among you here today know all too well, when people in power invent their own facts and attack those who question them, it can mark the beginning of the end of a free society. That is not hyperbole. It is what authoritarian regimes throughout history have done. They attempt to control reality. Not just our laws and our rights and our budgets, but our thoughts and beliefs.’, ‘Hillary Clinton’) Listening... Recognizing... User said: Gaurav in WikipediaGaurav is an Indian and Nepalese male name. The name literally means pride.== Notable people named Gaurav == Gaurav S Bajaj, Indian television actor Gaurav Bhatt, Indian Music Director, singer, songwriter. Listening... Recognizing... User said: open YouTubeListening... Recognizing...Unable to Recognizing your voice. Listening... Recognizing... User said: exit "
},
{
"code": null,
"e": 18667,
"s": 18653,
"text": "nsarvajith007"
},
{
"code": null,
"e": 18683,
"s": 18667,
"text": "simranarora5sos"
},
{
"code": null,
"e": 18691,
"s": 18683,
"text": "clintra"
},
{
"code": null,
"e": 18701,
"s": 18691,
"text": "ruhelaa48"
},
{
"code": null,
"e": 18713,
"s": 18701,
"text": "kashishsoda"
},
{
"code": null,
"e": 18731,
"s": 18713,
"text": "germanshephered48"
},
{
"code": null,
"e": 18742,
"s": 18731,
"text": "subrat1729"
},
{
"code": null,
"e": 18764,
"s": 18742,
"text": "sachinchatterjee31796"
},
{
"code": null,
"e": 18780,
"s": 18764,
"text": "Python-projects"
},
{
"code": null,
"e": 18795,
"s": 18780,
"text": "python-utility"
},
{
"code": null,
"e": 18819,
"s": 18795,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 18826,
"s": 18819,
"text": "Python"
},
{
"code": null,
"e": 18845,
"s": 18826,
"text": "Technical Scripter"
},
{
"code": null,
"e": 18943,
"s": 18845,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 18961,
"s": 18943,
"text": "Python Dictionary"
},
{
"code": null,
"e": 19003,
"s": 18961,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 19025,
"s": 19003,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 19060,
"s": 19025,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 19086,
"s": 19060,
"text": "Python String | replace()"
},
{
"code": null,
"e": 19118,
"s": 19086,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 19147,
"s": 19118,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 19174,
"s": 19147,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 19204,
"s": 19174,
"text": "Iterate over a list in Python"
}
] |
How to create a Queue in C#
|
18 Feb, 2019
Queue() Constructor is used to initializes a new instance of the Queue class which will be empty, and will have the default initial capacity, and uses the default growth factor. Queue represents a first-in, first out collection of object. It is used when you need first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called dequeue. This class comes under System.Collections namespace and implements ICollection, IEnumerable, and ICloneable interfaces.
Syntax:
public Queue ();
Important Points:
The capacity of the Queue represents the number of elements that the Queue can hold. It will increase automatically through reallocation as elements are added to it.
TrimToSize method is used to decreased the capacity of the Queue.
When a greater capacity is required then the current capacity is multiplied by a number which is termed as the growth factor.
This constructor is an O(1) operation.
Example 1:
// C# Program to illustrate how// to create a Queueusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // qt is the Queue object // Queue() is the constructor // used to initializes a new // instance of the Queue class Queue qt = new Queue(); // Count property is used to get the // number of elements in Queue // It will give 0 as no elements // are present currently Console.WriteLine(qt.Count); }}
0
Example 2:
// C# Program to illustrate how// to create a Queueusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // qt is the Queue object // Queue() is the constructor // used to initializes a new // instance of the Queue class Queue qt = new Queue(); Console.Write("Before Enqueue Method: "); // Count property is used to get the // number of elements in Queue // It will give 0 as no elements // are present currently Console.WriteLine(qt.Count); // Inserting the elements // into the Queue qt.Enqueue("This"); qt.Enqueue("is"); qt.Enqueue("how"); qt.Enqueue("to"); qt.Enqueue("create"); qt.Enqueue("Queue"); qt.Enqueue("in"); qt.Enqueue("C#"); Console.Write("After Enqueue Method: "); // Count property is used to get the // number of elements in qt Console.WriteLine(qt.Count); }}
Before Enqueue Method: 0
After Enqueue Method: 8
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue.-ctor?view=netframework-4.7.2#System_Collections_Queue__ctor
CSharp-Collections-Namespace
CSharp-Collections-Queue
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
C# Dictionary with examples
C# | How to check whether a List contains a specified element
C# | Arrays of Strings
C# | IsNullOrEmpty() Method
String.Split() Method in C# with Examples
Introduction to .NET Framework
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Feb, 2019"
},
{
"code": null,
"e": 556,
"s": 28,
"text": "Queue() Constructor is used to initializes a new instance of the Queue class which will be empty, and will have the default initial capacity, and uses the default growth factor. Queue represents a first-in, first out collection of object. It is used when you need first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called dequeue. This class comes under System.Collections namespace and implements ICollection, IEnumerable, and ICloneable interfaces."
},
{
"code": null,
"e": 564,
"s": 556,
"text": "Syntax:"
},
{
"code": null,
"e": 581,
"s": 564,
"text": "public Queue ();"
},
{
"code": null,
"e": 599,
"s": 581,
"text": "Important Points:"
},
{
"code": null,
"e": 765,
"s": 599,
"text": "The capacity of the Queue represents the number of elements that the Queue can hold. It will increase automatically through reallocation as elements are added to it."
},
{
"code": null,
"e": 831,
"s": 765,
"text": "TrimToSize method is used to decreased the capacity of the Queue."
},
{
"code": null,
"e": 957,
"s": 831,
"text": "When a greater capacity is required then the current capacity is multiplied by a number which is termed as the growth factor."
},
{
"code": null,
"e": 996,
"s": 957,
"text": "This constructor is an O(1) operation."
},
{
"code": null,
"e": 1007,
"s": 996,
"text": "Example 1:"
},
{
"code": "// C# Program to illustrate how// to create a Queueusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // qt is the Queue object // Queue() is the constructor // used to initializes a new // instance of the Queue class Queue qt = new Queue(); // Count property is used to get the // number of elements in Queue // It will give 0 as no elements // are present currently Console.WriteLine(qt.Count); }}",
"e": 1556,
"s": 1007,
"text": null
},
{
"code": null,
"e": 1559,
"s": 1556,
"text": "0\n"
},
{
"code": null,
"e": 1570,
"s": 1559,
"text": "Example 2:"
},
{
"code": "// C# Program to illustrate how// to create a Queueusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // qt is the Queue object // Queue() is the constructor // used to initializes a new // instance of the Queue class Queue qt = new Queue(); Console.Write(\"Before Enqueue Method: \"); // Count property is used to get the // number of elements in Queue // It will give 0 as no elements // are present currently Console.WriteLine(qt.Count); // Inserting the elements // into the Queue qt.Enqueue(\"This\"); qt.Enqueue(\"is\"); qt.Enqueue(\"how\"); qt.Enqueue(\"to\"); qt.Enqueue(\"create\"); qt.Enqueue(\"Queue\"); qt.Enqueue(\"in\"); qt.Enqueue(\"C#\"); Console.Write(\"After Enqueue Method: \"); // Count property is used to get the // number of elements in qt Console.WriteLine(qt.Count); }}",
"e": 2623,
"s": 1570,
"text": null
},
{
"code": null,
"e": 2673,
"s": 2623,
"text": "Before Enqueue Method: 0\nAfter Enqueue Method: 8\n"
},
{
"code": null,
"e": 2684,
"s": 2673,
"text": "Reference:"
},
{
"code": null,
"e": 2814,
"s": 2684,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue.-ctor?view=netframework-4.7.2#System_Collections_Queue__ctor"
},
{
"code": null,
"e": 2843,
"s": 2814,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 2868,
"s": 2843,
"text": "CSharp-Collections-Queue"
},
{
"code": null,
"e": 2871,
"s": 2868,
"text": "C#"
},
{
"code": null,
"e": 2969,
"s": 2871,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3023,
"s": 2969,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 3051,
"s": 3023,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 3113,
"s": 3051,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 3136,
"s": 3113,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 3164,
"s": 3136,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 3206,
"s": 3164,
"text": "String.Split() Method in C# with Examples"
},
{
"code": null,
"e": 3237,
"s": 3206,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 3252,
"s": 3237,
"text": "C# | Delegates"
},
{
"code": null,
"e": 3295,
"s": 3252,
"text": "C# | Multiple inheritance using interfaces"
}
] |
C fopen() function with Examples
|
04 Sep, 2021
Pre-requisite: Basics of File Handling in CThe fopen() method in C is a library function that is used to open a file to perform various operations which include reading, writing etc. along with various modes. If the file exists then the particular file is opened else a new file is created.
Syntax:
FILE *fopen(const char *file_name, const char *mode_of_operation);
Parameters: The method accepts two parameters of character type:
file_name: This is of C string type and accepts the name of the file that is needed to be opened.mode_of_operation: This is also of C string type and refers to the mode of the file access. Below are the file access modes for C: “r” – Searches file. Opens the file for reading only. If the file is opened successfully fopen() loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen() returns NULL.“w” – Searches file. If the file exists already, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. It creates a new file for writing only(no reading).“a” – Searches file. If the file is opened successfully fopen() loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened only for appending(writing at end of file).“r+” – Searches file. Opens the file for both reading and writing. If opened successfully, fopen() loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file.“w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The difference between w and w+ is that we can also read the file created using w+.“a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened for reading and appending(writing at end of file).
file_name: This is of C string type and accepts the name of the file that is needed to be opened.
mode_of_operation: This is also of C string type and refers to the mode of the file access. Below are the file access modes for C: “r” – Searches file. Opens the file for reading only. If the file is opened successfully fopen() loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen() returns NULL.“w” – Searches file. If the file exists already, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. It creates a new file for writing only(no reading).“a” – Searches file. If the file is opened successfully fopen() loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened only for appending(writing at end of file).“r+” – Searches file. Opens the file for both reading and writing. If opened successfully, fopen() loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file.“w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The difference between w and w+ is that we can also read the file created using w+.“a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened for reading and appending(writing at end of file).
“r” – Searches file. Opens the file for reading only. If the file is opened successfully fopen() loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen() returns NULL.“w” – Searches file. If the file exists already, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. It creates a new file for writing only(no reading).“a” – Searches file. If the file is opened successfully fopen() loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened only for appending(writing at end of file).“r+” – Searches file. Opens the file for both reading and writing. If opened successfully, fopen() loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file.“w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The difference between w and w+ is that we can also read the file created using w+.“a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened for reading and appending(writing at end of file).
“r” – Searches file. Opens the file for reading only. If the file is opened successfully fopen() loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen() returns NULL.
“w” – Searches file. If the file exists already, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. It creates a new file for writing only(no reading).
“a” – Searches file. If the file is opened successfully fopen() loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened only for appending(writing at end of file).
“r+” – Searches file. Opens the file for both reading and writing. If opened successfully, fopen() loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file.
“w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The difference between w and w+ is that we can also read the file created using w+.
“a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened for reading and appending(writing at end of file).
Return Value: The function is used to return a pointer to FILE if the execution succeeds else NULL is returned.
Example 1:
C
// C program to illustrate fopen() #include <stdio.h>#include <stdlib.h> int main(){ // pointer demo to FILE FILE* demo; // Creates a file "demo_file" // with file access as write-plus mode demo = fopen("demo_file.txt", "w+"); // adds content to the file fprintf(demo, "%s %s %s", "Welcome", "to", "GeeksforGeeks"); // closes the file pointed by demo fclose(demo); return 0;}
On running the following command, a new file will be created by the name “demo_file” and with the following content:
Welcome to GeeksforGeeks
Example 2: Now if we wish to look into the file then we need to run the following code, which will open the file and display its content.
C
// C program to illustrate fopen() #include <stdio.h> int main(){ // pointer demo to FILE FILE* demo; int display; // Creates a file "demo_file" // with file access as read mode demo = fopen("demo_file.txt", "r"); // loop to extract every characters while (1) { // reading file display = fgetc(demo); // end of file indicator if (feof(demo)) break; // displaying every characters printf("%c", display); } // closes the file pointed by demo fclose(demo); return 0;}
Output:
Welcome to GeeksforGeeks
More articles on File Handling in C:
Basics of File Handling in Cfopen() for an existing file in write modeEOF, getc() and feof() in CFile opening modes(r versus r+)
Basics of File Handling in C
fopen() for an existing file in write mode
EOF, getc() and feof() in C
File opening modes(r versus r+)
tr_abhishek
simmytarika5
C-File Handling
C-Functions
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
Exception Handling in C++
What is the purpose of a function prototype?
TCP Server-Client implementation in C
Smart Pointers in C++ and How to Use Them
Storage Classes in C
'this' pointer in C++
Ways to copy a vector in C++
Arrow operator -> in C/C++ with Examples
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Sep, 2021"
},
{
"code": null,
"e": 345,
"s": 54,
"text": "Pre-requisite: Basics of File Handling in CThe fopen() method in C is a library function that is used to open a file to perform various operations which include reading, writing etc. along with various modes. If the file exists then the particular file is opened else a new file is created."
},
{
"code": null,
"e": 354,
"s": 345,
"text": "Syntax: "
},
{
"code": null,
"e": 421,
"s": 354,
"text": "FILE *fopen(const char *file_name, const char *mode_of_operation);"
},
{
"code": null,
"e": 488,
"s": 421,
"text": "Parameters: The method accepts two parameters of character type: "
},
{
"code": null,
"e": 2259,
"s": 488,
"text": "file_name: This is of C string type and accepts the name of the file that is needed to be opened.mode_of_operation: This is also of C string type and refers to the mode of the file access. Below are the file access modes for C: “r” – Searches file. Opens the file for reading only. If the file is opened successfully fopen() loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen() returns NULL.“w” – Searches file. If the file exists already, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. It creates a new file for writing only(no reading).“a” – Searches file. If the file is opened successfully fopen() loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened only for appending(writing at end of file).“r+” – Searches file. Opens the file for both reading and writing. If opened successfully, fopen() loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file.“w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The difference between w and w+ is that we can also read the file created using w+.“a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened for reading and appending(writing at end of file)."
},
{
"code": null,
"e": 2357,
"s": 2259,
"text": "file_name: This is of C string type and accepts the name of the file that is needed to be opened."
},
{
"code": null,
"e": 4031,
"s": 2357,
"text": "mode_of_operation: This is also of C string type and refers to the mode of the file access. Below are the file access modes for C: “r” – Searches file. Opens the file for reading only. If the file is opened successfully fopen() loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen() returns NULL.“w” – Searches file. If the file exists already, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. It creates a new file for writing only(no reading).“a” – Searches file. If the file is opened successfully fopen() loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened only for appending(writing at end of file).“r+” – Searches file. Opens the file for both reading and writing. If opened successfully, fopen() loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file.“w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The difference between w and w+ is that we can also read the file created using w+.“a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened for reading and appending(writing at end of file)."
},
{
"code": null,
"e": 5574,
"s": 4031,
"text": "“r” – Searches file. Opens the file for reading only. If the file is opened successfully fopen() loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen() returns NULL.“w” – Searches file. If the file exists already, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. It creates a new file for writing only(no reading).“a” – Searches file. If the file is opened successfully fopen() loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened only for appending(writing at end of file).“r+” – Searches file. Opens the file for both reading and writing. If opened successfully, fopen() loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file.“w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The difference between w and w+ is that we can also read the file created using w+.“a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened for reading and appending(writing at end of file)."
},
{
"code": null,
"e": 5808,
"s": 5574,
"text": "“r” – Searches file. Opens the file for reading only. If the file is opened successfully fopen() loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen() returns NULL."
},
{
"code": null,
"e": 6031,
"s": 5808,
"text": "“w” – Searches file. If the file exists already, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. It creates a new file for writing only(no reading)."
},
{
"code": null,
"e": 6334,
"s": 6031,
"text": "“a” – Searches file. If the file is opened successfully fopen() loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened only for appending(writing at end of file)."
},
{
"code": null,
"e": 6561,
"s": 6334,
"text": "“r+” – Searches file. Opens the file for both reading and writing. If opened successfully, fopen() loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file."
},
{
"code": null,
"e": 6809,
"s": 6561,
"text": "“w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The difference between w and w+ is that we can also read the file created using w+."
},
{
"code": null,
"e": 7122,
"s": 6809,
"text": "“a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened for reading and appending(writing at end of file)."
},
{
"code": null,
"e": 7235,
"s": 7122,
"text": "Return Value: The function is used to return a pointer to FILE if the execution succeeds else NULL is returned. "
},
{
"code": null,
"e": 7248,
"s": 7235,
"text": "Example 1: "
},
{
"code": null,
"e": 7250,
"s": 7248,
"text": "C"
},
{
"code": "// C program to illustrate fopen() #include <stdio.h>#include <stdlib.h> int main(){ // pointer demo to FILE FILE* demo; // Creates a file \"demo_file\" // with file access as write-plus mode demo = fopen(\"demo_file.txt\", \"w+\"); // adds content to the file fprintf(demo, \"%s %s %s\", \"Welcome\", \"to\", \"GeeksforGeeks\"); // closes the file pointed by demo fclose(demo); return 0;}",
"e": 7672,
"s": 7250,
"text": null
},
{
"code": null,
"e": 7790,
"s": 7672,
"text": "On running the following command, a new file will be created by the name “demo_file” and with the following content: "
},
{
"code": null,
"e": 7815,
"s": 7790,
"text": "Welcome to GeeksforGeeks"
},
{
"code": null,
"e": 7954,
"s": 7815,
"text": "Example 2: Now if we wish to look into the file then we need to run the following code, which will open the file and display its content. "
},
{
"code": null,
"e": 7956,
"s": 7954,
"text": "C"
},
{
"code": "// C program to illustrate fopen() #include <stdio.h> int main(){ // pointer demo to FILE FILE* demo; int display; // Creates a file \"demo_file\" // with file access as read mode demo = fopen(\"demo_file.txt\", \"r\"); // loop to extract every characters while (1) { // reading file display = fgetc(demo); // end of file indicator if (feof(demo)) break; // displaying every characters printf(\"%c\", display); } // closes the file pointed by demo fclose(demo); return 0;}",
"e": 8517,
"s": 7956,
"text": null
},
{
"code": null,
"e": 8526,
"s": 8517,
"text": "Output: "
},
{
"code": null,
"e": 8551,
"s": 8526,
"text": "Welcome to GeeksforGeeks"
},
{
"code": null,
"e": 8590,
"s": 8551,
"text": "More articles on File Handling in C: "
},
{
"code": null,
"e": 8719,
"s": 8590,
"text": "Basics of File Handling in Cfopen() for an existing file in write modeEOF, getc() and feof() in CFile opening modes(r versus r+)"
},
{
"code": null,
"e": 8748,
"s": 8719,
"text": "Basics of File Handling in C"
},
{
"code": null,
"e": 8791,
"s": 8748,
"text": "fopen() for an existing file in write mode"
},
{
"code": null,
"e": 8819,
"s": 8791,
"text": "EOF, getc() and feof() in C"
},
{
"code": null,
"e": 8851,
"s": 8819,
"text": "File opening modes(r versus r+)"
},
{
"code": null,
"e": 8865,
"s": 8853,
"text": "tr_abhishek"
},
{
"code": null,
"e": 8878,
"s": 8865,
"text": "simmytarika5"
},
{
"code": null,
"e": 8894,
"s": 8878,
"text": "C-File Handling"
},
{
"code": null,
"e": 8906,
"s": 8894,
"text": "C-Functions"
},
{
"code": null,
"e": 8917,
"s": 8906,
"text": "C Language"
},
{
"code": null,
"e": 9015,
"s": 8917,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9063,
"s": 9015,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 9084,
"s": 9063,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 9110,
"s": 9084,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 9155,
"s": 9110,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 9193,
"s": 9155,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 9235,
"s": 9193,
"text": "Smart Pointers in C++ and How to Use Them"
},
{
"code": null,
"e": 9256,
"s": 9235,
"text": "Storage Classes in C"
},
{
"code": null,
"e": 9278,
"s": 9256,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 9307,
"s": 9278,
"text": "Ways to copy a vector in C++"
}
] |
Delete a column from a Pandas DataFrame
|
17 Jan, 2022
Deletion is one of the primary operations when it comes to data analysis. Very often we see that a particular attribute in the data frame is not at all useful for us while working on a specific analysis, rather having it may lead to problems and unnecessary change in the prediction. For example, if we want to analyze the students’ BMI of a particular school, then there is no need to have the religion column/attribute for the students, so we prefer to delete the column. Let us now see the syntax of deleting a column from a dataframe.Syntax:
del df['column_name']
Let us now see few examples:Example 1:
Python3
# importing the moduleimport pandas as pd # creating a DataFramemy_df = {'Name': ['Rutuja', 'Anuja'], 'ID': [1, 2], 'Age': [20, 19]}df = pd.DataFrame(my_df)display("Original DataFrame")display(df) # deleting a columndel df['Age'] display("DataFrame after deletion")display(df)
Output :
Note the column ‘Age” has been dropped.Example 2:
Python3
# importing the moduleimport pandas as pd # creating a DataFramemy_df = {'Students': ['A', 'B', 'C', 'D'], 'BMI': [22.7, 18.0, 21.4, 24.1], 'Religion': ['Hindu', 'Islam', 'Christian', 'Sikh']}df = pd.DataFrame(my_df)display("Original DataFrame")display(df) # deleting a columndel df['Religion'] display("DataFrame after deletion")display(df)
Output :
Note that the unnecessary column, ‘Religion’ has been deleted successfully.
saurabh1990aror
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 576,
"s": 28,
"text": "Deletion is one of the primary operations when it comes to data analysis. Very often we see that a particular attribute in the data frame is not at all useful for us while working on a specific analysis, rather having it may lead to problems and unnecessary change in the prediction. For example, if we want to analyze the students’ BMI of a particular school, then there is no need to have the religion column/attribute for the students, so we prefer to delete the column. Let us now see the syntax of deleting a column from a dataframe.Syntax: "
},
{
"code": null,
"e": 598,
"s": 576,
"text": "del df['column_name']"
},
{
"code": null,
"e": 639,
"s": 598,
"text": "Let us now see few examples:Example 1: "
},
{
"code": null,
"e": 647,
"s": 639,
"text": "Python3"
},
{
"code": "# importing the moduleimport pandas as pd # creating a DataFramemy_df = {'Name': ['Rutuja', 'Anuja'], 'ID': [1, 2], 'Age': [20, 19]}df = pd.DataFrame(my_df)display(\"Original DataFrame\")display(df) # deleting a columndel df['Age'] display(\"DataFrame after deletion\")display(df)",
"e": 932,
"s": 647,
"text": null
},
{
"code": null,
"e": 943,
"s": 932,
"text": "Output : "
},
{
"code": null,
"e": 995,
"s": 943,
"text": "Note the column ‘Age” has been dropped.Example 2: "
},
{
"code": null,
"e": 1003,
"s": 995,
"text": "Python3"
},
{
"code": "# importing the moduleimport pandas as pd # creating a DataFramemy_df = {'Students': ['A', 'B', 'C', 'D'], 'BMI': [22.7, 18.0, 21.4, 24.1], 'Religion': ['Hindu', 'Islam', 'Christian', 'Sikh']}df = pd.DataFrame(my_df)display(\"Original DataFrame\")display(df) # deleting a columndel df['Religion'] display(\"DataFrame after deletion\")display(df)",
"e": 1382,
"s": 1003,
"text": null
},
{
"code": null,
"e": 1393,
"s": 1382,
"text": "Output : "
},
{
"code": null,
"e": 1470,
"s": 1393,
"text": "Note that the unnecessary column, ‘Religion’ has been deleted successfully. "
},
{
"code": null,
"e": 1486,
"s": 1470,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 1511,
"s": 1486,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 1535,
"s": 1511,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 1549,
"s": 1535,
"text": "Python-pandas"
},
{
"code": null,
"e": 1556,
"s": 1549,
"text": "Python"
},
{
"code": null,
"e": 1654,
"s": 1556,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1686,
"s": 1654,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1713,
"s": 1686,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1734,
"s": 1713,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1757,
"s": 1734,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1813,
"s": 1757,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1844,
"s": 1813,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1886,
"s": 1844,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1928,
"s": 1886,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1967,
"s": 1928,
"text": "Python | datetime.timedelta() function"
}
] |
Protected variable in Python
|
10 Jan, 2020
Prerequisites: Underscore ( _ ) in Python
A Variable is an identifier that we assign to a memory location which is used to hold values in a computer program. Variables are named locations of storage in the program. Based on access specification, variables can be public, protected and private in a class.
Protected variables are those data members of a class that can be accessed within the class and the classes derived from that class. In Python, there is no existence of “Public” instance variables. However, we use underscore ‘_’ symbol to determine the access control of a data member in a class. Any member prefixed with an underscore should be treated as a non-public part of the API or any Python code, whether it is a function, a method or a data member.
Example 1:
# program to illustrate protected# data members in a class # Defining a classclass Geek: # protected data members _name = "R2J" _roll = 1706256 # public member function def displayNameAndRoll(self): # accessing protected data members print("Name: ", self._name) print("Roll: ", self._roll) # creating objects of the class obj = Geek() # calling public member # functions of the class obj.displayNameAndRoll()
Output:
Name: R2J
Roll: 1706256
Example 2: During Inheritance
# program to illustrate protected# data members in a class # super class class Shape: # constructor def __init__(self, length, breadth): self._length = length self._breadth = breadth # public member function def displaySides(self): # accessing protected data members print("Length: ", self._length) print("Breadth: ", self._breadth) # derived class class Rectangle(Shape): # constructor def __init__(self, length, breadth): # Calling the constructor of # Super class Shape.__init__(self, length, breadth) # public member function def calculateArea(self): # accessing protected data members of super class print("Area: ", self._length * self._breadth) # creating objects of the # derived class obj = Rectangle(80, 50) # calling derived member # functions of the classobj.displaySides() # calling public member# functions of the class obj.calculateArea()
Output:
Length: 80
Breadth: 50
Area: 4000
In the above example, the protected variables _length and _breadth of the super class Shape are accessed within the class by a member function displaySides() and can be accessed from class Rectangle which is derived from the Shape class. The member function calculateArea() of class Rectangle accesses the protected data members _length and _breadth of the super class Shape to calculate the area of the rectangle.
Python-OOP
python-oop-concepts
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Jan, 2020"
},
{
"code": null,
"e": 70,
"s": 28,
"text": "Prerequisites: Underscore ( _ ) in Python"
},
{
"code": null,
"e": 333,
"s": 70,
"text": "A Variable is an identifier that we assign to a memory location which is used to hold values in a computer program. Variables are named locations of storage in the program. Based on access specification, variables can be public, protected and private in a class."
},
{
"code": null,
"e": 792,
"s": 333,
"text": "Protected variables are those data members of a class that can be accessed within the class and the classes derived from that class. In Python, there is no existence of “Public” instance variables. However, we use underscore ‘_’ symbol to determine the access control of a data member in a class. Any member prefixed with an underscore should be treated as a non-public part of the API or any Python code, whether it is a function, a method or a data member."
},
{
"code": null,
"e": 803,
"s": 792,
"text": "Example 1:"
},
{
"code": "# program to illustrate protected# data members in a class # Defining a classclass Geek: # protected data members _name = \"R2J\" _roll = 1706256 # public member function def displayNameAndRoll(self): # accessing protected data members print(\"Name: \", self._name) print(\"Roll: \", self._roll) # creating objects of the class obj = Geek() # calling public member # functions of the class obj.displayNameAndRoll() ",
"e": 1287,
"s": 803,
"text": null
},
{
"code": null,
"e": 1295,
"s": 1287,
"text": "Output:"
},
{
"code": null,
"e": 1322,
"s": 1295,
"text": "Name: R2J\nRoll: 1706256\n"
},
{
"code": null,
"e": 1352,
"s": 1322,
"text": "Example 2: During Inheritance"
},
{
"code": "# program to illustrate protected# data members in a class # super class class Shape: # constructor def __init__(self, length, breadth): self._length = length self._breadth = breadth # public member function def displaySides(self): # accessing protected data members print(\"Length: \", self._length) print(\"Breadth: \", self._breadth) # derived class class Rectangle(Shape): # constructor def __init__(self, length, breadth): # Calling the constructor of # Super class Shape.__init__(self, length, breadth) # public member function def calculateArea(self): # accessing protected data members of super class print(\"Area: \", self._length * self._breadth) # creating objects of the # derived class obj = Rectangle(80, 50) # calling derived member # functions of the classobj.displaySides() # calling public member# functions of the class obj.calculateArea() ",
"e": 2412,
"s": 1352,
"text": null
},
{
"code": null,
"e": 2420,
"s": 2412,
"text": "Output:"
},
{
"code": null,
"e": 2458,
"s": 2420,
"text": "Length: 80\nBreadth: 50\nArea: 4000\n"
},
{
"code": null,
"e": 2873,
"s": 2458,
"text": "In the above example, the protected variables _length and _breadth of the super class Shape are accessed within the class by a member function displaySides() and can be accessed from class Rectangle which is derived from the Shape class. The member function calculateArea() of class Rectangle accesses the protected data members _length and _breadth of the super class Shape to calculate the area of the rectangle."
},
{
"code": null,
"e": 2884,
"s": 2873,
"text": "Python-OOP"
},
{
"code": null,
"e": 2904,
"s": 2884,
"text": "python-oop-concepts"
},
{
"code": null,
"e": 2911,
"s": 2904,
"text": "Python"
},
{
"code": null,
"e": 3009,
"s": 2911,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3051,
"s": 3009,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3073,
"s": 3051,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3108,
"s": 3073,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3134,
"s": 3108,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3166,
"s": 3134,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3195,
"s": 3166,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3225,
"s": 3195,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3252,
"s": 3225,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3288,
"s": 3252,
"text": "Convert integer to string in Python"
}
] |
HTML DOM getElementById() Method
|
25 Nov, 2021
The getElementById() method returns the elements that have given an ID which is passed to the function. This function is a widely used HTML DOM method in web designing to change the value of any particular element or get a particular element. If the passed ID to the function does not exist then it returns null. The element is required to have a unique id, in order to get access to that specific element quickly, & also that particular id should only be used once in the entire document.
Syntax:
document.getElementById( element_ID )
Parameter: This function accepts single parameter element_ID which is used to hold the ID of the element.
Return Value: It returns the object of the given ID. If no element exists with the given ID then it returns null.
Example 1: This example describes the getElementById() method where element_id is used to change the color of the text on clicking the button.
HTML
<!DOCTYPE html><html> <head> <title> DOM getElementById() Method </title> <script> // Function to change the color of element function geeks() { var demo = document.getElementById("geeks"); demo.style.color = "green"; } </script></head> <body style="text-align:center"> <h1 id="geeks">GeeksforGeeks</h1> <h2>DOM getElementById() Method</h2> <!-- Click on the button to change color --> <input type="button" onclick="geeks()" value="Click here to change color" /></body> </html>
Output:
getElementById() Method
Example 2: This example describes the getElementById() method where the element_id is used to change the content on clicking the button.
HTML
<!DOCTYPE html><html> <head> <title> DOM getElementById() Method </title> <script> // Function to change content of element function geeks() { var demo = document.getElementById("geeks"); demo.innerHTML = "Welcome to GeeksforGeeks!"; } </script></head> <body style="text-align:center"> <h1>GeeksforGeeks</h1> <h2>DOM getElementById() Method</h2> <h3 id="geeks">Hello Geeks!</h3> <!-- Click here to change content --> <input type="button" onclick="geeks()" value="Click here to change content" /></body> </html>
Output:
getElementById() Method
Supported Browsers: The browser supported by DOM getElementById() method are listed below:
Google Chrome 1.0
Internet Explorer 5.5
Microsoft Edge 12.0
Firefox 1.0
Opera 7.0
Safari 1.0
bhaskargeeksforgeeks
HTML-DOM
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 542,
"s": 52,
"text": "The getElementById() method returns the elements that have given an ID which is passed to the function. This function is a widely used HTML DOM method in web designing to change the value of any particular element or get a particular element. If the passed ID to the function does not exist then it returns null. The element is required to have a unique id, in order to get access to that specific element quickly, & also that particular id should only be used once in the entire document."
},
{
"code": null,
"e": 550,
"s": 542,
"text": "Syntax:"
},
{
"code": null,
"e": 588,
"s": 550,
"text": "document.getElementById( element_ID )"
},
{
"code": null,
"e": 694,
"s": 588,
"text": "Parameter: This function accepts single parameter element_ID which is used to hold the ID of the element."
},
{
"code": null,
"e": 808,
"s": 694,
"text": "Return Value: It returns the object of the given ID. If no element exists with the given ID then it returns null."
},
{
"code": null,
"e": 951,
"s": 808,
"text": "Example 1: This example describes the getElementById() method where element_id is used to change the color of the text on clicking the button."
},
{
"code": null,
"e": 956,
"s": 951,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> DOM getElementById() Method </title> <script> // Function to change the color of element function geeks() { var demo = document.getElementById(\"geeks\"); demo.style.color = \"green\"; } </script></head> <body style=\"text-align:center\"> <h1 id=\"geeks\">GeeksforGeeks</h1> <h2>DOM getElementById() Method</h2> <!-- Click on the button to change color --> <input type=\"button\" onclick=\"geeks()\" value=\"Click here to change color\" /></body> </html>",
"e": 1539,
"s": 956,
"text": null
},
{
"code": null,
"e": 1547,
"s": 1539,
"text": "Output:"
},
{
"code": null,
"e": 1571,
"s": 1547,
"text": "getElementById() Method"
},
{
"code": null,
"e": 1708,
"s": 1571,
"text": "Example 2: This example describes the getElementById() method where the element_id is used to change the content on clicking the button."
},
{
"code": null,
"e": 1713,
"s": 1708,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> DOM getElementById() Method </title> <script> // Function to change content of element function geeks() { var demo = document.getElementById(\"geeks\"); demo.innerHTML = \"Welcome to GeeksforGeeks!\"; } </script></head> <body style=\"text-align:center\"> <h1>GeeksforGeeks</h1> <h2>DOM getElementById() Method</h2> <h3 id=\"geeks\">Hello Geeks!</h3> <!-- Click here to change content --> <input type=\"button\" onclick=\"geeks()\" value=\"Click here to change content\" /></body> </html>",
"e": 2332,
"s": 1713,
"text": null
},
{
"code": null,
"e": 2340,
"s": 2332,
"text": "Output:"
},
{
"code": null,
"e": 2364,
"s": 2340,
"text": "getElementById() Method"
},
{
"code": null,
"e": 2455,
"s": 2364,
"text": "Supported Browsers: The browser supported by DOM getElementById() method are listed below:"
},
{
"code": null,
"e": 2473,
"s": 2455,
"text": "Google Chrome 1.0"
},
{
"code": null,
"e": 2495,
"s": 2473,
"text": "Internet Explorer 5.5"
},
{
"code": null,
"e": 2515,
"s": 2495,
"text": "Microsoft Edge 12.0"
},
{
"code": null,
"e": 2527,
"s": 2515,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 2537,
"s": 2527,
"text": "Opera 7.0"
},
{
"code": null,
"e": 2548,
"s": 2537,
"text": "Safari 1.0"
},
{
"code": null,
"e": 2569,
"s": 2548,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 2578,
"s": 2569,
"text": "HTML-DOM"
},
{
"code": null,
"e": 2585,
"s": 2578,
"text": "Picked"
},
{
"code": null,
"e": 2590,
"s": 2585,
"text": "HTML"
},
{
"code": null,
"e": 2607,
"s": 2590,
"text": "Web Technologies"
},
{
"code": null,
"e": 2612,
"s": 2607,
"text": "HTML"
},
{
"code": null,
"e": 2710,
"s": 2612,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2758,
"s": 2710,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 2820,
"s": 2758,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2870,
"s": 2820,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2894,
"s": 2870,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2947,
"s": 2894,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 3009,
"s": 2947,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3042,
"s": 3009,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3103,
"s": 3042,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3153,
"s": 3103,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Solving f(n)= (1) + (2*3) + (4*5*6) ... n using Recursion
|
06 Jul, 2022
Example :
Input : 2
Output: 7
Series: (1) + (2*3)
Input : 4
Output: 5167
Series: (1) + (2*3) + (4*5*6) + (7*8*9*10)
C++
C
Java
Python3
C#
PHP
Javascript
// CPP Program to print the solution// of the series f(n)= (1) + (2*3)// + (4*5*6) ... n using recursion#include<bits/stdc++.h>using namespace std; // Recursive function for// finding sum of series// calculated - number of terms till// which sum of terms has// been calculated// current - number of terms for which// sum has to becalculated// N - Number of terms in the// function to be calculatedint seriesSum(int calculated, int current, int N){ int i, cur = 1; // checking termination condition if (current == N + 1) return 0; // product of terms till current for (i = calculated; i < calculated + current; i++) cur *= i; // recursive call for adding // terms next in the series return cur + seriesSum(i, current + 1, N);} // Driver Codeint main(){ // input number of terms in the series int N = 5; // invoking the function to // calculate the sum cout<<seriesSum(1, 1, N)<<endl; return 0;}
// C Program to print the solution// of the series f(n)= (1) + (2*3)// + (4*5*6) ... n using recursion#include <stdio.h> // Recursive function for// finding sum of series// calculated - number of terms till// which sum of terms has// been calculated// current - number of terms for which// sum has to becalculated// N - Number of terms in the// function to be calculatedint seriesSum(int calculated, int current, int N){ int i, cur = 1; // checking termination condition if (current == N + 1) return 0; // product of terms till current for (i = calculated; i < calculated + current; i++) cur *= i; // recursive call for adding // terms next in the series return cur + seriesSum(i, current + 1, N);} // Driver Codeint main(){ // input number of terms in the series int N = 5; // invoking the function to // calculate the sum printf("%d\n", seriesSum(1, 1, N)); return 0;}
// Java Program to print the// solution of the series// f(n)= (1) + (2*3) + (4*5*6)// ... n using recursion class GFG{ /** * Recursive method for finding * sum of series * * @param calculated number of terms * till which sum of terms has been * calculated @param current number of * terms for which sum has to be calculated. * @param N Number of terms in the function * to be calculated @return sum */ static int seriesSum(int calculated, int current, int N) { int i, cur = 1; // checking termination condition if (current == N + 1) return 0; // product of terms till current for (i = calculated; i < calculated + current; i++) cur *= i; // recursive call for adding // terms next in the series return cur + seriesSum(i, current + 1, N); } // Driver Code public static void main(String[] args) { // input number of // terms in the series int N = 5; // invoking the method // to calculate the sum System.out.println(seriesSum(1, 1, N)); }}
# Python3 Program to print the solution# of the series f(n)= (1) + (2*3) + (4*5*6)# ... n using recursion # Recursive function for finding sum of series# calculated - number of terms till# which sum of terms# has been calculated# current - number of terms for# which sum has to be# calculated# N - Number of terms in the# function to be calculateddef seriesSum(calculated, current, N): i = calculated; cur = 1; # checking termination condition if (current == N + 1): return 0; # product of terms till current while (i < calculated + current): cur *= i; i += 1; # recursive call for adding # terms next in the series return cur + seriesSum(i, current + 1, N); # Driver code # input number of terms in the seriesN = 5; # invoking the function# to calculate the sumprint(seriesSum(1, 1, N)); # This code is contributed by mits
// C# Program to print the// solution of the series// f(n)= (1) + (2*3) + (4*5*6)// ... n using recursionusing System; class GFG{ // Recursive function for // finding sum of series // calculated - number of terms till // which sum of terms // has been calculated // current - number of terms for which // sum has to be calculated // N - Number of terms in the // function to be calculated static int seriesSum(int calculated, int current, int N) { int i, cur = 1; // checking termination condition if (current == N + 1) return 0; // product of terms till current for (i = calculated; i < calculated + current; i++) cur *= i; // recursive call for adding terms // next in the series return cur + seriesSum(i, current + 1, N); } // Driver Code public static void Main() { // input number of terms // in the series int N = 5; // invoking the method to // calculate the sum Console.WriteLine(seriesSum(1, 1, N)); }} // This code is contributed by vt_m.
<?php// PHP Program to print the// solution of the series// f(n)= (1) + (2*3) + (4*5*6)// ... n using recursion // Recursive function for// finding sum of series// calculated - number of terms till// which sum of terms// has been calculated// current - number of terms for// which sum has to be// calculated// N - Number of terms in the// function to be calculatedfunction seriesSum($calculated, $current, $N){ $i; $cur = 1; // checking termination condition if ($current == $N + 1) return 0; // product of terms till current for ($i = $calculated; $i < $calculated + $current; $i++) $cur *= $i; // recursive call for adding // terms next in the series return $cur + seriesSum($i, $current + 1, $N);} // Driver code // input number of// terms in the series$N = 5; // invoking the function// to calculate the sumecho(seriesSum(1, 1, $N)); // This code is contributed by Ajit.?>
<script> // JavaScript Program to print the// solution of the series// f(n)= (1) + (2*3) + (4*5*6)// ... n using recursion /** * Recursive method for finding * sum of series * * @param calculated number of terms * till which sum of terms has been * calculated @param current number of * terms for which sum has to be calculated. * @param N Number of terms in the function * to be calculated @return sum */ function seriesSum(calculated, current, N) { let i, cur = 1; // checking termination condition if (current == N + 1) return 0; // product of terms till current for (i = calculated; i < calculated + current; i++) cur *= i; // recursive call for adding // terms next in the series return cur + seriesSum(i, current + 1, N); } // Driver Code // input number of // terms in the series let N = 5; // invoking the method // to calculate the sum document.write(seriesSum(1, 1, N)); // This code is contributed by target_2.</script>
Output :
365527
Time Complexity: O(n2)
Auxiliary Space: O(n)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
jit_t
SURENDRA_GANGWAR
Mithun Kumar
target_2
akashish__
MAQ Software
series
C Language
C++
Mathematical
School Programming
MAQ Software
Mathematical
series
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Vector in C++ STL
Initialize a vector in C++ (7 different ways)
Templates in C++ with Examples
Operator Overloading in C++
Inheritance in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 65,
"s": 52,
"text": " Example : "
},
{
"code": null,
"e": 173,
"s": 65,
"text": "Input : 2\nOutput: 7\nSeries: (1) + (2*3)\n\nInput : 4\nOutput: 5167\nSeries: (1) + (2*3) + (4*5*6) + (7*8*9*10) "
},
{
"code": null,
"e": 181,
"s": 177,
"text": "C++"
},
{
"code": null,
"e": 183,
"s": 181,
"text": "C"
},
{
"code": null,
"e": 188,
"s": 183,
"text": "Java"
},
{
"code": null,
"e": 196,
"s": 188,
"text": "Python3"
},
{
"code": null,
"e": 199,
"s": 196,
"text": "C#"
},
{
"code": null,
"e": 203,
"s": 199,
"text": "PHP"
},
{
"code": null,
"e": 214,
"s": 203,
"text": "Javascript"
},
{
"code": "// CPP Program to print the solution// of the series f(n)= (1) + (2*3)// + (4*5*6) ... n using recursion#include<bits/stdc++.h>using namespace std; // Recursive function for// finding sum of series// calculated - number of terms till// which sum of terms has// been calculated// current - number of terms for which// sum has to becalculated// N - Number of terms in the// function to be calculatedint seriesSum(int calculated, int current, int N){ int i, cur = 1; // checking termination condition if (current == N + 1) return 0; // product of terms till current for (i = calculated; i < calculated + current; i++) cur *= i; // recursive call for adding // terms next in the series return cur + seriesSum(i, current + 1, N);} // Driver Codeint main(){ // input number of terms in the series int N = 5; // invoking the function to // calculate the sum cout<<seriesSum(1, 1, N)<<endl; return 0;}",
"e": 1279,
"s": 214,
"text": null
},
{
"code": "// C Program to print the solution// of the series f(n)= (1) + (2*3)// + (4*5*6) ... n using recursion#include <stdio.h> // Recursive function for// finding sum of series// calculated - number of terms till// which sum of terms has// been calculated// current - number of terms for which// sum has to becalculated// N - Number of terms in the// function to be calculatedint seriesSum(int calculated, int current, int N){ int i, cur = 1; // checking termination condition if (current == N + 1) return 0; // product of terms till current for (i = calculated; i < calculated + current; i++) cur *= i; // recursive call for adding // terms next in the series return cur + seriesSum(i, current + 1, N);} // Driver Codeint main(){ // input number of terms in the series int N = 5; // invoking the function to // calculate the sum printf(\"%d\\n\", seriesSum(1, 1, N)); return 0;}",
"e": 2327,
"s": 1279,
"text": null
},
{
"code": "// Java Program to print the// solution of the series// f(n)= (1) + (2*3) + (4*5*6)// ... n using recursion class GFG{ /** * Recursive method for finding * sum of series * * @param calculated number of terms * till which sum of terms has been * calculated @param current number of * terms for which sum has to be calculated. * @param N Number of terms in the function * to be calculated @return sum */ static int seriesSum(int calculated, int current, int N) { int i, cur = 1; // checking termination condition if (current == N + 1) return 0; // product of terms till current for (i = calculated; i < calculated + current; i++) cur *= i; // recursive call for adding // terms next in the series return cur + seriesSum(i, current + 1, N); } // Driver Code public static void main(String[] args) { // input number of // terms in the series int N = 5; // invoking the method // to calculate the sum System.out.println(seriesSum(1, 1, N)); }}",
"e": 3554,
"s": 2327,
"text": null
},
{
"code": "# Python3 Program to print the solution# of the series f(n)= (1) + (2*3) + (4*5*6)# ... n using recursion # Recursive function for finding sum of series# calculated - number of terms till# which sum of terms# has been calculated# current - number of terms for# which sum has to be# calculated# N - Number of terms in the# function to be calculateddef seriesSum(calculated, current, N): i = calculated; cur = 1; # checking termination condition if (current == N + 1): return 0; # product of terms till current while (i < calculated + current): cur *= i; i += 1; # recursive call for adding # terms next in the series return cur + seriesSum(i, current + 1, N); # Driver code # input number of terms in the seriesN = 5; # invoking the function# to calculate the sumprint(seriesSum(1, 1, N)); # This code is contributed by mits",
"e": 4490,
"s": 3554,
"text": null
},
{
"code": "// C# Program to print the// solution of the series// f(n)= (1) + (2*3) + (4*5*6)// ... n using recursionusing System; class GFG{ // Recursive function for // finding sum of series // calculated - number of terms till // which sum of terms // has been calculated // current - number of terms for which // sum has to be calculated // N - Number of terms in the // function to be calculated static int seriesSum(int calculated, int current, int N) { int i, cur = 1; // checking termination condition if (current == N + 1) return 0; // product of terms till current for (i = calculated; i < calculated + current; i++) cur *= i; // recursive call for adding terms // next in the series return cur + seriesSum(i, current + 1, N); } // Driver Code public static void Main() { // input number of terms // in the series int N = 5; // invoking the method to // calculate the sum Console.WriteLine(seriesSum(1, 1, N)); }} // This code is contributed by vt_m.",
"e": 5804,
"s": 4490,
"text": null
},
{
"code": "<?php// PHP Program to print the// solution of the series// f(n)= (1) + (2*3) + (4*5*6)// ... n using recursion // Recursive function for// finding sum of series// calculated - number of terms till// which sum of terms// has been calculated// current - number of terms for// which sum has to be// calculated// N - Number of terms in the// function to be calculatedfunction seriesSum($calculated, $current, $N){ $i; $cur = 1; // checking termination condition if ($current == $N + 1) return 0; // product of terms till current for ($i = $calculated; $i < $calculated + $current; $i++) $cur *= $i; // recursive call for adding // terms next in the series return $cur + seriesSum($i, $current + 1, $N);} // Driver code // input number of// terms in the series$N = 5; // invoking the function// to calculate the sumecho(seriesSum(1, 1, $N)); // This code is contributed by Ajit.?>",
"e": 6830,
"s": 5804,
"text": null
},
{
"code": "<script> // JavaScript Program to print the// solution of the series// f(n)= (1) + (2*3) + (4*5*6)// ... n using recursion /** * Recursive method for finding * sum of series * * @param calculated number of terms * till which sum of terms has been * calculated @param current number of * terms for which sum has to be calculated. * @param N Number of terms in the function * to be calculated @return sum */ function seriesSum(calculated, current, N) { let i, cur = 1; // checking termination condition if (current == N + 1) return 0; // product of terms till current for (i = calculated; i < calculated + current; i++) cur *= i; // recursive call for adding // terms next in the series return cur + seriesSum(i, current + 1, N); } // Driver Code // input number of // terms in the series let N = 5; // invoking the method // to calculate the sum document.write(seriesSum(1, 1, N)); // This code is contributed by target_2.</script>",
"e": 8026,
"s": 6830,
"text": null
},
{
"code": null,
"e": 8037,
"s": 8026,
"text": "Output : "
},
{
"code": null,
"e": 8045,
"s": 8037,
"text": "365527 "
},
{
"code": null,
"e": 8068,
"s": 8045,
"text": "Time Complexity: O(n2)"
},
{
"code": null,
"e": 8214,
"s": 8068,
"text": "Auxiliary Space: O(n)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 8220,
"s": 8214,
"text": "jit_t"
},
{
"code": null,
"e": 8237,
"s": 8220,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 8250,
"s": 8237,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 8259,
"s": 8250,
"text": "target_2"
},
{
"code": null,
"e": 8270,
"s": 8259,
"text": "akashish__"
},
{
"code": null,
"e": 8283,
"s": 8270,
"text": "MAQ Software"
},
{
"code": null,
"e": 8290,
"s": 8283,
"text": "series"
},
{
"code": null,
"e": 8301,
"s": 8290,
"text": "C Language"
},
{
"code": null,
"e": 8305,
"s": 8301,
"text": "C++"
},
{
"code": null,
"e": 8318,
"s": 8305,
"text": "Mathematical"
},
{
"code": null,
"e": 8337,
"s": 8318,
"text": "School Programming"
},
{
"code": null,
"e": 8350,
"s": 8337,
"text": "MAQ Software"
},
{
"code": null,
"e": 8363,
"s": 8350,
"text": "Mathematical"
},
{
"code": null,
"e": 8370,
"s": 8363,
"text": "series"
},
{
"code": null,
"e": 8374,
"s": 8370,
"text": "CPP"
},
{
"code": null,
"e": 8472,
"s": 8374,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8489,
"s": 8472,
"text": "Substring in C++"
},
{
"code": null,
"e": 8524,
"s": 8489,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 8546,
"s": 8524,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 8592,
"s": 8546,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 8637,
"s": 8592,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 8655,
"s": 8637,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 8701,
"s": 8655,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 8732,
"s": 8701,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 8760,
"s": 8732,
"text": "Operator Overloading in C++"
}
] |
Python | Initialize a dictionary with only keys from a list
|
15 Feb, 2019
Given a List, the task is to create a dictionary with only keys by using given list as keys.
Let’s see the different methods we can do this task.
Method #1 : By iterating through list
# Python code to initialize a dictionary# with only keys from a list # List of keyskeyList = ["Paras", "Jain", "Cyware"] # initialize dictionaryd = {} # iterating through the elements of listfor i in keyList: d[i] = None print(d)
{'Cyware': None, 'Paras': None, 'Jain': None}
Method #2 : Using dictionary comprehension
# Python code to initialize a dictionary# with only keys from a list # List of KeyskeyList = ["Paras", "Jain", "Cyware"] # Using Dictionary comprehensionmyDict = {key: None for key in keyList}print(myDict)
{'Paras': None, 'Jain': None, 'Cyware': None}
Method #3 : Using zip() function
# Python code to initialize a dictionary# with only keys from a list # List of keyslistKeys = ["Paras", "Jain", "Cyware"] # using zip() function to create a dictionary# with keys and same length None value dct = dict(zip(listKeys, [None]*len(listKeys))) # print dictprint(dct)
{'Cyware': None, 'Paras': None, 'Jain': None}
Method #4 : Using fromkeys() method
# Python code to initialize a dictionary# with only keys from a list # List of keysStudent = ["Paras", "Jain", "Cyware"] # using fromkeys() methodStudentDict = dict.fromkeys(Student, None) # printing dictionaryprint(StudentDict)
{'Cyware': None, 'Jain': None, 'Paras': None}
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n15 Feb, 2019"
},
{
"code": null,
"e": 146,
"s": 53,
"text": "Given a List, the task is to create a dictionary with only keys by using given list as keys."
},
{
"code": null,
"e": 199,
"s": 146,
"text": "Let’s see the different methods we can do this task."
},
{
"code": null,
"e": 237,
"s": 199,
"text": "Method #1 : By iterating through list"
},
{
"code": "# Python code to initialize a dictionary# with only keys from a list # List of keyskeyList = [\"Paras\", \"Jain\", \"Cyware\"] # initialize dictionaryd = {} # iterating through the elements of listfor i in keyList: d[i] = None print(d)",
"e": 478,
"s": 237,
"text": null
},
{
"code": null,
"e": 525,
"s": 478,
"text": "{'Cyware': None, 'Paras': None, 'Jain': None}\n"
},
{
"code": null,
"e": 569,
"s": 525,
"text": " Method #2 : Using dictionary comprehension"
},
{
"code": "# Python code to initialize a dictionary# with only keys from a list # List of KeyskeyList = [\"Paras\", \"Jain\", \"Cyware\"] # Using Dictionary comprehensionmyDict = {key: None for key in keyList}print(myDict)",
"e": 777,
"s": 569,
"text": null
},
{
"code": null,
"e": 824,
"s": 777,
"text": "{'Paras': None, 'Jain': None, 'Cyware': None}\n"
},
{
"code": null,
"e": 858,
"s": 824,
"text": " Method #3 : Using zip() function"
},
{
"code": "# Python code to initialize a dictionary# with only keys from a list # List of keyslistKeys = [\"Paras\", \"Jain\", \"Cyware\"] # using zip() function to create a dictionary# with keys and same length None value dct = dict(zip(listKeys, [None]*len(listKeys))) # print dictprint(dct)",
"e": 1138,
"s": 858,
"text": null
},
{
"code": null,
"e": 1185,
"s": 1138,
"text": "{'Cyware': None, 'Paras': None, 'Jain': None}\n"
},
{
"code": null,
"e": 1222,
"s": 1185,
"text": " Method #4 : Using fromkeys() method"
},
{
"code": "# Python code to initialize a dictionary# with only keys from a list # List of keysStudent = [\"Paras\", \"Jain\", \"Cyware\"] # using fromkeys() methodStudentDict = dict.fromkeys(Student, None) # printing dictionaryprint(StudentDict)",
"e": 1454,
"s": 1222,
"text": null
},
{
"code": null,
"e": 1501,
"s": 1454,
"text": "{'Cyware': None, 'Jain': None, 'Paras': None}\n"
},
{
"code": null,
"e": 1530,
"s": 1503,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 1542,
"s": 1530,
"text": "python-dict"
},
{
"code": null,
"e": 1549,
"s": 1542,
"text": "Python"
},
{
"code": null,
"e": 1565,
"s": 1549,
"text": "Python Programs"
},
{
"code": null,
"e": 1577,
"s": 1565,
"text": "python-dict"
},
{
"code": null,
"e": 1675,
"s": 1577,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1717,
"s": 1675,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1739,
"s": 1717,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1774,
"s": 1739,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1800,
"s": 1774,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1832,
"s": 1800,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1875,
"s": 1832,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 1897,
"s": 1875,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1936,
"s": 1897,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1974,
"s": 1936,
"text": "Python | Convert a list to dictionary"
}
] |
How to save files using a File Chooser in JavaFX?
|
Using JavaFX file chooser, you can open files browse through them and save the files. The class javafx.stage.FileChooser represents a file chooser, you can open a file dialog open single or multiple files using this. You can create a file chooser in your application by instantiating this class.
The showSaveDialog() method displays a save dialog which allows you to save a file and return it. This method returns null if you haven’t chosen any file
To save a file using JavaFX −
Instantiate the FileChooser class.
Instantiate the FileChooser class.
Set the required properties.
Set the required properties.
Invoke the showSaveDialog() method.
Invoke the showSaveDialog() method.
Add the file chooser to a root node.
Add the file chooser to a root node.
Add the root node to the scene object
Add the root node to the scene object
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.FileChooser.ExtensionFilter;
public class FileChooserSavingFile extends Application {
@Override
public void start(Stage stage) {
ImageView imgView = new ImageView("UIControls/Save.png");
imgView.setFitWidth(20);
imgView.setFitHeight(20);
Menu file = new Menu("File");
MenuItem item = new MenuItem("Save", imgView);
file.getItems().addAll(item);
//Creating a File chooser
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save");
fileChooser.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*.*"));
//Adding action on the menu item
item.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
//Opening a dialog box
fileChooser.showSaveDialog(stage);
}
});
//Creating a menu bar and adding menu to it.
MenuBar menuBar = new MenuBar(file);
Group root = new Group(menuBar);
Scene scene = new Scene(root, 595, 355, Color.BEIGE);
stage.setTitle("File Chooser Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
|
[
{
"code": null,
"e": 1358,
"s": 1062,
"text": "Using JavaFX file chooser, you can open files browse through them and save the files. The class javafx.stage.FileChooser represents a file chooser, you can open a file dialog open single or multiple files using this. You can create a file chooser in your application by instantiating this class."
},
{
"code": null,
"e": 1512,
"s": 1358,
"text": "The showSaveDialog() method displays a save dialog which allows you to save a file and return it. This method returns null if you haven’t chosen any file"
},
{
"code": null,
"e": 1542,
"s": 1512,
"text": "To save a file using JavaFX −"
},
{
"code": null,
"e": 1577,
"s": 1542,
"text": "Instantiate the FileChooser class."
},
{
"code": null,
"e": 1612,
"s": 1577,
"text": "Instantiate the FileChooser class."
},
{
"code": null,
"e": 1641,
"s": 1612,
"text": "Set the required properties."
},
{
"code": null,
"e": 1670,
"s": 1641,
"text": "Set the required properties."
},
{
"code": null,
"e": 1706,
"s": 1670,
"text": "Invoke the showSaveDialog() method."
},
{
"code": null,
"e": 1742,
"s": 1706,
"text": "Invoke the showSaveDialog() method."
},
{
"code": null,
"e": 1779,
"s": 1742,
"text": "Add the file chooser to a root node."
},
{
"code": null,
"e": 1816,
"s": 1779,
"text": "Add the file chooser to a root node."
},
{
"code": null,
"e": 1854,
"s": 1816,
"text": "Add the root node to the scene object"
},
{
"code": null,
"e": 1892,
"s": 1854,
"text": "Add the root node to the scene object"
},
{
"code": null,
"e": 3517,
"s": 1892,
"text": "import javafx.application.Application;\nimport javafx.event.ActionEvent;\nimport javafx.event.EventHandler;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Menu;\nimport javafx.scene.control.MenuBar;\nimport javafx.scene.control.MenuItem;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.paint.Color;\nimport javafx.stage.FileChooser;\nimport javafx.stage.Stage;\nimport javafx.stage.FileChooser.ExtensionFilter;\npublic class FileChooserSavingFile extends Application {\n @Override\n public void start(Stage stage) {\n ImageView imgView = new ImageView(\"UIControls/Save.png\");\n imgView.setFitWidth(20);\n imgView.setFitHeight(20);\n Menu file = new Menu(\"File\");\n MenuItem item = new MenuItem(\"Save\", imgView);\n file.getItems().addAll(item);\n //Creating a File chooser\n FileChooser fileChooser = new FileChooser();\n fileChooser.setTitle(\"Save\");\n fileChooser.getExtensionFilters().addAll(new ExtensionFilter(\"All Files\", \"*.*\"));\n //Adding action on the menu item\n item.setOnAction(new EventHandler<ActionEvent>() {\n public void handle(ActionEvent event) {\n //Opening a dialog box\n fileChooser.showSaveDialog(stage);\n }\n });\n //Creating a menu bar and adding menu to it.\n MenuBar menuBar = new MenuBar(file);\n Group root = new Group(menuBar);\n Scene scene = new Scene(root, 595, 355, Color.BEIGE);\n stage.setTitle(\"File Chooser Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
] |
C++ ios Library - Uppercase Function
|
It is used to sets the uppercase format flag for the str stream. When the uppercase format flag is set, uppercase (capital) letters are used instead of lowercase for representations on output operations involving stream-generated letters, like some hexadecimal representations and numerical base prefixes.
Following is the declaration for std::uppercase function.
ios_base& uppercase (ios_base& str);
str − Stream object whose format flag is affected.
It returns Argument str.
Basic guarantee − if an exception is thrown, str is in a valid state.
It modifies str. Concurrent access to the same stream object may cause data races.
In below example explains about std::uppercase function.
#include <iostream>
int main () {
std::cout << std::showbase << std::hex;
std::cout << std::uppercase << 77 << '\n';
std::cout << std::nouppercase << 77 << '\n';
return 0;
}
Let us compile and run the above program, this will produce the following result −
0X4D
0x4d
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2909,
"s": 2603,
"text": "It is used to sets the uppercase format flag for the str stream. When the uppercase format flag is set, uppercase (capital) letters are used instead of lowercase for representations on output operations involving stream-generated letters, like some hexadecimal representations and numerical base prefixes."
},
{
"code": null,
"e": 2967,
"s": 2909,
"text": "Following is the declaration for std::uppercase function."
},
{
"code": null,
"e": 3004,
"s": 2967,
"text": "ios_base& uppercase (ios_base& str);"
},
{
"code": null,
"e": 3055,
"s": 3004,
"text": "str − Stream object whose format flag is affected."
},
{
"code": null,
"e": 3080,
"s": 3055,
"text": "It returns Argument str."
},
{
"code": null,
"e": 3150,
"s": 3080,
"text": "Basic guarantee − if an exception is thrown, str is in a valid state."
},
{
"code": null,
"e": 3233,
"s": 3150,
"text": "It modifies str. Concurrent access to the same stream object may cause data races."
},
{
"code": null,
"e": 3290,
"s": 3233,
"text": "In below example explains about std::uppercase function."
},
{
"code": null,
"e": 3477,
"s": 3290,
"text": "#include <iostream>\n\nint main () {\n std::cout << std::showbase << std::hex;\n std::cout << std::uppercase << 77 << '\\n';\n std::cout << std::nouppercase << 77 << '\\n';\n return 0;\n}"
},
{
"code": null,
"e": 3560,
"s": 3477,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3571,
"s": 3560,
"text": "0X4D\n0x4d\n"
},
{
"code": null,
"e": 3578,
"s": 3571,
"text": " Print"
},
{
"code": null,
"e": 3589,
"s": 3578,
"text": " Add Notes"
}
] |
How can Tensorflow be used to test, reset the model and load the latest checkpoint?
|
Tensorflow is a machine learning framework that is provided by Google. It is an open−source framework used in conjunction with Python to implement algorithms, deep learning applications and much more. It is used in research and for production purposes. It has optimization techniques that help in performing complicated mathematical operations quickly. This is because it uses NumPy and multi−dimensional arrays. These multi−dimensional arrays are also known as ‘tensors’. The framework supports working with deep neural network. It is highly scalable, and comes with many popular datasets.
The ‘tensorflow’ package can be installed on Windows using the below line of code −
pip install tensorflow
Keras was developed as a part of research for the project ONEIROS (Open ended Neuro−Electronic Intelligent Robot Operating System). Keras is a deep learning API, which is written in Python. It is a high-level API that has a productive interface that helps solve machine learning problems. It runs on top of Tensorflow framework. It was built to help experiment in a quick manner. It provides essential abstractions and building blocks that are essential in developing and encapsulating machine learning solutions.
It is highly scalable, and comes with cross platform abilities. This means Keras can be run on TPU or clusters of GPUs. Keras models can also be exported to run in a web browser or a mobile phone as well. Keras is already present within the Tensorflow package. It can be accessed using the below line of code −
import tensorflow
from tensorflow import keras
We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook.
Following is the code −
print("A new model instance is created")
model = create_model()
print("The previously saved weights are loaded")
model.load_weights(latest)
print("The model is being re−evaluated")
loss, acc = model.evaluate(test_images, test_labels, verbose=2)
print("This is the restored model, with accuracy: {:5.3f}%".format(100 * acc))
Code credit − https://www.tensorflow.org/tutorials/keras/save_and_load
A new model instance is created
The previously saved weights are loaded
The model is being re-evaluated
32/32 - 0s - loss: 0.4828 - sparse_categorical_accuracy: 0.8770
This is the restored model, with accuracy:87.700%
Again, a new model of the instance is created using the ‘create_model’ method.
Again, a new model of the instance is created using the ‘create_model’ method.
The previously saved weights are loaded to this instance using the ‘load_weights’ method.
The previously saved weights are loaded to this instance using the ‘load_weights’ method.
This new model is evaluated using the ‘evaluate’ method.
This new model is evaluated using the ‘evaluate’ method.
Its accuracy and loss during training is determined.
Its accuracy and loss during training is determined.
These values are displayed on the console.
These values are displayed on the console.
|
[
{
"code": null,
"e": 1653,
"s": 1062,
"text": "Tensorflow is a machine learning framework that is provided by Google. It is an open−source framework used in conjunction with Python to implement algorithms, deep learning applications and much more. It is used in research and for production purposes. It has optimization techniques that help in performing complicated mathematical operations quickly. This is because it uses NumPy and multi−dimensional arrays. These multi−dimensional arrays are also known as ‘tensors’. The framework supports working with deep neural network. It is highly scalable, and comes with many popular datasets."
},
{
"code": null,
"e": 1737,
"s": 1653,
"text": "The ‘tensorflow’ package can be installed on Windows using the below line of code −"
},
{
"code": null,
"e": 1760,
"s": 1737,
"text": "pip install tensorflow"
},
{
"code": null,
"e": 2274,
"s": 1760,
"text": "Keras was developed as a part of research for the project ONEIROS (Open ended Neuro−Electronic Intelligent Robot Operating System). Keras is a deep learning API, which is written in Python. It is a high-level API that has a productive interface that helps solve machine learning problems. It runs on top of Tensorflow framework. It was built to help experiment in a quick manner. It provides essential abstractions and building blocks that are essential in developing and encapsulating machine learning solutions."
},
{
"code": null,
"e": 2585,
"s": 2274,
"text": "It is highly scalable, and comes with cross platform abilities. This means Keras can be run on TPU or clusters of GPUs. Keras models can also be exported to run in a web browser or a mobile phone as well. Keras is already present within the Tensorflow package. It can be accessed using the below line of code −"
},
{
"code": null,
"e": 2632,
"s": 2585,
"text": "import tensorflow\nfrom tensorflow import keras"
},
{
"code": null,
"e": 2902,
"s": 2632,
"text": "We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook."
},
{
"code": null,
"e": 2926,
"s": 2902,
"text": "Following is the code −"
},
{
"code": null,
"e": 3250,
"s": 2926,
"text": "print(\"A new model instance is created\")\nmodel = create_model()\nprint(\"The previously saved weights are loaded\")\nmodel.load_weights(latest)\nprint(\"The model is being re−evaluated\")\nloss, acc = model.evaluate(test_images, test_labels, verbose=2)\nprint(\"This is the restored model, with accuracy: {:5.3f}%\".format(100 * acc))"
},
{
"code": null,
"e": 3322,
"s": 3250,
"text": "Code credit − https://www.tensorflow.org/tutorials/keras/save_and_load"
},
{
"code": null,
"e": 3540,
"s": 3322,
"text": "A new model instance is created\nThe previously saved weights are loaded\nThe model is being re-evaluated\n32/32 - 0s - loss: 0.4828 - sparse_categorical_accuracy: 0.8770\nThis is the restored model, with accuracy:87.700%"
},
{
"code": null,
"e": 3619,
"s": 3540,
"text": "Again, a new model of the instance is created using the ‘create_model’ method."
},
{
"code": null,
"e": 3698,
"s": 3619,
"text": "Again, a new model of the instance is created using the ‘create_model’ method."
},
{
"code": null,
"e": 3788,
"s": 3698,
"text": "The previously saved weights are loaded to this instance using the ‘load_weights’ method."
},
{
"code": null,
"e": 3878,
"s": 3788,
"text": "The previously saved weights are loaded to this instance using the ‘load_weights’ method."
},
{
"code": null,
"e": 3935,
"s": 3878,
"text": "This new model is evaluated using the ‘evaluate’ method."
},
{
"code": null,
"e": 3992,
"s": 3935,
"text": "This new model is evaluated using the ‘evaluate’ method."
},
{
"code": null,
"e": 4045,
"s": 3992,
"text": "Its accuracy and loss during training is determined."
},
{
"code": null,
"e": 4098,
"s": 4045,
"text": "Its accuracy and loss during training is determined."
},
{
"code": null,
"e": 4141,
"s": 4098,
"text": "These values are displayed on the console."
},
{
"code": null,
"e": 4184,
"s": 4141,
"text": "These values are displayed on the console."
}
] |
String Matching With FuzzyWuzzy. This tutorial will go over how to match... | by Jason Wong | Towards Data Science
|
Tutorial for Matching Sequences With the FuzzyWuzzy Library
This tutorial will go over how to match strings by their similarity. FuzzyWuzzy can save you ample amounts of time during the data science process by providing tools such as the Levenshtein distance calculation. Along with examples, I will also include some helpful tips to get the most out of FuzzyWuzzy.
String matching can be useful for a variety of situations, for example, joining two tables by an athlete’s name when it is spelled or punctuated differently in both tables. This is where FuzzyWuzzy comes in and saves the day! Instead of trying to format the strings in order to match, Fuzzywuzzy uses a some similarity ratio between two sequences and returns the similarity percentage. For a more detailed description, take a look over the documentation. Let’s start by importing the necessary libraries and go over a simple example. Although it isn’t required, python-Levenshtein is highly recommended with FuzzyWuzzy. It makes the string matching process 4–10x faster but the results may differ from difflib, a module providing classes and functions for comparing sequences.
#Installing FuzzyWuzzypip install fuzzywuzzy#Importimport fuzzywuzzyfrom fuzzywuzzy import fuzzfrom fuzzywuzzy import processStr_A = 'FuzzyWuzzy is a lifesaver!'Str_B = 'fuzzy wuzzy is a LIFE SAVER.' ratio = fuzz.ratio(Str_A.lower(), Str_B.lower())print('Similarity score: {}'.format(ratio))#OutputSimilarity score: 93
We used the ratio() function above to calculate the Levenshtein distance similarity ratio between the two strings (sequences). The similarity ratio percentage here is 93%. We can say the Str_B has a similarity of 93% to Str_A when both are lowercase.
FuzzyWuzzy also has more powerful functions to help with matching strings in more complex situations. The partial ratio() function allows us to perform substring matching. This works by taking the shortest string and matching it with all substrings that are of the same length.
Str_A = 'Chicago, Illinois' Str_B = 'Chicago'ratio = fuzz.partial_ratio(Str_A.lower(), Str_B.lower())print('Similarity score: {}'.format(ratio))#OutputSimilarity score: 100
Using the partial ratio() function above, we get a similarity ratio of 100. In the scenario of Chicago and Chicago, Illinois this can be helpful since both strings are referring to the same city. This function is also useful when matching names. For example, if one sequence was someone’s first and middle name, and the sequence you’re trying to match on is that person’s first, middle, and last name. The partial_ratio() function will return a 100% match since the person’s first and middle name are the same.
FuzzyWuzzy also has token functions that tokenize the strings, change capitals to lowercase, and remove punctuation. The token_sort_ratio() function sorts the strings alphabetically and then joins them together. Then, the fuzz.ratio() is calculated. This can come in handy when the strings you are comparing are the same in spelling but are not in the same order. Let’s use another name example.
Str_A = 'Gunner William Kline' Str_B = 'Kline, Gunner William'ratio = fuzz.token_sort_ratio(Str_A, Str_B)print('Similarity score: {}'.format(ratio))#OutputSimilarity score: 100
The token_set_ratio() function is similar to the token_sort_ratio() function above, except it takes out the common tokens before calculating the fuzz.ratio() between the new strings. This function is the most helpful when applied to a set of strings with a significant difference in lengths.
Str_A = 'The 3000 meter steeplechase winner, Soufiane El Bakkali' Str_B = 'Soufiane El Bakkali'ratio = fuzz.token_set_ratio(Str_A, Str_B)print('Similarity score: {}'.format(ratio))#OutputSimilarity score: 100
FuzzyWuzzy also comes with a handy module, process, that returns the strings along with a similarity score out of a vector of strings. All you need to do is call the extract() function after process.
choices = ["3000m Steeplechase", "Men's 3000 meter steeplechase", "3000m STEEPLECHASE MENS", "mens 3000 meter SteepleChase"] process.extract("Men's 3000 Meter Steeplechase", choices, scorer=fuzz.token_sort_ratio)#Output[("Men's 3000 meter steeplechase", 100), ('mens 3000 meter SteepleChase', 95), ('3000m STEEPLECHASE MENS', 85), ('3000m Steeplechase', 77)]
Similarly to the extract function, you can also use the process module to only extract one string with the highest similarity score by calling the extractOne() function.
choices = ["3000m Steeplechase", "Men's 3000 meter steeplechase", "3000m STEEPLECHASE MENS", "mens 3000 meter SteepleChase"]process.extractOne("Men's 3000 Meter Steeplechase", choices, scorer=fuzz.token_sort_ratio)#Output("Men's 3000 meter steeplechase", 100)
Take a look at the dataframes below, df_1 to the left and df_2 to the right df_1 contains the athletes that participated in the Summer Olympic Games. This dataframe has a name column where the athlete names are strings. If I wanted to get the results for the events these athletes participated in, I would scrape the tables and put them in a dataframe. From there, I could perform a left join with the results of the events to the dataframe(left) below. To do this I need to specify the column or index levels to join the values on.
Here, we run into the problem where some of the names from the first dataframe are not in the same format as the second dataframe. If I were to try and left join the second dataframe to the first on the name column, the values will not find a match and therefore, the values won’t be where we need them. Here, we can cast the names from each dataframe into a list, and then create a function with FuzzyWuzzy to return a dictionary holding the strings we need to replace in order to find matches for the values.
#Casting the name column of both dataframes into listsdf1_names = list(df_1.name.unique())df2_names = list(df_2.name.unique())#Defining a function to return the match and similarity score of the fuzz.ratio() scorer. The function will take in a term(name), list of terms(list_names), and a minimum similarity score(min_score) to return the match. def match_names(name, list_names, min_score=0): max_score = -1 max_name = '' for x in list_names: score = fuzz.ratio(name, x) if (score > min_score) & (score > max_score): max_name = x max_score = score return (max_name, max_score)#For loop to create a list of tuples with the first value being the name from the second dataframe (name to replace) and the second value from the first dataframe (string replacing the name value). Then, casting the list of tuples as a dictionary. names = []for x in doping_names: match = match_names(x, athlete_names, 75) if match[1] >= 75: name = ('(' + str(x), str(match[0]) + ')') names.append(name)name_dict = dict(names)name_dict#Output{'Abdelatif Chemlal': 'Abdelatif Chemlal', 'Abdelkader Hachlaf': 'Abdelkader Hachlaf', 'Abderrahim Goumri': 'Abderrahim Al-Goumri', 'Abraham Kiprotich': 'Abraham Kipchirchir Rotich', 'Abubaker Ali Kamal': 'Abubaker Ali Kamal', 'Adil Kaouch': 'Adil El-Kaouch', 'Adrián Annus': 'Adrin Zsolt Annus', 'Ahmad Hazer': 'Ahmad Hazer', 'Ahmed Faiz': 'Ahmed Ali', 'Ahmed Mohamed Dheeb': 'Mohammed Ahmed', 'Ak Hafiy Tajuddin Rositi': 'Ak Hafiy Tajuddin Rositi', 'Aleksandr Bulanov': 'Aleksandar Rakovi', 'Aleksey Lesnichiy': 'Aleksey Lesnichy', 'Alemayehu Bezabeh': 'Alemayehu Bezabeh Desta', 'Alemitu Bekele': 'Alemitu Bekele Degfa', 'Alex Schwazer': 'Alex Schwazer', 'Alicia Brown': 'Alicia Brown', 'Alissa Kallinikou': 'Alissa Kallinikou', 'Allison Randall': 'Allison Randall', 'Amaka Ogoegbunam': 'Amaka Ogoegbunam', 'Amantle Montsho': 'Amantle Montsho', 'Amina Aït Hammou': 'Amina "Mina" At Hammou', 'Amine Laâlou': 'Amine Lalou', 'Anastasios Gousis': 'Anastasios "Tasos" Gousis', 'Anastasiya Soprunova': 'Anastasiya Valeryevna Soprunova', 'Antonio David Jiménez': 'AntonioDavid Jimnez Pentinel', 'Anzhelika Shevchenko': 'Anzhelika Viktorivna Shevchenko}#Using the dictionary to replace the keys with the values in the 'name' column for the second dataframedf_2.name = df_2.name.replace(name_dict)
As you can see from the output above, when casting the list of tuples as a dictionary, we can easily replace the original string with a new one. In doing this, when I go to join the dataframes together, the values will be in the correct location on the matching name.
combined_dataframe = pd.merge(df_1, df_2, how='left', on='name')
This post introduced the FuzzyWuzzy library for string matching in Python. There are many different use cases for FuzzyWuzzy and it can definitely save you time when finding a string match. I would recommend spending some time playing around with the different functions and methods to find the most optimal solution to your problem. Thank you so much for taking the time to check out my blog!
Arias, F. (2019). Fuzzy String Matching in Python. Retrieved October 27, 2020, from https://www.datacamp.com/community/tutorials/fuzzy-string-python?utm_source=adwords_ppc
Gitau, C. (2018, March 05). Fuzzy String Matching in Python. Retrieved October 27, 2020, from https://towardsdatascience.com/fuzzy-string-matching-in-python-68f240d910fe
Fuzzywuzzy. (n.d.). Retrieved October 27, 2020, from https://pypi.org/project/fuzzywuzzy/
Ztane. (n.d.). Ztane/python-Levenshtein. Retrieved October 27, 2020, from https://github.com/ztane/python-Levenshtein/
Difflib — Helpers for computing deltas¶. (n.d.). Retrieved October 27, 2020, from https://docs.python.org/3/library/difflib.html
|
[
{
"code": null,
"e": 232,
"s": 172,
"text": "Tutorial for Matching Sequences With the FuzzyWuzzy Library"
},
{
"code": null,
"e": 538,
"s": 232,
"text": "This tutorial will go over how to match strings by their similarity. FuzzyWuzzy can save you ample amounts of time during the data science process by providing tools such as the Levenshtein distance calculation. Along with examples, I will also include some helpful tips to get the most out of FuzzyWuzzy."
},
{
"code": null,
"e": 1315,
"s": 538,
"text": "String matching can be useful for a variety of situations, for example, joining two tables by an athlete’s name when it is spelled or punctuated differently in both tables. This is where FuzzyWuzzy comes in and saves the day! Instead of trying to format the strings in order to match, Fuzzywuzzy uses a some similarity ratio between two sequences and returns the similarity percentage. For a more detailed description, take a look over the documentation. Let’s start by importing the necessary libraries and go over a simple example. Although it isn’t required, python-Levenshtein is highly recommended with FuzzyWuzzy. It makes the string matching process 4–10x faster but the results may differ from difflib, a module providing classes and functions for comparing sequences."
},
{
"code": null,
"e": 1634,
"s": 1315,
"text": "#Installing FuzzyWuzzypip install fuzzywuzzy#Importimport fuzzywuzzyfrom fuzzywuzzy import fuzzfrom fuzzywuzzy import processStr_A = 'FuzzyWuzzy is a lifesaver!'Str_B = 'fuzzy wuzzy is a LIFE SAVER.' ratio = fuzz.ratio(Str_A.lower(), Str_B.lower())print('Similarity score: {}'.format(ratio))#OutputSimilarity score: 93"
},
{
"code": null,
"e": 1885,
"s": 1634,
"text": "We used the ratio() function above to calculate the Levenshtein distance similarity ratio between the two strings (sequences). The similarity ratio percentage here is 93%. We can say the Str_B has a similarity of 93% to Str_A when both are lowercase."
},
{
"code": null,
"e": 2163,
"s": 1885,
"text": "FuzzyWuzzy also has more powerful functions to help with matching strings in more complex situations. The partial ratio() function allows us to perform substring matching. This works by taking the shortest string and matching it with all substrings that are of the same length."
},
{
"code": null,
"e": 2336,
"s": 2163,
"text": "Str_A = 'Chicago, Illinois' Str_B = 'Chicago'ratio = fuzz.partial_ratio(Str_A.lower(), Str_B.lower())print('Similarity score: {}'.format(ratio))#OutputSimilarity score: 100"
},
{
"code": null,
"e": 2847,
"s": 2336,
"text": "Using the partial ratio() function above, we get a similarity ratio of 100. In the scenario of Chicago and Chicago, Illinois this can be helpful since both strings are referring to the same city. This function is also useful when matching names. For example, if one sequence was someone’s first and middle name, and the sequence you’re trying to match on is that person’s first, middle, and last name. The partial_ratio() function will return a 100% match since the person’s first and middle name are the same."
},
{
"code": null,
"e": 3243,
"s": 2847,
"text": "FuzzyWuzzy also has token functions that tokenize the strings, change capitals to lowercase, and remove punctuation. The token_sort_ratio() function sorts the strings alphabetically and then joins them together. Then, the fuzz.ratio() is calculated. This can come in handy when the strings you are comparing are the same in spelling but are not in the same order. Let’s use another name example."
},
{
"code": null,
"e": 3420,
"s": 3243,
"text": "Str_A = 'Gunner William Kline' Str_B = 'Kline, Gunner William'ratio = fuzz.token_sort_ratio(Str_A, Str_B)print('Similarity score: {}'.format(ratio))#OutputSimilarity score: 100"
},
{
"code": null,
"e": 3712,
"s": 3420,
"text": "The token_set_ratio() function is similar to the token_sort_ratio() function above, except it takes out the common tokens before calculating the fuzz.ratio() between the new strings. This function is the most helpful when applied to a set of strings with a significant difference in lengths."
},
{
"code": null,
"e": 3921,
"s": 3712,
"text": "Str_A = 'The 3000 meter steeplechase winner, Soufiane El Bakkali' Str_B = 'Soufiane El Bakkali'ratio = fuzz.token_set_ratio(Str_A, Str_B)print('Similarity score: {}'.format(ratio))#OutputSimilarity score: 100"
},
{
"code": null,
"e": 4121,
"s": 3921,
"text": "FuzzyWuzzy also comes with a handy module, process, that returns the strings along with a similarity score out of a vector of strings. All you need to do is call the extract() function after process."
},
{
"code": null,
"e": 4500,
"s": 4121,
"text": "choices = [\"3000m Steeplechase\", \"Men's 3000 meter steeplechase\", \"3000m STEEPLECHASE MENS\", \"mens 3000 meter SteepleChase\"] process.extract(\"Men's 3000 Meter Steeplechase\", choices, scorer=fuzz.token_sort_ratio)#Output[(\"Men's 3000 meter steeplechase\", 100), ('mens 3000 meter SteepleChase', 95), ('3000m STEEPLECHASE MENS', 85), ('3000m Steeplechase', 77)]"
},
{
"code": null,
"e": 4670,
"s": 4500,
"text": "Similarly to the extract function, you can also use the process module to only extract one string with the highest similarity score by calling the extractOne() function."
},
{
"code": null,
"e": 4949,
"s": 4670,
"text": "choices = [\"3000m Steeplechase\", \"Men's 3000 meter steeplechase\", \"3000m STEEPLECHASE MENS\", \"mens 3000 meter SteepleChase\"]process.extractOne(\"Men's 3000 Meter Steeplechase\", choices, scorer=fuzz.token_sort_ratio)#Output(\"Men's 3000 meter steeplechase\", 100)"
},
{
"code": null,
"e": 5482,
"s": 4949,
"text": "Take a look at the dataframes below, df_1 to the left and df_2 to the right df_1 contains the athletes that participated in the Summer Olympic Games. This dataframe has a name column where the athlete names are strings. If I wanted to get the results for the events these athletes participated in, I would scrape the tables and put them in a dataframe. From there, I could perform a left join with the results of the events to the dataframe(left) below. To do this I need to specify the column or index levels to join the values on."
},
{
"code": null,
"e": 5993,
"s": 5482,
"text": "Here, we run into the problem where some of the names from the first dataframe are not in the same format as the second dataframe. If I were to try and left join the second dataframe to the first on the name column, the values will not find a match and therefore, the values won’t be where we need them. Here, we can cast the names from each dataframe into a list, and then create a function with FuzzyWuzzy to return a dictionary holding the strings we need to replace in order to find matches for the values."
},
{
"code": null,
"e": 8376,
"s": 5993,
"text": "#Casting the name column of both dataframes into listsdf1_names = list(df_1.name.unique())df2_names = list(df_2.name.unique())#Defining a function to return the match and similarity score of the fuzz.ratio() scorer. The function will take in a term(name), list of terms(list_names), and a minimum similarity score(min_score) to return the match. def match_names(name, list_names, min_score=0): max_score = -1 max_name = '' for x in list_names: score = fuzz.ratio(name, x) if (score > min_score) & (score > max_score): max_name = x max_score = score return (max_name, max_score)#For loop to create a list of tuples with the first value being the name from the second dataframe (name to replace) and the second value from the first dataframe (string replacing the name value). Then, casting the list of tuples as a dictionary. names = []for x in doping_names: match = match_names(x, athlete_names, 75) if match[1] >= 75: name = ('(' + str(x), str(match[0]) + ')') names.append(name)name_dict = dict(names)name_dict#Output{'Abdelatif Chemlal': 'Abdelatif Chemlal', 'Abdelkader Hachlaf': 'Abdelkader Hachlaf', 'Abderrahim Goumri': 'Abderrahim Al-Goumri', 'Abraham Kiprotich': 'Abraham Kipchirchir Rotich', 'Abubaker Ali Kamal': 'Abubaker Ali Kamal', 'Adil Kaouch': 'Adil El-Kaouch', 'Adrián Annus': 'Adrin Zsolt Annus', 'Ahmad Hazer': 'Ahmad Hazer', 'Ahmed Faiz': 'Ahmed Ali', 'Ahmed Mohamed Dheeb': 'Mohammed Ahmed', 'Ak Hafiy Tajuddin Rositi': 'Ak Hafiy Tajuddin Rositi', 'Aleksandr Bulanov': 'Aleksandar Rakovi', 'Aleksey Lesnichiy': 'Aleksey Lesnichy', 'Alemayehu Bezabeh': 'Alemayehu Bezabeh Desta', 'Alemitu Bekele': 'Alemitu Bekele Degfa', 'Alex Schwazer': 'Alex Schwazer', 'Alicia Brown': 'Alicia Brown', 'Alissa Kallinikou': 'Alissa Kallinikou', 'Allison Randall': 'Allison Randall', 'Amaka Ogoegbunam': 'Amaka Ogoegbunam', 'Amantle Montsho': 'Amantle Montsho', 'Amina Aït Hammou': 'Amina \"Mina\" At Hammou', 'Amine Laâlou': 'Amine Lalou', 'Anastasios Gousis': 'Anastasios \"Tasos\" Gousis', 'Anastasiya Soprunova': 'Anastasiya Valeryevna Soprunova', 'Antonio David Jiménez': 'AntonioDavid Jimnez Pentinel', 'Anzhelika Shevchenko': 'Anzhelika Viktorivna Shevchenko}#Using the dictionary to replace the keys with the values in the 'name' column for the second dataframedf_2.name = df_2.name.replace(name_dict)"
},
{
"code": null,
"e": 8644,
"s": 8376,
"text": "As you can see from the output above, when casting the list of tuples as a dictionary, we can easily replace the original string with a new one. In doing this, when I go to join the dataframes together, the values will be in the correct location on the matching name."
},
{
"code": null,
"e": 8709,
"s": 8644,
"text": "combined_dataframe = pd.merge(df_1, df_2, how='left', on='name')"
},
{
"code": null,
"e": 9103,
"s": 8709,
"text": "This post introduced the FuzzyWuzzy library for string matching in Python. There are many different use cases for FuzzyWuzzy and it can definitely save you time when finding a string match. I would recommend spending some time playing around with the different functions and methods to find the most optimal solution to your problem. Thank you so much for taking the time to check out my blog!"
},
{
"code": null,
"e": 9275,
"s": 9103,
"text": "Arias, F. (2019). Fuzzy String Matching in Python. Retrieved October 27, 2020, from https://www.datacamp.com/community/tutorials/fuzzy-string-python?utm_source=adwords_ppc"
},
{
"code": null,
"e": 9445,
"s": 9275,
"text": "Gitau, C. (2018, March 05). Fuzzy String Matching in Python. Retrieved October 27, 2020, from https://towardsdatascience.com/fuzzy-string-matching-in-python-68f240d910fe"
},
{
"code": null,
"e": 9535,
"s": 9445,
"text": "Fuzzywuzzy. (n.d.). Retrieved October 27, 2020, from https://pypi.org/project/fuzzywuzzy/"
},
{
"code": null,
"e": 9654,
"s": 9535,
"text": "Ztane. (n.d.). Ztane/python-Levenshtein. Retrieved October 27, 2020, from https://github.com/ztane/python-Levenshtein/"
}
] |
Tryit Editor v3.7
|
HTML form elements
Tryit: input element
|
[
{
"code": null,
"e": 29,
"s": 10,
"text": "HTML form elements"
}
] |
Introduction to Graph Neural Networks with DeepWalk | by Mohit Mayank | Towards Data Science
|
Graph Neural Networks are the current hot topic [1]. And this interest is surely justified as GNNs are all about latent representation of the graph in vector space. Representing an entity as a vector is nothing new. There are many examples like word2vec and Gloves embeddings in NLP which transforms a word into a vector. What makes such representation powerful are (1) these vectors incorporate a notion of similarity among them i.e. two words who are similar to each other tend to be closer in the vector space (dot product is large), and (2) they have application in diverse downstream problems like classification, clustering, etc. This is what makes GNN interesting, as while there are many solutions to embed a word or image as a vector, GNN laid the foundation to do so for graphs. In this post, we will discuss one of the initial and basic approaches to do so — DeepWalk [2]
Graph or Networks is used to represent relational data, where the main entities are called nodes. A relationship between nodes is represented by edges. A graph can be made complex by adding multiple types of nodes, edges, direction to edges, or even weights to edges.
One example of a graph is shown in Figure 1. The graph is the Karate dataset [4] which represents the social information of the members of a university karate club. Each node represents a member of the club, and each edge represents a tie between two members of the club. The left info bar states several graph properties like a number of nodes, edges, density, degree, etc. Network repository [3] contains many such networks from different fields and domains and provides visualization tools and basic stats as shown above.
As the idea behind vector embedding is to highlight similarities, we will consider some definitions for similar nodes. Two nodes can be called similar by several ways, like if they have a similar — in-degree count, out-degree count, avg-degree, or no of neighbors, etc. One interesting notion is to consider the neighbors of nodes and the more common neighbors they share, more similar they are. In plain text, a node is defined by the company it keeps. If two nodes have very similar company, they are very similar. This idea of representing an entity by its locality is not new. The base of word embedding in NLP is based on the motto that, “a word is represented by the context it keeps”. With this much similarity between the two fields, its obvious that the first instinct was to leverage the existing techniques in NLP, port it to graph domains by somehow converting the idea of context of words to neighbors of nodes. One such existing technique is word2vec, which we will discuss briefly.
A detour with word2vec (w2v) is required to completely appreciate and understand the idea behind DeepWalk. Word2Vec is a word embedding technique that represents a word as a vector. Each vector can be thought of as a point in $R^{D}$ space, where $D$ is the dimension of each vector. One thing to note is that these vectors are not randomly spread out in the vector space. They follow certain properties such that, words who are similar like cat and tiger are relatively closer to each other than a completely unrelated word like tank. In the vector space, this means their cosine similarity score is higher. Along with this, we can even observe famous analogies like king - man + woman = queen which can be replicated by vector addition of these word's representation vector.
While such representation is not unique to w2v, its major contribution was to provide a simple and faster neural network based word embedder. To do so, w2v transformed the training as a classification problem where given one word the networks try to answer which word is most probable to be found in the context of the given word. This technique is formally called Skip-gram, where input is the middle word and output is context word. This is done by creating a 1-layer deep neural network where the input word is fed in one-hot encoded format and output is softmax with ideally large value to context word.
The training data is prepared by sliding a window (of some window size) across the corpus of large text (which could be articles or novels or even complete Wikipedia), and for each such window the middle word is the input word and the remaining words in the context are output words. For each input word in vector space, we want the context words to be close but the remaining words far. And if two input words will have similar context words, their vector will also be close. This is the intuition behind Word2Vec which it does by using negative sampling. After training we can observe something interesting — the weights between the Input-Hidden layer of NN now represent the notions we wanted in our word embeddings, such that words with the same context have similar values across vector dimension. And these weights are used as word embeddings.
The result in Figure 4 is from training 5D word embeddings from a cool interactive w2v demo Wevi [5]. As obvious words like (juice, milk, water) and (orange, apple) have similar kinds of vectors (some dimensions are equally lit — red or blue). Interested readers can go to [7] for a detailed understanding of the architecture and maths. Also [5] is suggested for excellent visualization of the engine behind word2vec.
DeepWalk employs the same training technique as of w2v i.e. skip-gram. But one important thing remaining is to create training data that captures the notion of context in graphs. This is done by random walk technique, where we start from one node and randomly go to one of its neighbors. We repeat this process $L$ time which is the length of the random walk. After this, we restart the process again. If we do this for all nodes (and $M$ times for each node) we have in some sense transformed the graph structure into a text like corpus used to train w2v where each word is a node and its context defines its neighbor.
The DeepWalk authors provide a python implementation here. Installation details with other pre-requisite are provided in the readme (windows user be vary of some installation and execution issues). The CLI API exposes several algorithmic and optimization parameters like,
input requires the path of the input file which contains graph information. A graph can be stored in several formats, some of the famous (and supported by the code) are — adjacency list (node-all_neighbors list) and edge list (node-node pair which have an edge).
number-walks The number of random walks taken for each node.
representation-size the dimension of final embedding of each node. Also the size of hidden layer in the skipgram model.
walk-length the length of each random walk.
window-size the context window size in the skipgram training.
workers optimization parameter defining number of independent process to spawn for the training.
output the path to output embedding file.
Authors have also provided example graphs, one of which is our Karate club dataset. It's stored in the format of the adjacency list.
Now let’s read the graph data and create node embeddings by,
deepwalk --input example_graphs/karate.adjlist --number-walks 10--representation-size 64 --walk-length 40 --window-size 5 --workers 8 --output trained_model/karate.embeddings
This performs start-to-end analysis by taking care of — loading the graph from the file, generating random walks, and finally training skip-gram model on the walk data. By running this with additional --max-memory-data-size 0 param, the script also stores the walk data as shown below.
Finally, we get the output embedding file which contains vector embedding for each node in the graph. The file looks as,
A much simpler API is provided by newly released python implementation — KarateClub [6]. To do the same set of actions, all we need to do is following.
# import librariesimport networkx as nx from karateclub import DeepWalk# load the karate club datasetG = nx.karate_club_graph()# load the DeepWalk model and set parametersdw = DeepWalk(dimensions=64)# fit the modeldw.fit(G)# extract embeddingsembedding = dw.get_embedding()
The DeepWalk class also extends the same parameters exposed by the author's code and can be tweaked to do the desired experiment.
To see DeepWalk in action, we will pick one graph and visualize the network as well as the final embeddings. For better understanding, I created a union of 3 complete graphs with some additional edges to connect each graph.
Now, we will create DeepWalk embeddings of the graph. For this, we can use the KarateClub package and by running DeepWalk on default settings we get embeddings of 128 dimensions. To visualize this I use dimensionality reduction technique PCA, which scaled-down embeddings from R128 to R2. I will also plot the 128D heatmap of the embedding on the side.
There is a clear segregation of nodes in the left chart which denotes the vector space of the embedding. This showcase how DeepWalk can transform a graph from force layout visualization to vector space visualization while maintaining some of the structural properties. The heatmap plot also hints to a clear segregation of graph into 3 clusters.
Another important thing to note is when the graph is not so complex, we can get by with lower dimension embedding as well. This not only reduces the dimensions but also improves the optimization and convergence as there are fewer parameters in skip-gram to train. To prove this we will create embedding of only size 2. This can be done by setting the parameter in DeepWalk object dw = DeepWalk(dimensions=2) . We will again visualize the same plots.
Both the plots again hint towards the same number of clusters in the graph, and all this by only using 1% of the previous dimensions (from 128 to 2 i.e. ~1%).
As the answer to this analogy NLP - word2vec + GraphNeuralNetworks = ? can arguably be DeepWalk (is it? 🙂 ), it leads to two interesting points, (1) DeepWalk's impact in GNN can be analogous to Word2Vec's in NLP. And it's true as DeepWalk was one of the first approaches to use NN for node embeddings. It was also a cool example of how some proven SOTA technique from another domain (here, NLP) can be ported to and applied in a completely different domain (here, graphs). This leads to the second point, (2) As DeepWalk was published a while ago (in 2014 - only 6 years but a lifetime in AI research), currently, there are lots of other techniques which can be applied to do the job in a better way like Node2Vec or even Graph convolution networks like GraphSAGE, etc. That said, as to start with NN based NLP, word2vec is the best starting point, I think DeepWalk is in the same sense a good beginning for NN based graph analysis. And hence the topic of this article.
Cheers.
[1] EasyAI — GNN may be the future of AI
[2] DeepWalk — Paper | Code
[3] Network repository
[4] Zachary karate club — The KONECT Project
[5] Wevi — word embedding visual inspector
[6] Karate club — Paper | Code
[7] Lil’Log — Learning word embedding
|
[
{
"code": null,
"e": 1055,
"s": 172,
"text": "Graph Neural Networks are the current hot topic [1]. And this interest is surely justified as GNNs are all about latent representation of the graph in vector space. Representing an entity as a vector is nothing new. There are many examples like word2vec and Gloves embeddings in NLP which transforms a word into a vector. What makes such representation powerful are (1) these vectors incorporate a notion of similarity among them i.e. two words who are similar to each other tend to be closer in the vector space (dot product is large), and (2) they have application in diverse downstream problems like classification, clustering, etc. This is what makes GNN interesting, as while there are many solutions to embed a word or image as a vector, GNN laid the foundation to do so for graphs. In this post, we will discuss one of the initial and basic approaches to do so — DeepWalk [2]"
},
{
"code": null,
"e": 1323,
"s": 1055,
"text": "Graph or Networks is used to represent relational data, where the main entities are called nodes. A relationship between nodes is represented by edges. A graph can be made complex by adding multiple types of nodes, edges, direction to edges, or even weights to edges."
},
{
"code": null,
"e": 1848,
"s": 1323,
"text": "One example of a graph is shown in Figure 1. The graph is the Karate dataset [4] which represents the social information of the members of a university karate club. Each node represents a member of the club, and each edge represents a tie between two members of the club. The left info bar states several graph properties like a number of nodes, edges, density, degree, etc. Network repository [3] contains many such networks from different fields and domains and provides visualization tools and basic stats as shown above."
},
{
"code": null,
"e": 2845,
"s": 1848,
"text": "As the idea behind vector embedding is to highlight similarities, we will consider some definitions for similar nodes. Two nodes can be called similar by several ways, like if they have a similar — in-degree count, out-degree count, avg-degree, or no of neighbors, etc. One interesting notion is to consider the neighbors of nodes and the more common neighbors they share, more similar they are. In plain text, a node is defined by the company it keeps. If two nodes have very similar company, they are very similar. This idea of representing an entity by its locality is not new. The base of word embedding in NLP is based on the motto that, “a word is represented by the context it keeps”. With this much similarity between the two fields, its obvious that the first instinct was to leverage the existing techniques in NLP, port it to graph domains by somehow converting the idea of context of words to neighbors of nodes. One such existing technique is word2vec, which we will discuss briefly."
},
{
"code": null,
"e": 3622,
"s": 2845,
"text": "A detour with word2vec (w2v) is required to completely appreciate and understand the idea behind DeepWalk. Word2Vec is a word embedding technique that represents a word as a vector. Each vector can be thought of as a point in $R^{D}$ space, where $D$ is the dimension of each vector. One thing to note is that these vectors are not randomly spread out in the vector space. They follow certain properties such that, words who are similar like cat and tiger are relatively closer to each other than a completely unrelated word like tank. In the vector space, this means their cosine similarity score is higher. Along with this, we can even observe famous analogies like king - man + woman = queen which can be replicated by vector addition of these word's representation vector."
},
{
"code": null,
"e": 4230,
"s": 3622,
"text": "While such representation is not unique to w2v, its major contribution was to provide a simple and faster neural network based word embedder. To do so, w2v transformed the training as a classification problem where given one word the networks try to answer which word is most probable to be found in the context of the given word. This technique is formally called Skip-gram, where input is the middle word and output is context word. This is done by creating a 1-layer deep neural network where the input word is fed in one-hot encoded format and output is softmax with ideally large value to context word."
},
{
"code": null,
"e": 5080,
"s": 4230,
"text": "The training data is prepared by sliding a window (of some window size) across the corpus of large text (which could be articles or novels or even complete Wikipedia), and for each such window the middle word is the input word and the remaining words in the context are output words. For each input word in vector space, we want the context words to be close but the remaining words far. And if two input words will have similar context words, their vector will also be close. This is the intuition behind Word2Vec which it does by using negative sampling. After training we can observe something interesting — the weights between the Input-Hidden layer of NN now represent the notions we wanted in our word embeddings, such that words with the same context have similar values across vector dimension. And these weights are used as word embeddings."
},
{
"code": null,
"e": 5498,
"s": 5080,
"text": "The result in Figure 4 is from training 5D word embeddings from a cool interactive w2v demo Wevi [5]. As obvious words like (juice, milk, water) and (orange, apple) have similar kinds of vectors (some dimensions are equally lit — red or blue). Interested readers can go to [7] for a detailed understanding of the architecture and maths. Also [5] is suggested for excellent visualization of the engine behind word2vec."
},
{
"code": null,
"e": 6118,
"s": 5498,
"text": "DeepWalk employs the same training technique as of w2v i.e. skip-gram. But one important thing remaining is to create training data that captures the notion of context in graphs. This is done by random walk technique, where we start from one node and randomly go to one of its neighbors. We repeat this process $L$ time which is the length of the random walk. After this, we restart the process again. If we do this for all nodes (and $M$ times for each node) we have in some sense transformed the graph structure into a text like corpus used to train w2v where each word is a node and its context defines its neighbor."
},
{
"code": null,
"e": 6390,
"s": 6118,
"text": "The DeepWalk authors provide a python implementation here. Installation details with other pre-requisite are provided in the readme (windows user be vary of some installation and execution issues). The CLI API exposes several algorithmic and optimization parameters like,"
},
{
"code": null,
"e": 6653,
"s": 6390,
"text": "input requires the path of the input file which contains graph information. A graph can be stored in several formats, some of the famous (and supported by the code) are — adjacency list (node-all_neighbors list) and edge list (node-node pair which have an edge)."
},
{
"code": null,
"e": 6714,
"s": 6653,
"text": "number-walks The number of random walks taken for each node."
},
{
"code": null,
"e": 6834,
"s": 6714,
"text": "representation-size the dimension of final embedding of each node. Also the size of hidden layer in the skipgram model."
},
{
"code": null,
"e": 6878,
"s": 6834,
"text": "walk-length the length of each random walk."
},
{
"code": null,
"e": 6940,
"s": 6878,
"text": "window-size the context window size in the skipgram training."
},
{
"code": null,
"e": 7037,
"s": 6940,
"text": "workers optimization parameter defining number of independent process to spawn for the training."
},
{
"code": null,
"e": 7079,
"s": 7037,
"text": "output the path to output embedding file."
},
{
"code": null,
"e": 7212,
"s": 7079,
"text": "Authors have also provided example graphs, one of which is our Karate club dataset. It's stored in the format of the adjacency list."
},
{
"code": null,
"e": 7273,
"s": 7212,
"text": "Now let’s read the graph data and create node embeddings by,"
},
{
"code": null,
"e": 7448,
"s": 7273,
"text": "deepwalk --input example_graphs/karate.adjlist --number-walks 10--representation-size 64 --walk-length 40 --window-size 5 --workers 8 --output trained_model/karate.embeddings"
},
{
"code": null,
"e": 7734,
"s": 7448,
"text": "This performs start-to-end analysis by taking care of — loading the graph from the file, generating random walks, and finally training skip-gram model on the walk data. By running this with additional --max-memory-data-size 0 param, the script also stores the walk data as shown below."
},
{
"code": null,
"e": 7855,
"s": 7734,
"text": "Finally, we get the output embedding file which contains vector embedding for each node in the graph. The file looks as,"
},
{
"code": null,
"e": 8007,
"s": 7855,
"text": "A much simpler API is provided by newly released python implementation — KarateClub [6]. To do the same set of actions, all we need to do is following."
},
{
"code": null,
"e": 8281,
"s": 8007,
"text": "# import librariesimport networkx as nx from karateclub import DeepWalk# load the karate club datasetG = nx.karate_club_graph()# load the DeepWalk model and set parametersdw = DeepWalk(dimensions=64)# fit the modeldw.fit(G)# extract embeddingsembedding = dw.get_embedding()"
},
{
"code": null,
"e": 8411,
"s": 8281,
"text": "The DeepWalk class also extends the same parameters exposed by the author's code and can be tweaked to do the desired experiment."
},
{
"code": null,
"e": 8635,
"s": 8411,
"text": "To see DeepWalk in action, we will pick one graph and visualize the network as well as the final embeddings. For better understanding, I created a union of 3 complete graphs with some additional edges to connect each graph."
},
{
"code": null,
"e": 8988,
"s": 8635,
"text": "Now, we will create DeepWalk embeddings of the graph. For this, we can use the KarateClub package and by running DeepWalk on default settings we get embeddings of 128 dimensions. To visualize this I use dimensionality reduction technique PCA, which scaled-down embeddings from R128 to R2. I will also plot the 128D heatmap of the embedding on the side."
},
{
"code": null,
"e": 9334,
"s": 8988,
"text": "There is a clear segregation of nodes in the left chart which denotes the vector space of the embedding. This showcase how DeepWalk can transform a graph from force layout visualization to vector space visualization while maintaining some of the structural properties. The heatmap plot also hints to a clear segregation of graph into 3 clusters."
},
{
"code": null,
"e": 9784,
"s": 9334,
"text": "Another important thing to note is when the graph is not so complex, we can get by with lower dimension embedding as well. This not only reduces the dimensions but also improves the optimization and convergence as there are fewer parameters in skip-gram to train. To prove this we will create embedding of only size 2. This can be done by setting the parameter in DeepWalk object dw = DeepWalk(dimensions=2) . We will again visualize the same plots."
},
{
"code": null,
"e": 9943,
"s": 9784,
"text": "Both the plots again hint towards the same number of clusters in the graph, and all this by only using 1% of the previous dimensions (from 128 to 2 i.e. ~1%)."
},
{
"code": null,
"e": 10913,
"s": 9943,
"text": "As the answer to this analogy NLP - word2vec + GraphNeuralNetworks = ? can arguably be DeepWalk (is it? 🙂 ), it leads to two interesting points, (1) DeepWalk's impact in GNN can be analogous to Word2Vec's in NLP. And it's true as DeepWalk was one of the first approaches to use NN for node embeddings. It was also a cool example of how some proven SOTA technique from another domain (here, NLP) can be ported to and applied in a completely different domain (here, graphs). This leads to the second point, (2) As DeepWalk was published a while ago (in 2014 - only 6 years but a lifetime in AI research), currently, there are lots of other techniques which can be applied to do the job in a better way like Node2Vec or even Graph convolution networks like GraphSAGE, etc. That said, as to start with NN based NLP, word2vec is the best starting point, I think DeepWalk is in the same sense a good beginning for NN based graph analysis. And hence the topic of this article."
},
{
"code": null,
"e": 10921,
"s": 10913,
"text": "Cheers."
},
{
"code": null,
"e": 10962,
"s": 10921,
"text": "[1] EasyAI — GNN may be the future of AI"
},
{
"code": null,
"e": 10990,
"s": 10962,
"text": "[2] DeepWalk — Paper | Code"
},
{
"code": null,
"e": 11013,
"s": 10990,
"text": "[3] Network repository"
},
{
"code": null,
"e": 11058,
"s": 11013,
"text": "[4] Zachary karate club — The KONECT Project"
},
{
"code": null,
"e": 11101,
"s": 11058,
"text": "[5] Wevi — word embedding visual inspector"
},
{
"code": null,
"e": 11132,
"s": 11101,
"text": "[6] Karate club — Paper | Code"
}
] |
Different ways to represent N as sum of K non-zero integers - GeeksforGeeks
|
11 Aug, 2021
Given N and K. The task is to find out how many different ways there are to represent N as the sum of K non-zero integers.
Examples:
Input: N = 5, K = 3 Output: 6 The possible combinations of integers are: ( 1, 1, 3 ) ( 1, 3, 1 ) ( 3, 1, 1 ) ( 1, 2, 2 ) ( 2, 2, 1 ) ( 2, 1, 2 )
Input: N = 10, K = 4 Output: 84
The approach to the problem is to observe a sequence and use combinations to solve the problem. To obtain a number N, N 1’s are required, summation of N 1’s will give N. The problem allows you to use K integers only to make N.
Observation:
Let's take N = 5 and K = 3, then all
possible combinations of K numbers are: ( 1, 1, 3 )
( 1, 3, 1 )
( 3, 1, 1 )
( 1, 2, 2 )
( 2, 2, 1 )
( 2, 1, 2 )
The above can be rewritten as: ( 1, 1, 1 + 1 + 1 )
( 1, 1 + 1 + 1, 1 )
( 1 + 1 + 1, 1, 1 )
( 1, 1 + 1, 1 + 1 )
( 1 + 1, 1 + 1, 1 )
( 1 + 1, 1, 1 + 1 )
From above, a conclusion can be drawn that of N 1’s, k-1 commas have to be placed in between N 1’s and the remaining places are to be filled with ‘+’ signs. All combinations of placing k-1 commas and placing ‘+’ signs in the remaining places will be the answer. So, in general, for N there will be N-1 spaces between all 1, and out of those choose k-1 and place a comma in between those 1. In between the rest 1’s, place ‘+’ signs. So the way of choosing K-1 objects out of N-1 is . The dynamic programming approach is used to calculate .
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to calculate Different ways to// represent N as sum of K non-zero integers.#include <bits/stdc++.h>using namespace std; // Returns value of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ int C[n + 1][k + 1]; int i, j; // Calculate value of Binomial Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Driver Codeint main(){ int n = 5, k = 3; cout << "Total number of different ways are " << binomialCoeff(n - 1, k - 1); return 0;}
// Java program to calculate// Different ways to represent// N as sum of K non-zero integers.import java.io.*; class GFG{ // Returns value of Binomial// Coefficient C(n, k)static int binomialCoeff(int n, int k){ int C[][] = new int [n + 1][k + 1]; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Driver Codepublic static void main (String[] args){ int n = 5, k = 3; System.out.println( "Total number of " + "different ways are " + binomialCoeff(n - 1, k - 1));}} // This code is contributed// by anuj_67.
# python 3 program to calculate Different ways to# represent N as sum of K non-zero integers. # Returns value of Binomial Coefficient C(n, k)def binomialCoeff(n, k): C = [[0 for i in range(k+1)]for i in range(n+1)] # Calculate value of Binomial Coefficient in bottom up manner for i in range(0,n+1,1): for j in range(0,min(i, k)+1,1): # Base Cases if (j == 0 or j == i): C[i][j] = 1 # Calculate value using previously stored values else: C[i][j] = C[i - 1][j - 1] + C[i - 1][j] return C[n][k] # Driver Codeif __name__ == '__main__': n = 5 k = 3 print("Total number of different ways are",binomialCoeff(n - 1, k - 1)) # This code is contributed by# Sanjit_Prasad
// C# program to calculate// Different ways to represent// N as sum of K non-zero integers.using System; class GFG{ // Returns value of Binomial// Coefficient C(n, k)static int binomialCoeff(int n, int k){ int [,]C = new int [n + 1, k + 1]; int i, j; // Calculate value of // Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.Min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i, j] = 1; // Calculate value using // previously stored values else C[i, j] = C[i - 1, j - 1] + C[i - 1, j]; } } return C[n,k];} // Driver Codepublic static void Main (){ int n = 5, k = 3; Console.WriteLine( "Total number of " + "different ways are " + binomialCoeff(n - 1, k - 1));}} // This code is contributed// by anuj_67.
<?php// PHP program to calculate// Different ways to represent// N as sum of K non-zero integers. // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff($n, $k){ $C = array(array()); $i; $j; // Calculate value of Binomial // Coefficient in bottom up manner for ($i = 0; $i <= $n; $i++) { for ($j = 0; $j <= min($i, $k); $j++) { // Base Cases if ($j == 0 or $j == $i) $C[$i][$j] = 1; // Calculate value using // previously stored values else $C[$i][$j] = $C[$i - 1][$j - 1] + $C[$i - 1][$j]; } } return $C[$n][$k];} // Driver Code$n = 5; $k = 3;echo "Total number of " , "different ways are " , binomialCoeff($n - 1, $k - 1); // This code is contributed// by anuj_67.?>
<script> // Javascript program to calculate // Different ways to represent // N as sum of K non-zero integers. // Returns value of Binomial // Coefficient C(n, k) function binomialCoeff(n, k) { let C = new Array(n + 1); for(let i = 0; i < n + 1; i ++) { C[i] = new Array(k + 1); for(let j = 0; j < k + 1; j++) { C[i][j] = 0; } } let i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k]; } let n = 5, k = 3; document.write( "Total number of " + "different ways are " + binomialCoeff(n - 1, k - 1)); </script>
Total number of different ways are 6
Time Complexity: O(N * K)Auxiliary Space: O(N * K)
vt_m
Sanjit_Prasad
Akanksha_Rai
nidhi_biet
suresh07
pankajsharmagfg
Algorithms-Dynamic Programming
Permutation and Combination
Algorithms
Combinatorial
Combinatorial
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
Quadratic Probing in Hashing
Introduction to Algorithms
Uniform-Cost Search (Dijkstra for large Graphs)
DSA Sheet by Love Babbar
Write a program to print all permutations of a given string
Permutation and Combination in Python
itertools.combinations() module in Python to print all possible combinations
Heap's Algorithm for generating permutations
Factorial of a large number
|
[
{
"code": null,
"e": 24935,
"s": 24907,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 25058,
"s": 24935,
"text": "Given N and K. The task is to find out how many different ways there are to represent N as the sum of K non-zero integers."
},
{
"code": null,
"e": 25069,
"s": 25058,
"text": "Examples: "
},
{
"code": null,
"e": 25214,
"s": 25069,
"text": "Input: N = 5, K = 3 Output: 6 The possible combinations of integers are: ( 1, 1, 3 ) ( 1, 3, 1 ) ( 3, 1, 1 ) ( 1, 2, 2 ) ( 2, 2, 1 ) ( 2, 1, 2 )"
},
{
"code": null,
"e": 25246,
"s": 25214,
"text": "Input: N = 10, K = 4 Output: 84"
},
{
"code": null,
"e": 25474,
"s": 25246,
"text": "The approach to the problem is to observe a sequence and use combinations to solve the problem. To obtain a number N, N 1’s are required, summation of N 1’s will give N. The problem allows you to use K integers only to make N. "
},
{
"code": null,
"e": 25489,
"s": 25474,
"text": "Observation: "
},
{
"code": null,
"e": 26146,
"s": 25489,
"text": "Let's take N = 5 and K = 3, then all \npossible combinations of K numbers are: ( 1, 1, 3 )\n ( 1, 3, 1 )\n ( 3, 1, 1 )\n ( 1, 2, 2 )\n ( 2, 2, 1 )\n ( 2, 1, 2 )\n\nThe above can be rewritten as: ( 1, 1, 1 + 1 + 1 )\n ( 1, 1 + 1 + 1, 1 )\n ( 1 + 1 + 1, 1, 1 )\n ( 1, 1 + 1, 1 + 1 )\n ( 1 + 1, 1 + 1, 1 )\n ( 1 + 1, 1, 1 + 1 )"
},
{
"code": null,
"e": 26686,
"s": 26146,
"text": "From above, a conclusion can be drawn that of N 1’s, k-1 commas have to be placed in between N 1’s and the remaining places are to be filled with ‘+’ signs. All combinations of placing k-1 commas and placing ‘+’ signs in the remaining places will be the answer. So, in general, for N there will be N-1 spaces between all 1, and out of those choose k-1 and place a comma in between those 1. In between the rest 1’s, place ‘+’ signs. So the way of choosing K-1 objects out of N-1 is . The dynamic programming approach is used to calculate . "
},
{
"code": null,
"e": 26738,
"s": 26686,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26742,
"s": 26738,
"text": "C++"
},
{
"code": null,
"e": 26747,
"s": 26742,
"text": "Java"
},
{
"code": null,
"e": 26755,
"s": 26747,
"text": "Python3"
},
{
"code": null,
"e": 26758,
"s": 26755,
"text": "C#"
},
{
"code": null,
"e": 26762,
"s": 26758,
"text": "PHP"
},
{
"code": null,
"e": 26773,
"s": 26762,
"text": "Javascript"
},
{
"code": "// CPP program to calculate Different ways to// represent N as sum of K non-zero integers.#include <bits/stdc++.h>using namespace std; // Returns value of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ int C[n + 1][k + 1]; int i, j; // Calculate value of Binomial Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Driver Codeint main(){ int n = 5, k = 3; cout << \"Total number of different ways are \" << binomialCoeff(n - 1, k - 1); return 0;}",
"e": 27570,
"s": 26773,
"text": null
},
{
"code": "// Java program to calculate// Different ways to represent// N as sum of K non-zero integers.import java.io.*; class GFG{ // Returns value of Binomial// Coefficient C(n, k)static int binomialCoeff(int n, int k){ int C[][] = new int [n + 1][k + 1]; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Driver Codepublic static void main (String[] args){ int n = 5, k = 3; System.out.println( \"Total number of \" + \"different ways are \" + binomialCoeff(n - 1, k - 1));}} // This code is contributed// by anuj_67.",
"e": 28622,
"s": 27570,
"text": null
},
{
"code": "# python 3 program to calculate Different ways to# represent N as sum of K non-zero integers. # Returns value of Binomial Coefficient C(n, k)def binomialCoeff(n, k): C = [[0 for i in range(k+1)]for i in range(n+1)] # Calculate value of Binomial Coefficient in bottom up manner for i in range(0,n+1,1): for j in range(0,min(i, k)+1,1): # Base Cases if (j == 0 or j == i): C[i][j] = 1 # Calculate value using previously stored values else: C[i][j] = C[i - 1][j - 1] + C[i - 1][j] return C[n][k] # Driver Codeif __name__ == '__main__': n = 5 k = 3 print(\"Total number of different ways are\",binomialCoeff(n - 1, k - 1)) # This code is contributed by# Sanjit_Prasad",
"e": 29393,
"s": 28622,
"text": null
},
{
"code": "// C# program to calculate// Different ways to represent// N as sum of K non-zero integers.using System; class GFG{ // Returns value of Binomial// Coefficient C(n, k)static int binomialCoeff(int n, int k){ int [,]C = new int [n + 1, k + 1]; int i, j; // Calculate value of // Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.Min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i, j] = 1; // Calculate value using // previously stored values else C[i, j] = C[i - 1, j - 1] + C[i - 1, j]; } } return C[n,k];} // Driver Codepublic static void Main (){ int n = 5, k = 3; Console.WriteLine( \"Total number of \" + \"different ways are \" + binomialCoeff(n - 1, k - 1));}} // This code is contributed// by anuj_67.",
"e": 30446,
"s": 29393,
"text": null
},
{
"code": "<?php// PHP program to calculate// Different ways to represent// N as sum of K non-zero integers. // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff($n, $k){ $C = array(array()); $i; $j; // Calculate value of Binomial // Coefficient in bottom up manner for ($i = 0; $i <= $n; $i++) { for ($j = 0; $j <= min($i, $k); $j++) { // Base Cases if ($j == 0 or $j == $i) $C[$i][$j] = 1; // Calculate value using // previously stored values else $C[$i][$j] = $C[$i - 1][$j - 1] + $C[$i - 1][$j]; } } return $C[$n][$k];} // Driver Code$n = 5; $k = 3;echo \"Total number of \" , \"different ways are \" , binomialCoeff($n - 1, $k - 1); // This code is contributed// by anuj_67.?>",
"e": 31325,
"s": 30446,
"text": null
},
{
"code": "<script> // Javascript program to calculate // Different ways to represent // N as sum of K non-zero integers. // Returns value of Binomial // Coefficient C(n, k) function binomialCoeff(n, k) { let C = new Array(n + 1); for(let i = 0; i < n + 1; i ++) { C[i] = new Array(k + 1); for(let j = 0; j < k + 1; j++) { C[i][j] = 0; } } let i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k]; } let n = 5, k = 3; document.write( \"Total number of \" + \"different ways are \" + binomialCoeff(n - 1, k - 1)); </script>",
"e": 32524,
"s": 31325,
"text": null
},
{
"code": null,
"e": 32561,
"s": 32524,
"text": "Total number of different ways are 6"
},
{
"code": null,
"e": 32615,
"s": 32563,
"text": "Time Complexity: O(N * K)Auxiliary Space: O(N * K) "
},
{
"code": null,
"e": 32620,
"s": 32615,
"text": "vt_m"
},
{
"code": null,
"e": 32634,
"s": 32620,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 32647,
"s": 32634,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 32658,
"s": 32647,
"text": "nidhi_biet"
},
{
"code": null,
"e": 32667,
"s": 32658,
"text": "suresh07"
},
{
"code": null,
"e": 32683,
"s": 32667,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 32714,
"s": 32683,
"text": "Algorithms-Dynamic Programming"
},
{
"code": null,
"e": 32742,
"s": 32714,
"text": "Permutation and Combination"
},
{
"code": null,
"e": 32753,
"s": 32742,
"text": "Algorithms"
},
{
"code": null,
"e": 32767,
"s": 32753,
"text": "Combinatorial"
},
{
"code": null,
"e": 32781,
"s": 32767,
"text": "Combinatorial"
},
{
"code": null,
"e": 32792,
"s": 32781,
"text": "Algorithms"
},
{
"code": null,
"e": 32890,
"s": 32792,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32899,
"s": 32890,
"text": "Comments"
},
{
"code": null,
"e": 32912,
"s": 32899,
"text": "Old Comments"
},
{
"code": null,
"e": 32961,
"s": 32912,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 32990,
"s": 32961,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 33017,
"s": 32990,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 33065,
"s": 33017,
"text": "Uniform-Cost Search (Dijkstra for large Graphs)"
},
{
"code": null,
"e": 33090,
"s": 33065,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 33150,
"s": 33090,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 33188,
"s": 33150,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 33265,
"s": 33188,
"text": "itertools.combinations() module in Python to print all possible combinations"
},
{
"code": null,
"e": 33310,
"s": 33265,
"text": "Heap's Algorithm for generating permutations"
}
] |
ASP.NET Core - Configuration
|
In this chapter, we will be discussing the configuration related to ASP.NET Core project. In Solution Explorer, you will see the Startup.cs file. If you have worked with previous versions of ASP.NET Core, you will probably expect to see a global.asax file, which was one place where you could write codes to execute during startup of a web application.
You would also expect to see a web.config file containing all the configuration parameters your application needed to execute.
You would also expect to see a web.config file containing all the configuration parameters your application needed to execute.
In ASP.NET Core those files are all gone, and instead of configuration and startup code are loaded from Startup.cs.
In ASP.NET Core those files are all gone, and instead of configuration and startup code are loaded from Startup.cs.
There is a Startup class inside the file and in this class you can configure your application and even configure your configuration sources.
There is a Startup class inside the file and in this class you can configure your application and even configure your configuration sources.
Here is the default implementation in the Startup.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace FirstAppDemo {
public class Startup {
// This method gets called by the runtime.
// Use this method to add services to the container.
// For more information on how to configure your application,
// visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services) {
}
// This method gets called by the runtime. Use this method to configure
// the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory) {
loggerFactory.AddConsole();
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.Run(async (context) => {
await context.Response.WriteAsync("Hello World!");
});
}
}
}
In the Startup class, there are two methods where most of our work will take place. The Configure method of the class is where you build your HTTP processing pipeline.
This defines how your application responds to requests. Currently this application can only say Hello World! and if we want the application to behave differently, we will need to change the pipeline around by adding additional code in this Configure method.
This defines how your application responds to requests. Currently this application can only say Hello World! and if we want the application to behave differently, we will need to change the pipeline around by adding additional code in this Configure method.
For example, if we want to serve the static files such as an index.html file, we will need to add some code to the Configure method.
For example, if we want to serve the static files such as an index.html file, we will need to add some code to the Configure method.
You can also have an error page or route requests to an ASP.NET MVC controller; both of these scenarios will also require to do some work in this Configure method.
You can also have an error page or route requests to an ASP.NET MVC controller; both of these scenarios will also require to do some work in this Configure method.
In the Startup class, you will also see the ConfigureServices() method. This helps you configure components for your application.
In the Startup class, you will also see the ConfigureServices() method. This helps you configure components for your application.
Right now, we have a hard-coded string for every response — the Hello World! string. Instead of hard-coding the string, we want to load this string from some component that knows the text that we want to display.
This other component might load that text from a database or a web service or a JSON file, it doesn't matter where exactly it is.
This other component might load that text from a database or a web service or a JSON file, it doesn't matter where exactly it is.
We will just set up a scenario so that we do not have this hard-coded string.
We will just set up a scenario so that we do not have this hard-coded string.
In the Solution Explorer, right-click on your project node and select Add → New Item.
In the left pane, select Installed → Code and then in the middle pane, select the JSON File. Call this file AppSettings.json and click on the Add button as in the above screenshot.
We can also have our program read the text from the file instead of having the Hello World! String in Startup.cs. Let us add the following code in AppSettings.json file.
{
"message": "Hello, World! this message is from configuration file..."
}
Now we need to access this message from the Startup.cs file. Here is the implementation of the Startup.cs file which will read the above message from the JSON file.
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
namespace FirstAppDemo {
public class Startup {
public Startup() {
var builder = new ConfigurationBuilder()
.AddJsonFile("AppSettings.json");
Configuration = builder.Build();
}
public IConfiguration Configuration { get; set; }
// This method gets called by the runtime.
// Use this method to add services to the container.
// For more information on how to configure your application,
// visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services) {
}
// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app) {
app.UseIISPlatformHandler();
app.Run(async (context) => {
var msg = Configuration["message"];
await context.Response.WriteAsync(msg);
});
}
// Entry point for the application.
public static void Main(string[] args) =7gt; WebApplication.Run<Startup>(args);
}
}
Let us now run the application. Once you run the application, it will produce the following output.
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2814,
"s": 2461,
"text": "In this chapter, we will be discussing the configuration related to ASP.NET Core project. In Solution Explorer, you will see the Startup.cs file. If you have worked with previous versions of ASP.NET Core, you will probably expect to see a global.asax file, which was one place where you could write codes to execute during startup of a web application."
},
{
"code": null,
"e": 2941,
"s": 2814,
"text": "You would also expect to see a web.config file containing all the configuration parameters your application needed to execute."
},
{
"code": null,
"e": 3068,
"s": 2941,
"text": "You would also expect to see a web.config file containing all the configuration parameters your application needed to execute."
},
{
"code": null,
"e": 3184,
"s": 3068,
"text": "In ASP.NET Core those files are all gone, and instead of configuration and startup code are loaded from Startup.cs."
},
{
"code": null,
"e": 3300,
"s": 3184,
"text": "In ASP.NET Core those files are all gone, and instead of configuration and startup code are loaded from Startup.cs."
},
{
"code": null,
"e": 3441,
"s": 3300,
"text": "There is a Startup class inside the file and in this class you can configure your application and even configure your configuration sources."
},
{
"code": null,
"e": 3582,
"s": 3441,
"text": "There is a Startup class inside the file and in this class you can configure your application and even configure your configuration sources."
},
{
"code": null,
"e": 3641,
"s": 3582,
"text": "Here is the default implementation in the Startup.cs file."
},
{
"code": null,
"e": 4833,
"s": 3641,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \n\nusing Microsoft.AspNetCore.Builder; \nusing Microsoft.AspNetCore.Hosting; \nusing Microsoft.AspNetCore.Http; \n\nusing Microsoft.Extensions.DependencyInjection; \nusing Microsoft.Extensions.Logging; \n\nnamespace FirstAppDemo { \n public class Startup { \n // This method gets called by the runtime.\n // Use this method to add services to the container. \n // For more information on how to configure your application, \n // visit http://go.microsoft.com/fwlink/?LinkID=398940 \n public void ConfigureServices(IServiceCollection services) { \n } \n \n // This method gets called by the runtime. Use this method to configure \n // the HTTP request pipeline.\n public void Configure(IApplicationBuilder app, IHostingEnvironment env, \n ILoggerFactory loggerFactory) { \n loggerFactory.AddConsole(); \n \n if (env.IsDevelopment()) { \n app.UseDeveloperExceptionPage(); \n } \n app.Run(async (context) => { \n await context.Response.WriteAsync(\"Hello World!\"); \n }); \n } \n } \n}"
},
{
"code": null,
"e": 5001,
"s": 4833,
"text": "In the Startup class, there are two methods where most of our work will take place. The Configure method of the class is where you build your HTTP processing pipeline."
},
{
"code": null,
"e": 5259,
"s": 5001,
"text": "This defines how your application responds to requests. Currently this application can only say Hello World! and if we want the application to behave differently, we will need to change the pipeline around by adding additional code in this Configure method."
},
{
"code": null,
"e": 5517,
"s": 5259,
"text": "This defines how your application responds to requests. Currently this application can only say Hello World! and if we want the application to behave differently, we will need to change the pipeline around by adding additional code in this Configure method."
},
{
"code": null,
"e": 5650,
"s": 5517,
"text": "For example, if we want to serve the static files such as an index.html file, we will need to add some code to the Configure method."
},
{
"code": null,
"e": 5783,
"s": 5650,
"text": "For example, if we want to serve the static files such as an index.html file, we will need to add some code to the Configure method."
},
{
"code": null,
"e": 5947,
"s": 5783,
"text": "You can also have an error page or route requests to an ASP.NET MVC controller; both of these scenarios will also require to do some work in this Configure method."
},
{
"code": null,
"e": 6111,
"s": 5947,
"text": "You can also have an error page or route requests to an ASP.NET MVC controller; both of these scenarios will also require to do some work in this Configure method."
},
{
"code": null,
"e": 6241,
"s": 6111,
"text": "In the Startup class, you will also see the ConfigureServices() method. This helps you configure components for your application."
},
{
"code": null,
"e": 6371,
"s": 6241,
"text": "In the Startup class, you will also see the ConfigureServices() method. This helps you configure components for your application."
},
{
"code": null,
"e": 6584,
"s": 6371,
"text": "Right now, we have a hard-coded string for every response — the Hello World! string. Instead of hard-coding the string, we want to load this string from some component that knows the text that we want to display."
},
{
"code": null,
"e": 6714,
"s": 6584,
"text": "This other component might load that text from a database or a web service or a JSON file, it doesn't matter where exactly it is."
},
{
"code": null,
"e": 6844,
"s": 6714,
"text": "This other component might load that text from a database or a web service or a JSON file, it doesn't matter where exactly it is."
},
{
"code": null,
"e": 6922,
"s": 6844,
"text": "We will just set up a scenario so that we do not have this hard-coded string."
},
{
"code": null,
"e": 7000,
"s": 6922,
"text": "We will just set up a scenario so that we do not have this hard-coded string."
},
{
"code": null,
"e": 7086,
"s": 7000,
"text": "In the Solution Explorer, right-click on your project node and select Add → New Item."
},
{
"code": null,
"e": 7267,
"s": 7086,
"text": "In the left pane, select Installed → Code and then in the middle pane, select the JSON File. Call this file AppSettings.json and click on the Add button as in the above screenshot."
},
{
"code": null,
"e": 7437,
"s": 7267,
"text": "We can also have our program read the text from the file instead of having the Hello World! String in Startup.cs. Let us add the following code in AppSettings.json file."
},
{
"code": null,
"e": 7517,
"s": 7437,
"text": "{ \n \"message\": \"Hello, World! this message is from configuration file...\" \n}\n"
},
{
"code": null,
"e": 7682,
"s": 7517,
"text": "Now we need to access this message from the Startup.cs file. Here is the implementation of the Startup.cs file which will read the above message from the JSON file."
},
{
"code": null,
"e": 9021,
"s": 7682,
"text": "using Microsoft.AspNet.Builder; \nusing Microsoft.AspNet.Hosting; \nusing Microsoft.AspNet.Http; \n\nusing Microsoft.Extensions.DependencyInjection; \nusing Microsoft.Extensions.Configuration; \n\nnamespace FirstAppDemo { \n public class Startup { \n public Startup() { \n var builder = new ConfigurationBuilder() \n .AddJsonFile(\"AppSettings.json\"); \n Configuration = builder.Build(); \n } \n public IConfiguration Configuration { get; set; } \n \n // This method gets called by the runtime. \n // Use this method to add services to the container. \n // For more information on how to configure your application, \n // visit http://go.microsoft.com/fwlink/?LinkID=398940 \n public void ConfigureServices(IServiceCollection services) { \n } \n \n // This method gets called by the runtime. \n // Use this method to configure the HTTP request pipeline. \n public void Configure(IApplicationBuilder app) {\n app.UseIISPlatformHandler(); \n app.Run(async (context) => { \n var msg = Configuration[\"message\"]; \n await context.Response.WriteAsync(msg); \n }); \n } \n \n // Entry point for the application. \n public static void Main(string[] args) =7gt; WebApplication.Run<Startup>(args); \n } \n}"
},
{
"code": null,
"e": 9121,
"s": 9021,
"text": "Let us now run the application. Once you run the application, it will produce the following output."
},
{
"code": null,
"e": 9156,
"s": 9121,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 9170,
"s": 9156,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9205,
"s": 9170,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9228,
"s": 9205,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 9262,
"s": 9228,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 9282,
"s": 9262,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 9317,
"s": 9282,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9334,
"s": 9317,
"text": " University Code"
},
{
"code": null,
"e": 9369,
"s": 9334,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9386,
"s": 9369,
"text": " University Code"
},
{
"code": null,
"e": 9420,
"s": 9386,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 9435,
"s": 9420,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 9442,
"s": 9435,
"text": " Print"
},
{
"code": null,
"e": 9453,
"s": 9442,
"text": " Add Notes"
}
] |
Add elements to a Dictionary in Javascript
|
Now we'll create the put method that'll allow us to put key-value pairs on the dictionary. Now using this we'll implement the put method.
Note that JS has objects that act quite like dictionaries. We can just set the container's key property to value.
put(key, value) {
this.container[key] = value;
}
You can test this and the previous functions using −
const myMap = new MyMap()
myMap.put("key1", "value1")
myMap.put("key2", "value2")
myMap.display()
console.log(myMap.hasKey("key1"));
console.log(myMap.hasKey("key3"));
This will give the output −
{key1: "value1", key2: "value2"}
true
false
In ES6, you can put a key-value pair in a map using the set method. For example,
const myMap = new Map([
["key1", "value1"],
["key2", "value2"]
]);
myMap.set("key3", "value3")
console.log(myMap.has("key1"))
console.log(myMap.has("key3"))
This will give the output −
True
True
|
[
{
"code": null,
"e": 1200,
"s": 1062,
"text": "Now we'll create the put method that'll allow us to put key-value pairs on the dictionary. Now using this we'll implement the put method."
},
{
"code": null,
"e": 1315,
"s": 1200,
"text": "Note that JS has objects that act quite like dictionaries. We can just set the container's key property to value. "
},
{
"code": null,
"e": 1367,
"s": 1315,
"text": "put(key, value) {\n this.container[key] = value;\n}"
},
{
"code": null,
"e": 1421,
"s": 1367,
"text": "You can test this and the previous functions using − "
},
{
"code": null,
"e": 1591,
"s": 1421,
"text": "const myMap = new MyMap()\nmyMap.put(\"key1\", \"value1\")\nmyMap.put(\"key2\", \"value2\")\n\nmyMap.display()\n\nconsole.log(myMap.hasKey(\"key1\"));\nconsole.log(myMap.hasKey(\"key3\"));"
},
{
"code": null,
"e": 1619,
"s": 1591,
"text": "This will give the output −"
},
{
"code": null,
"e": 1663,
"s": 1619,
"text": "{key1: \"value1\", key2: \"value2\"}\ntrue\nfalse"
},
{
"code": null,
"e": 1745,
"s": 1663,
"text": "In ES6, you can put a key-value pair in a map using the set method. For example, "
},
{
"code": null,
"e": 1910,
"s": 1745,
"text": "const myMap = new Map([\n [\"key1\", \"value1\"],\n [\"key2\", \"value2\"]\n]);\n\nmyMap.set(\"key3\", \"value3\")\n\nconsole.log(myMap.has(\"key1\"))\nconsole.log(myMap.has(\"key3\"))"
},
{
"code": null,
"e": 1938,
"s": 1910,
"text": "This will give the output −"
},
{
"code": null,
"e": 1948,
"s": 1938,
"text": "True\nTrue"
}
] |
How to stop the execution of a function with JavaScript?
|
To stop the execution of a function in JavaScript, use the clearTimeout() method. This function call clears any timer set by the setTimeout() functions.
You can try to run the following code to learn how to work with clearTimeout() method in JavaScript.
<html>
<head>
<title>JavaScript clearTimeout() method</title>
<script>
<!--
var imgObj = null;
var animate ;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight(){
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
}
function stop(){
clearTimeout(animate);
imgObj.style.left = '0px';
}
window.onload = init;
//-->
</script>
</head>
<body>
<form>
<img id = "myImage" src = "/images/html.gif" />
<p>Click the buttons below to handle animation</p>
<input type = "button" value = "Start" onclick = "moveRight();" />
<input type = "button" value = "Stop" onclick = "stop();" />
</form>
</body>
</html>
|
[
{
"code": null,
"e": 1215,
"s": 1062,
"text": "To stop the execution of a function in JavaScript, use the clearTimeout() method. This function call clears any timer set by the setTimeout() functions."
},
{
"code": null,
"e": 1316,
"s": 1215,
"text": "You can try to run the following code to learn how to work with clearTimeout() method in JavaScript."
},
{
"code": null,
"e": 2404,
"s": 1316,
"text": "<html>\n <head>\n <title>JavaScript clearTimeout() method</title>\n <script>\n <!--\n var imgObj = null;\n var animate ;\n \n function init(){\n imgObj = document.getElementById('myImage');\n imgObj.style.position= 'relative';\n imgObj.style.left = '0px';\n }\n function moveRight(){\n imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';\n animate = setTimeout(moveRight,20); // call moveRight in 20msec\n }\n function stop(){\n clearTimeout(animate);\n imgObj.style.left = '0px';\n }\n window.onload = init;\n //-->\n </script>\n </head>\n <body>\n <form>\n <img id = \"myImage\" src = \"/images/html.gif\" />\n <p>Click the buttons below to handle animation</p>\n <input type = \"button\" value = \"Start\" onclick = \"moveRight();\" />\n <input type = \"button\" value = \"Stop\" onclick = \"stop();\" />\n </form>\n </body>\n</html>"
}
] |
How To Scrape the Dark Web. Scraping the Dark Web using Python... | by Mitchell Telatnik | Towards Data Science
|
To most users, Google is the gateway to exploring the internet. However, the deep web contains pages that cannot be indexed by Google. Within this space, lies the dark web — anonymized websites, often called hidden services, dealing in criminal activity from drugs to hacking to human trafficking.
Website URLs on the dark web do not follow conventions and are often a random string of letters and numbers followed by the .onion subdomain. These websites require the TOR browser to resolve, and cannot be accessed through traditional browsers such as Chrome or Safari.
The first hurdle in scraping the dark web is finding hidden services to scrape. If you already know the locations of websites you wish to scrape, you are in luck! The URL’s to these websites are often not searchable and are passed from person to person, either in-person or online. Luckily, there are a couple of methods we can use to find these hidden services.
Directories containing links to hidden services exist on both the dark web and the surface web. These directories can give you a good direction, but will often contain more well-known services, and services that are more easily found.
Snowball sampling is a crawling method that takes a seed website (such as one you found from a directory) and then crawls the website looking for links to other websites. After collecting these links, the crawler will then continue the process for those sites expanding its search exponentially. This method has the ability to find hidden services not listed in directories. In addition, these sites are more likely to draw serious criminals since they are not as transparent in their existence.
While the snowball sampling method is recommended for finding hidden services, its implementation is beyond the scope of this article. I have written a second article on snowball sampling the dark web here.
After the hidden services to be scraped have been identified, the environment needs to be setup. This article covers the use of Python, Selenium, TOR browser, and Mac OSX.
The TOR browser is a browser that uses the TOR network and will allow us to resolve websites using a .onion subdomain. The TOR browser can be downloaded here.
Running a VPN while crawling the dark web can provide you additional security. A virtual private network (VPN) is not required, but highly recommended.
For this article, I assume you already have python installed on your machine with an IDE of your choice. If not, many tutorials can be found online.
Pandas is a data manipulation Python package. Pandas will be used to store and export the data scraped to a csv file. Pandas can be installed using pip by typing the following command into your terminal:
pip install pandas
Selenium is a browser automation Python package. Selenium will be used to crawl the websites and extract data. Selenium can be installed using pip by typing the following command into your terminal:
pip install selenium
For selenium to automate a browser, it requires a driver. Because the TOR browser is running off of Firefox, we will be using Mozilla’s Geckodriver. You can download the driver here. After downloading, extract the driver and move it to your ~/.local/bin folder.
The location of the TOR browser’s Firefox binary will also be needed. To find this, right-click on the TOR browser in your applications folder and click on show contents. Then navigate to the Firefox binary and copy the full path. Save this path somewhere for later use.
Now that you have set up your environment you are ready to start writing your scraper.
First, import the web driver and FirefoxBinary from selenium. Also import pandas as pd.
from selenium import webdriverfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinaryimport pandas as pd
Create a variable “binary” and set it to the path of the Firefox binary you saved earlier.
binary = FirefoxBinary(*path to your firefox binary*)
Set the web driver up to use Firefox and pass the binary variable.
driver = webdriver.Firefox(firefox_binary = binary)
Create a variable “url” and set it to the url of the hidden service you wish to scrape.
url = *your url*
Open the TOR browser and get the url.
driver.get(url)
You can now scrape the hidden service like you would any website!
Whether you are beginner to Selenium or need brushing up, you can use these basic techniques to effectively scrape the website. Additional Selenium scraping tutorials can be found on the internet.
A key part of scraping with Selenium is locating HTML elements to collect the data. There are several ways you can do this in Selenium. One method is by using the class name. In order to find the class name of an element, you can right-click it and click inspect. Below is an example of finding an element by class name.
driver.find_element_by_class_name("postMain")
You can also find elements by their XPath. An XPath represents the location of the element in the HTML structure. You can find the XPath of an element in the right-click menu of the HTML item in the inspect interface. Below is an example of finding an element by XPath.
driver.find_element_by_xpath('/html/body/div/div[2]/div[2]/div/div[1]/div/a[1]')
If you want to find multiple elements, you can use “find_elements” instead of “find_element”. Below is an example.
driver.find_elements_by_class_name("postMain")
You can retrieve the text of an element by using the text function. Below is an example.
driver.find_element_by_class_name('postContent').text
You can store elements by saving the element in a variable and then appending the variable to a list. Below is an example.
post_content_list = []postText = driver.find_element_by_class_name('postContent').textpost_content_list.append(postText)
Some page-based websites include the page number in the URL. You can loop over a range and alter the url to crawl multiple pages. An example is below.
for i in range(1, MAX_PAGE_NUM + 1): page_num = i url = '*first part of url*' + str(page_num) + '*last part of url*' driver.get(url)
After crawling a page and saving data into lists, you can export those lists as tabular data using Pandas. An example is below.
df['postURL'] = post_url_listdf['author'] = post_author_listdf['postTitle'] = post_title_listdf.to_csv('scrape.csv')
Many hidden services employ anti-crawling measures to keep information secret and to avoid DDoS attacks. The most common measures you will encounter are captchas. While some captcha auto-solvers exist, oftentimes hidden services will use unique captcha types that the solvers cannot pass. Below is an example of a captcha found on a forum.
If the captcha is required at specific points (like first connecting to the server) you can use the implicit wait function in Selenium. This function will wait for a pre-determined time until the next action can be performed. Below is an example of this in use where Selenium will wait until it can find the element with the class name “postMain”.
driver.implicitly_wait(10000)driver.find_element_by_class_name("postMain")
Other times, if the server identifies you are a robot, it will stop serving you. In order to bypass this, scrape the website in chunks instead of all at once. You can save the data in different csv files and them combine them with an additional python script using Pandas concat function. Below is an example.
import pandas as pddf = pd.read_csv('scrape.csv')df2 = pd.read_csv('scrape2.csv')df3 = pd.read_csv('scrape3.csv')df4 = pd.read_csv('scrape4.csv')df5 = pd.read_csv('scrape5.csv')df6 = pd.read_csv('scrape6.csv')frames = [df, df2, df3, df4, df5, df6]result = pd.concat(frames, ignore_index = True)result.to_csv('ForumScrape.csv')
Scraping the dark web has unique challenges compared to scraping the surface web. However, it is relatively untapped and can provide excellent cybercrime intelligence operations. While hidden services often employ anti-crawling measures, these can still be bypassed, and provide interesting and useful data.
I want to reiterate that scraping the dark web can be dangerous. Make sure you take the necessary safety precautions. Please continue to research safe browsing on the dark web. I am not responsible for any harm that occurs.
|
[
{
"code": null,
"e": 469,
"s": 171,
"text": "To most users, Google is the gateway to exploring the internet. However, the deep web contains pages that cannot be indexed by Google. Within this space, lies the dark web — anonymized websites, often called hidden services, dealing in criminal activity from drugs to hacking to human trafficking."
},
{
"code": null,
"e": 740,
"s": 469,
"text": "Website URLs on the dark web do not follow conventions and are often a random string of letters and numbers followed by the .onion subdomain. These websites require the TOR browser to resolve, and cannot be accessed through traditional browsers such as Chrome or Safari."
},
{
"code": null,
"e": 1103,
"s": 740,
"text": "The first hurdle in scraping the dark web is finding hidden services to scrape. If you already know the locations of websites you wish to scrape, you are in luck! The URL’s to these websites are often not searchable and are passed from person to person, either in-person or online. Luckily, there are a couple of methods we can use to find these hidden services."
},
{
"code": null,
"e": 1338,
"s": 1103,
"text": "Directories containing links to hidden services exist on both the dark web and the surface web. These directories can give you a good direction, but will often contain more well-known services, and services that are more easily found."
},
{
"code": null,
"e": 1834,
"s": 1338,
"text": "Snowball sampling is a crawling method that takes a seed website (such as one you found from a directory) and then crawls the website looking for links to other websites. After collecting these links, the crawler will then continue the process for those sites expanding its search exponentially. This method has the ability to find hidden services not listed in directories. In addition, these sites are more likely to draw serious criminals since they are not as transparent in their existence."
},
{
"code": null,
"e": 2041,
"s": 1834,
"text": "While the snowball sampling method is recommended for finding hidden services, its implementation is beyond the scope of this article. I have written a second article on snowball sampling the dark web here."
},
{
"code": null,
"e": 2213,
"s": 2041,
"text": "After the hidden services to be scraped have been identified, the environment needs to be setup. This article covers the use of Python, Selenium, TOR browser, and Mac OSX."
},
{
"code": null,
"e": 2372,
"s": 2213,
"text": "The TOR browser is a browser that uses the TOR network and will allow us to resolve websites using a .onion subdomain. The TOR browser can be downloaded here."
},
{
"code": null,
"e": 2524,
"s": 2372,
"text": "Running a VPN while crawling the dark web can provide you additional security. A virtual private network (VPN) is not required, but highly recommended."
},
{
"code": null,
"e": 2673,
"s": 2524,
"text": "For this article, I assume you already have python installed on your machine with an IDE of your choice. If not, many tutorials can be found online."
},
{
"code": null,
"e": 2877,
"s": 2673,
"text": "Pandas is a data manipulation Python package. Pandas will be used to store and export the data scraped to a csv file. Pandas can be installed using pip by typing the following command into your terminal:"
},
{
"code": null,
"e": 2896,
"s": 2877,
"text": "pip install pandas"
},
{
"code": null,
"e": 3095,
"s": 2896,
"text": "Selenium is a browser automation Python package. Selenium will be used to crawl the websites and extract data. Selenium can be installed using pip by typing the following command into your terminal:"
},
{
"code": null,
"e": 3116,
"s": 3095,
"text": "pip install selenium"
},
{
"code": null,
"e": 3378,
"s": 3116,
"text": "For selenium to automate a browser, it requires a driver. Because the TOR browser is running off of Firefox, we will be using Mozilla’s Geckodriver. You can download the driver here. After downloading, extract the driver and move it to your ~/.local/bin folder."
},
{
"code": null,
"e": 3649,
"s": 3378,
"text": "The location of the TOR browser’s Firefox binary will also be needed. To find this, right-click on the TOR browser in your applications folder and click on show contents. Then navigate to the Firefox binary and copy the full path. Save this path somewhere for later use."
},
{
"code": null,
"e": 3736,
"s": 3649,
"text": "Now that you have set up your environment you are ready to start writing your scraper."
},
{
"code": null,
"e": 3824,
"s": 3736,
"text": "First, import the web driver and FirefoxBinary from selenium. Also import pandas as pd."
},
{
"code": null,
"e": 3941,
"s": 3824,
"text": "from selenium import webdriverfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinaryimport pandas as pd"
},
{
"code": null,
"e": 4032,
"s": 3941,
"text": "Create a variable “binary” and set it to the path of the Firefox binary you saved earlier."
},
{
"code": null,
"e": 4086,
"s": 4032,
"text": "binary = FirefoxBinary(*path to your firefox binary*)"
},
{
"code": null,
"e": 4153,
"s": 4086,
"text": "Set the web driver up to use Firefox and pass the binary variable."
},
{
"code": null,
"e": 4205,
"s": 4153,
"text": "driver = webdriver.Firefox(firefox_binary = binary)"
},
{
"code": null,
"e": 4293,
"s": 4205,
"text": "Create a variable “url” and set it to the url of the hidden service you wish to scrape."
},
{
"code": null,
"e": 4310,
"s": 4293,
"text": "url = *your url*"
},
{
"code": null,
"e": 4348,
"s": 4310,
"text": "Open the TOR browser and get the url."
},
{
"code": null,
"e": 4364,
"s": 4348,
"text": "driver.get(url)"
},
{
"code": null,
"e": 4430,
"s": 4364,
"text": "You can now scrape the hidden service like you would any website!"
},
{
"code": null,
"e": 4627,
"s": 4430,
"text": "Whether you are beginner to Selenium or need brushing up, you can use these basic techniques to effectively scrape the website. Additional Selenium scraping tutorials can be found on the internet."
},
{
"code": null,
"e": 4948,
"s": 4627,
"text": "A key part of scraping with Selenium is locating HTML elements to collect the data. There are several ways you can do this in Selenium. One method is by using the class name. In order to find the class name of an element, you can right-click it and click inspect. Below is an example of finding an element by class name."
},
{
"code": null,
"e": 4994,
"s": 4948,
"text": "driver.find_element_by_class_name(\"postMain\")"
},
{
"code": null,
"e": 5264,
"s": 4994,
"text": "You can also find elements by their XPath. An XPath represents the location of the element in the HTML structure. You can find the XPath of an element in the right-click menu of the HTML item in the inspect interface. Below is an example of finding an element by XPath."
},
{
"code": null,
"e": 5345,
"s": 5264,
"text": "driver.find_element_by_xpath('/html/body/div/div[2]/div[2]/div/div[1]/div/a[1]')"
},
{
"code": null,
"e": 5460,
"s": 5345,
"text": "If you want to find multiple elements, you can use “find_elements” instead of “find_element”. Below is an example."
},
{
"code": null,
"e": 5507,
"s": 5460,
"text": "driver.find_elements_by_class_name(\"postMain\")"
},
{
"code": null,
"e": 5596,
"s": 5507,
"text": "You can retrieve the text of an element by using the text function. Below is an example."
},
{
"code": null,
"e": 5650,
"s": 5596,
"text": "driver.find_element_by_class_name('postContent').text"
},
{
"code": null,
"e": 5773,
"s": 5650,
"text": "You can store elements by saving the element in a variable and then appending the variable to a list. Below is an example."
},
{
"code": null,
"e": 5894,
"s": 5773,
"text": "post_content_list = []postText = driver.find_element_by_class_name('postContent').textpost_content_list.append(postText)"
},
{
"code": null,
"e": 6045,
"s": 5894,
"text": "Some page-based websites include the page number in the URL. You can loop over a range and alter the url to crawl multiple pages. An example is below."
},
{
"code": null,
"e": 6181,
"s": 6045,
"text": "for i in range(1, MAX_PAGE_NUM + 1): page_num = i url = '*first part of url*' + str(page_num) + '*last part of url*' driver.get(url)"
},
{
"code": null,
"e": 6309,
"s": 6181,
"text": "After crawling a page and saving data into lists, you can export those lists as tabular data using Pandas. An example is below."
},
{
"code": null,
"e": 6426,
"s": 6309,
"text": "df['postURL'] = post_url_listdf['author'] = post_author_listdf['postTitle'] = post_title_listdf.to_csv('scrape.csv')"
},
{
"code": null,
"e": 6766,
"s": 6426,
"text": "Many hidden services employ anti-crawling measures to keep information secret and to avoid DDoS attacks. The most common measures you will encounter are captchas. While some captcha auto-solvers exist, oftentimes hidden services will use unique captcha types that the solvers cannot pass. Below is an example of a captcha found on a forum."
},
{
"code": null,
"e": 7114,
"s": 6766,
"text": "If the captcha is required at specific points (like first connecting to the server) you can use the implicit wait function in Selenium. This function will wait for a pre-determined time until the next action can be performed. Below is an example of this in use where Selenium will wait until it can find the element with the class name “postMain”."
},
{
"code": null,
"e": 7189,
"s": 7114,
"text": "driver.implicitly_wait(10000)driver.find_element_by_class_name(\"postMain\")"
},
{
"code": null,
"e": 7499,
"s": 7189,
"text": "Other times, if the server identifies you are a robot, it will stop serving you. In order to bypass this, scrape the website in chunks instead of all at once. You can save the data in different csv files and them combine them with an additional python script using Pandas concat function. Below is an example."
},
{
"code": null,
"e": 7826,
"s": 7499,
"text": "import pandas as pddf = pd.read_csv('scrape.csv')df2 = pd.read_csv('scrape2.csv')df3 = pd.read_csv('scrape3.csv')df4 = pd.read_csv('scrape4.csv')df5 = pd.read_csv('scrape5.csv')df6 = pd.read_csv('scrape6.csv')frames = [df, df2, df3, df4, df5, df6]result = pd.concat(frames, ignore_index = True)result.to_csv('ForumScrape.csv')"
},
{
"code": null,
"e": 8134,
"s": 7826,
"text": "Scraping the dark web has unique challenges compared to scraping the surface web. However, it is relatively untapped and can provide excellent cybercrime intelligence operations. While hidden services often employ anti-crawling measures, these can still be bypassed, and provide interesting and useful data."
}
] |
Distinct strings with odd and even changes allowed - GeeksforGeeks
|
07 Mar, 2022
Given an array of lower case strings, the task is to find the number of strings that are distinct. Two strings are distinct if, on applying the following operations on one string, the second string cannot be formed.
A character on the odd index can be swapped with another character on the odd index only.
A character on even index can be swapped with another character on even index only.
Examples:
Input : arr[] = {"abcd", "cbad", "bacd"}
Output : 2
The 2nd string can be converted to the 1st by swapping
the first and third characters. So there are 2 distinct
strings as the third string cannot be converted to the
first.
Input : arr[] = {"abc", "cba"}
Output : 1
A simple solution is to run two loops. The outer loop picks a string and the inner loop checks if there is a previously string which can be converted to a current string by doing allowed transformations. This solution requires O(n2m) time where n is the number of strings and m is the maximum number of characters in any string.
An efficient solution generates an encoded string for every input string. The encoded has counts of even and odd positioned characters separated by a separator. Two strings are considered same if their encoded strings are the same, then else not. Once we have a way to encode strings, the problem is reduced to counting distinct encoded strings. This is a typical problem of hashing. We create a hash set and, one by one, store encodings of strings. If an encoding already exists, we ignore the string. Otherwise, we store encoding in hash and increment count of distinct strings.
C++
Java
Python3
C#
Javascript
#include<bits/stdc++.h>using namespace std; int MAX_CHAR = 26; string encodeString(char str[], int m) { // hashEven stores the count of even indexed character // for each string hashOdd stores the count of odd // indexed characters for each string int hashEven[MAX_CHAR]; int hashOdd[MAX_CHAR]; // creating hash for each string for (int i = 0; i < m; i++) { char c = str[i]; if ((i & 1) != 0) // If index of current character is odd hashOdd[c-'a']++; else hashEven[c-'a']++; } // For every character from 'a' to 'z', we store its // count at even position followed by a separator, // followed by count at odd position. string encoding = ""; for (int i = 0; i < MAX_CHAR; i++) { encoding += (hashEven[i]); encoding += ('-'); encoding += (hashOdd[i]); encoding += ('-'); } return encoding; } // This function basically uses a hashing based set to// store strings which are distinct according// to criteria given in question. int countDistinct(string input[], int n) { int countDist = 0; // Initialize result // Create an empty set and store all distinct // strings in it. set<string> s; for (int i = 0; i < n; i++) { // If this encoding appears first time, increment // count of distinct encodings. char char_array[input[i].length()+1]; strcpy(char_array, input[i].c_str()); if (s.find(encodeString(char_array, input[i].length()+1)) == s.end()) { s.insert(encodeString(char_array,input[i].length()+1)); countDist++; } } return countDist; } // Driver code int main() { string input[] = {"abcd", "acbd", "adcb", "cdba", "bcda", "badc"}; int n = sizeof(input)/sizeof(input[0]); cout << countDistinct(input, n) << "\n"; } // This code is contributed by NishaBharti.
// Java program to count distinct strings with// even odd swapping allowed.import java.util.HashSet;import java.util.Set;class GFG {static int MAX_CHAR = 26; static String encodeString(char[] str) { // hashEven stores the count of even indexed character // for each string hashOdd stores the count of odd // indexed characters for each string int hashEven[] = new int[MAX_CHAR]; int hashOdd[] = new int[MAX_CHAR]; // creating hash for each string for (int i = 0; i < str.length; i++) { char c = str[i]; if ((i & 1) != 0) // If index of current character is odd hashOdd[c-'a']++; else hashEven[c-'a']++; } // For every character from 'a' to 'z', we store its // count at even position followed by a separator, // followed by count at odd position. String encoding = ""; for (int i = 0; i < MAX_CHAR; i++) { encoding += (hashEven[i]); encoding += ('-'); encoding += (hashOdd[i]); encoding += ('-'); } return encoding; } // This function basically uses a hashing based set to// store strings which are distinct according// to criteria given in question. static int countDistinct(String input[], int n) { int countDist = 0; // Initialize result // Create an empty set and store all distinct // strings in it. Set<String> s = new HashSet<>(); for (int i = 0; i < n; i++) { // If this encoding appears first time, increment // count of distinct encodings. if (!s.contains(encodeString(input[i].toCharArray()))) { s.add(encodeString(input[i].toCharArray())); countDist++; } } return countDist; } public static void main(String[] args) { String input[] = {"abcd", "acbd", "adcb", "cdba", "bcda", "badc"}; int n = input.length; System.out.println(countDistinct(input, n)); }}
# Python3 program to count distinct strings with# even odd swapping allowed.MAX_CHAR = 26 # Returns encoding of string that can be used# for hashing. The idea is to return same encoding# for strings which can become same after swapping# a even positioned character with other even characters# OR swapping an odd character with other odd characters.def encodeString(string): # hashEven stores the count of even indexed character # for each string hashOdd stores the count of odd # indexed characters for each string hashEven = [0] * MAX_CHAR hashOdd = [0] * MAX_CHAR # creating hash for each string for i in range(len(string)): c = string[i] if i & 1: # If index of current character is odd hashOdd[ord(c) - ord('a')] += 1 else: hashEven[ord(c) - ord('a')] += 1 # For every character from 'a' to 'z', we store its # count at even position followed by a separator, # followed by count at odd position. encoding = "" for i in range(MAX_CHAR): encoding += str(hashEven[i]) encoding += str('-') encoding += str(hashOdd[i]) encoding += str('-') return encoding # This function basically uses a hashing based set to# store strings which are distinct according# to criteria given in question.def countDistinct(input, n): countDist = 0 # Initialize result # Create an empty set and store all distinct # strings in it. s = set() for i in range(n): # If this encoding appears first time, increment # count of distinct encodings. if encodeString(input[i]) not in s: s.add(encodeString(input[i])) countDist += 1 return countDist # Driver Codeif __name__ == "__main__": input = ["abcd", "acbd", "adcb", "cdba", "bcda", "badc"] n = len(input) print(countDistinct(input, n)) # This code is contributed by# sanjeev2552
// C# program to count distinct strings with// even odd swapping allowed.using System;using System.Collections.Generic; class GFG{ static int MAX_CHAR = 26; static String encodeString(char[] str) { // hashEven stores the count of even // indexed character for each string // hashOdd stores the count of odd // indexed characters for each string int []hashEven = new int[MAX_CHAR]; int []hashOdd = new int[MAX_CHAR]; // creating hash for each string for (int i = 0; i < str.Length; i++) { char m = str[i]; // If index of current character is odd if ((i & 1) != 0) hashOdd[m - 'a']++; else hashEven[m - 'a']++; } // For every character from 'a' to 'z', // we store its count at even position // followed by a separator, // followed by count at odd position. String encoding = ""; for (int i = 0; i < MAX_CHAR; i++) { encoding += (hashEven[i]); encoding += ('-'); encoding += (hashOdd[i]); encoding += ('-'); } return encoding; } // This function basically uses a hashing based set // to store strings which are distinct according // to criteria given in question. static int countDistinct(String []input, int n) { int countDist = 0; // Initialize result // Create an empty set and store all distinct // strings in it. HashSet<String> s = new HashSet<String>(); for (int i = 0; i < n; i++) { // If this encoding appears first time, // increment count of distinct encodings. if (!s.Contains(encodeString(input[i].ToCharArray()))) { s.Add(encodeString(input[i].ToCharArray())); countDist++; } } return countDist; } // Driver Code public static void Main(String[] args) { String []input = {"abcd", "acbd", "adcb", "cdba", "bcda", "badc"}; int n = input.Length; Console.WriteLine(countDistinct(input, n)); }} // This code is contributed by 29AjayKumar
<script> // Javascript program to count distinct strings with // even odd swapping allowed let MAX_CHAR = 26; function encodeString(str) { // hashEven stores the count of even indexed character // for each string hashOdd stores the count of odd // indexed characters for each string let hashEven = Array(MAX_CHAR).fill(0); let hashOdd = Array(MAX_CHAR).fill(0); // creating hash for each string for (let i = 0; i < str.length; i++) { let c = str[i]; if ((i & 1) != 0) // If index of current character is odd hashOdd[c.charCodeAt() - 'a'.charCodeAt()]++; else hashEven[c.charCodeAt() - 'a'.charCodeAt()]++; } // For every character from 'a' to 'z', we store its // count at even position followed by a separator, // followed by count at odd position. let encoding = ""; for (let i = 0; i < MAX_CHAR; i++) { encoding += (hashEven[i]); encoding += ('-'); encoding += (hashOdd[i]); encoding += ('-'); } return encoding; } // This function basically uses a hashing based set to // store strings which are distinct according // to criteria given in question. function countDistinct(input, n) { let countDist = 0; // Initialize result // Create an empty set and store all distinct // strings in it. let s = new Set(); for (let i = 0; i < n; i++) { // If this encoding appears first time, increment // count of distinct encodings. if (!s.has(encodeString(input[i].split('')))) { s.add(encodeString(input[i].split(''))); countDist++; } } return countDist; } // Driver program let input = ["abcd", "acbd", "adcb", "cdba", "bcda", "badc"]; let n = input.length; document.write(countDistinct(input, n)); </script>
4
This article is contributed by kp93. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
krutikkhandhadiya
29AjayKumar
Akanksha_Rai
sanjeev2552
avijitmondal1998
NishaBharti
jayliya
simmytarika5
Hash
Strings
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hashing | Set 2 (Separate Chaining)
Most frequent element in an array
Sort string of characters
Counting frequencies of array elements
Double Hashing
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
|
[
{
"code": null,
"e": 25162,
"s": 25134,
"text": "\n07 Mar, 2022"
},
{
"code": null,
"e": 25380,
"s": 25162,
"text": "Given an array of lower case strings, the task is to find the number of strings that are distinct. Two strings are distinct if, on applying the following operations on one string, the second string cannot be formed. "
},
{
"code": null,
"e": 25470,
"s": 25380,
"text": "A character on the odd index can be swapped with another character on the odd index only."
},
{
"code": null,
"e": 25554,
"s": 25470,
"text": "A character on even index can be swapped with another character on even index only."
},
{
"code": null,
"e": 25566,
"s": 25554,
"text": "Examples: "
},
{
"code": null,
"e": 25732,
"s": 25566,
"text": "Input : arr[] = {\"abcd\", \"cbad\", \"bacd\"}\nOutput : 2\nThe 2nd string can be converted to the 1st by swapping \nthe first and third characters. So there are 2 distinct "
},
{
"code": null,
"e": 25840,
"s": 25732,
"text": "strings as the third string cannot be converted to the \nfirst.\n\nInput : arr[] = {\"abc\", \"cba\"}\nOutput : 1 "
},
{
"code": null,
"e": 26169,
"s": 25840,
"text": "A simple solution is to run two loops. The outer loop picks a string and the inner loop checks if there is a previously string which can be converted to a current string by doing allowed transformations. This solution requires O(n2m) time where n is the number of strings and m is the maximum number of characters in any string."
},
{
"code": null,
"e": 26751,
"s": 26169,
"text": "An efficient solution generates an encoded string for every input string. The encoded has counts of even and odd positioned characters separated by a separator. Two strings are considered same if their encoded strings are the same, then else not. Once we have a way to encode strings, the problem is reduced to counting distinct encoded strings. This is a typical problem of hashing. We create a hash set and, one by one, store encodings of strings. If an encoding already exists, we ignore the string. Otherwise, we store encoding in hash and increment count of distinct strings. "
},
{
"code": null,
"e": 26755,
"s": 26751,
"text": "C++"
},
{
"code": null,
"e": 26760,
"s": 26755,
"text": "Java"
},
{
"code": null,
"e": 26768,
"s": 26760,
"text": "Python3"
},
{
"code": null,
"e": 26771,
"s": 26768,
"text": "C#"
},
{
"code": null,
"e": 26782,
"s": 26771,
"text": "Javascript"
},
{
"code": "#include<bits/stdc++.h>using namespace std; int MAX_CHAR = 26; string encodeString(char str[], int m) { // hashEven stores the count of even indexed character // for each string hashOdd stores the count of odd // indexed characters for each string int hashEven[MAX_CHAR]; int hashOdd[MAX_CHAR]; // creating hash for each string for (int i = 0; i < m; i++) { char c = str[i]; if ((i & 1) != 0) // If index of current character is odd hashOdd[c-'a']++; else hashEven[c-'a']++; } // For every character from 'a' to 'z', we store its // count at even position followed by a separator, // followed by count at odd position. string encoding = \"\"; for (int i = 0; i < MAX_CHAR; i++) { encoding += (hashEven[i]); encoding += ('-'); encoding += (hashOdd[i]); encoding += ('-'); } return encoding; } // This function basically uses a hashing based set to// store strings which are distinct according// to criteria given in question. int countDistinct(string input[], int n) { int countDist = 0; // Initialize result // Create an empty set and store all distinct // strings in it. set<string> s; for (int i = 0; i < n; i++) { // If this encoding appears first time, increment // count of distinct encodings. char char_array[input[i].length()+1]; strcpy(char_array, input[i].c_str()); if (s.find(encodeString(char_array, input[i].length()+1)) == s.end()) { s.insert(encodeString(char_array,input[i].length()+1)); countDist++; } } return countDist; } // Driver code int main() { string input[] = {\"abcd\", \"acbd\", \"adcb\", \"cdba\", \"bcda\", \"badc\"}; int n = sizeof(input)/sizeof(input[0]); cout << countDistinct(input, n) << \"\\n\"; } // This code is contributed by NishaBharti.",
"e": 28869,
"s": 26782,
"text": null
},
{
"code": "// Java program to count distinct strings with// even odd swapping allowed.import java.util.HashSet;import java.util.Set;class GFG {static int MAX_CHAR = 26; static String encodeString(char[] str) { // hashEven stores the count of even indexed character // for each string hashOdd stores the count of odd // indexed characters for each string int hashEven[] = new int[MAX_CHAR]; int hashOdd[] = new int[MAX_CHAR]; // creating hash for each string for (int i = 0; i < str.length; i++) { char c = str[i]; if ((i & 1) != 0) // If index of current character is odd hashOdd[c-'a']++; else hashEven[c-'a']++; } // For every character from 'a' to 'z', we store its // count at even position followed by a separator, // followed by count at odd position. String encoding = \"\"; for (int i = 0; i < MAX_CHAR; i++) { encoding += (hashEven[i]); encoding += ('-'); encoding += (hashOdd[i]); encoding += ('-'); } return encoding; } // This function basically uses a hashing based set to// store strings which are distinct according// to criteria given in question. static int countDistinct(String input[], int n) { int countDist = 0; // Initialize result // Create an empty set and store all distinct // strings in it. Set<String> s = new HashSet<>(); for (int i = 0; i < n; i++) { // If this encoding appears first time, increment // count of distinct encodings. if (!s.contains(encodeString(input[i].toCharArray()))) { s.add(encodeString(input[i].toCharArray())); countDist++; } } return countDist; } public static void main(String[] args) { String input[] = {\"abcd\", \"acbd\", \"adcb\", \"cdba\", \"bcda\", \"badc\"}; int n = input.length; System.out.println(countDistinct(input, n)); }}",
"e": 30938,
"s": 28869,
"text": null
},
{
"code": "# Python3 program to count distinct strings with# even odd swapping allowed.MAX_CHAR = 26 # Returns encoding of string that can be used# for hashing. The idea is to return same encoding# for strings which can become same after swapping# a even positioned character with other even characters# OR swapping an odd character with other odd characters.def encodeString(string): # hashEven stores the count of even indexed character # for each string hashOdd stores the count of odd # indexed characters for each string hashEven = [0] * MAX_CHAR hashOdd = [0] * MAX_CHAR # creating hash for each string for i in range(len(string)): c = string[i] if i & 1: # If index of current character is odd hashOdd[ord(c) - ord('a')] += 1 else: hashEven[ord(c) - ord('a')] += 1 # For every character from 'a' to 'z', we store its # count at even position followed by a separator, # followed by count at odd position. encoding = \"\" for i in range(MAX_CHAR): encoding += str(hashEven[i]) encoding += str('-') encoding += str(hashOdd[i]) encoding += str('-') return encoding # This function basically uses a hashing based set to# store strings which are distinct according# to criteria given in question.def countDistinct(input, n): countDist = 0 # Initialize result # Create an empty set and store all distinct # strings in it. s = set() for i in range(n): # If this encoding appears first time, increment # count of distinct encodings. if encodeString(input[i]) not in s: s.add(encodeString(input[i])) countDist += 1 return countDist # Driver Codeif __name__ == \"__main__\": input = [\"abcd\", \"acbd\", \"adcb\", \"cdba\", \"bcda\", \"badc\"] n = len(input) print(countDistinct(input, n)) # This code is contributed by# sanjeev2552",
"e": 32839,
"s": 30938,
"text": null
},
{
"code": "// C# program to count distinct strings with// even odd swapping allowed.using System;using System.Collections.Generic; class GFG{ static int MAX_CHAR = 26; static String encodeString(char[] str) { // hashEven stores the count of even // indexed character for each string // hashOdd stores the count of odd // indexed characters for each string int []hashEven = new int[MAX_CHAR]; int []hashOdd = new int[MAX_CHAR]; // creating hash for each string for (int i = 0; i < str.Length; i++) { char m = str[i]; // If index of current character is odd if ((i & 1) != 0) hashOdd[m - 'a']++; else hashEven[m - 'a']++; } // For every character from 'a' to 'z', // we store its count at even position // followed by a separator, // followed by count at odd position. String encoding = \"\"; for (int i = 0; i < MAX_CHAR; i++) { encoding += (hashEven[i]); encoding += ('-'); encoding += (hashOdd[i]); encoding += ('-'); } return encoding; } // This function basically uses a hashing based set // to store strings which are distinct according // to criteria given in question. static int countDistinct(String []input, int n) { int countDist = 0; // Initialize result // Create an empty set and store all distinct // strings in it. HashSet<String> s = new HashSet<String>(); for (int i = 0; i < n; i++) { // If this encoding appears first time, // increment count of distinct encodings. if (!s.Contains(encodeString(input[i].ToCharArray()))) { s.Add(encodeString(input[i].ToCharArray())); countDist++; } } return countDist; } // Driver Code public static void Main(String[] args) { String []input = {\"abcd\", \"acbd\", \"adcb\", \"cdba\", \"bcda\", \"badc\"}; int n = input.Length; Console.WriteLine(countDistinct(input, n)); }} // This code is contributed by 29AjayKumar",
"e": 35089,
"s": 32839,
"text": null
},
{
"code": "<script> // Javascript program to count distinct strings with // even odd swapping allowed let MAX_CHAR = 26; function encodeString(str) { // hashEven stores the count of even indexed character // for each string hashOdd stores the count of odd // indexed characters for each string let hashEven = Array(MAX_CHAR).fill(0); let hashOdd = Array(MAX_CHAR).fill(0); // creating hash for each string for (let i = 0; i < str.length; i++) { let c = str[i]; if ((i & 1) != 0) // If index of current character is odd hashOdd[c.charCodeAt() - 'a'.charCodeAt()]++; else hashEven[c.charCodeAt() - 'a'.charCodeAt()]++; } // For every character from 'a' to 'z', we store its // count at even position followed by a separator, // followed by count at odd position. let encoding = \"\"; for (let i = 0; i < MAX_CHAR; i++) { encoding += (hashEven[i]); encoding += ('-'); encoding += (hashOdd[i]); encoding += ('-'); } return encoding; } // This function basically uses a hashing based set to // store strings which are distinct according // to criteria given in question. function countDistinct(input, n) { let countDist = 0; // Initialize result // Create an empty set and store all distinct // strings in it. let s = new Set(); for (let i = 0; i < n; i++) { // If this encoding appears first time, increment // count of distinct encodings. if (!s.has(encodeString(input[i].split('')))) { s.add(encodeString(input[i].split(''))); countDist++; } } return countDist; } // Driver program let input = [\"abcd\", \"acbd\", \"adcb\", \"cdba\", \"bcda\", \"badc\"]; let n = input.length; document.write(countDistinct(input, n)); </script>",
"e": 37123,
"s": 35089,
"text": null
},
{
"code": null,
"e": 37125,
"s": 37123,
"text": "4"
},
{
"code": null,
"e": 37537,
"s": 37125,
"text": "This article is contributed by kp93. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 37555,
"s": 37537,
"text": "krutikkhandhadiya"
},
{
"code": null,
"e": 37567,
"s": 37555,
"text": "29AjayKumar"
},
{
"code": null,
"e": 37580,
"s": 37567,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 37592,
"s": 37580,
"text": "sanjeev2552"
},
{
"code": null,
"e": 37609,
"s": 37592,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 37621,
"s": 37609,
"text": "NishaBharti"
},
{
"code": null,
"e": 37629,
"s": 37621,
"text": "jayliya"
},
{
"code": null,
"e": 37642,
"s": 37629,
"text": "simmytarika5"
},
{
"code": null,
"e": 37647,
"s": 37642,
"text": "Hash"
},
{
"code": null,
"e": 37655,
"s": 37647,
"text": "Strings"
},
{
"code": null,
"e": 37660,
"s": 37655,
"text": "Hash"
},
{
"code": null,
"e": 37668,
"s": 37660,
"text": "Strings"
},
{
"code": null,
"e": 37766,
"s": 37668,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37802,
"s": 37766,
"text": "Hashing | Set 2 (Separate Chaining)"
},
{
"code": null,
"e": 37836,
"s": 37802,
"text": "Most frequent element in an array"
},
{
"code": null,
"e": 37862,
"s": 37836,
"text": "Sort string of characters"
},
{
"code": null,
"e": 37901,
"s": 37862,
"text": "Counting frequencies of array elements"
},
{
"code": null,
"e": 37916,
"s": 37901,
"text": "Double Hashing"
},
{
"code": null,
"e": 37941,
"s": 37916,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 37987,
"s": 37941,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 38021,
"s": 37987,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 38081,
"s": 38021,
"text": "Write a program to print all permutations of a given string"
}
] |
Python program to communicate between parent and child process using the pipe.
|
Using fork is the easiest way to create child process.fork () is part of the os standard Python library.
Here, we solve this task by using of pipe(). For passing information from one process to another pipe() is used. For two way communication two pipes can be use, one for each direction because pipe() is unidirectional.
Step 1: file descriptors r, w for reading and writing.
Step 2: Create a process using the fork.
Step 3: if process id is 0 then create a child process.
Step 4: else create parent process.
import os
def parentchild(cwrites):
r, w = os.pipe()
pid = os.fork()
if pid:
os.close(w)
r = os.fdopen(r)
print ("Parent is reading")
str = r.read()
print( "Parent reads =", str)
else:
os.close(r)
w = os.fdopen (w, 'w')
print ("Child is writing")
w.write(cwrites)
print("Child writes = ",cwrites)
w.close()
# Driver code
cwrites = "Python Program"
parentchild(cwrites)
Child is writing
Child writes = Python Program
Parent is reading
Parent reads = Python Program
|
[
{
"code": null,
"e": 1167,
"s": 1062,
"text": "Using fork is the easiest way to create child process.fork () is part of the os standard Python library."
},
{
"code": null,
"e": 1385,
"s": 1167,
"text": "Here, we solve this task by using of pipe(). For passing information from one process to another pipe() is used. For two way communication two pipes can be use, one for each direction because pipe() is unidirectional."
},
{
"code": null,
"e": 1574,
"s": 1385,
"text": "Step 1: file descriptors r, w for reading and writing.\nStep 2: Create a process using the fork.\nStep 3: if process id is 0 then create a child process.\nStep 4: else create parent process.\n"
},
{
"code": null,
"e": 2048,
"s": 1574,
"text": "import os \ndef parentchild(cwrites): \n r, w = os.pipe() \n pid = os.fork() \n if pid: \n os.close(w) \n r = os.fdopen(r) \n print (\"Parent is reading\") \n str = r.read() \n print( \"Parent reads =\", str) \n else: \n os.close(r) \n w = os.fdopen (w, 'w') \n print (\"Child is writing\") \n w.write(cwrites) \n print(\"Child writes = \",cwrites) \n w.close() \n# Driver code \ncwrites = \"Python Program\"\nparentchild(cwrites) "
},
{
"code": null,
"e": 2144,
"s": 2048,
"text": "Child is writing\nChild writes = Python Program\nParent is reading\nParent reads = Python Program\n"
}
] |
Deep learning on a combination of time series and tabular data. | by Manish Chablani | Towards Data Science
|
We often times find ourself in a situation where we have combination of different features that we want to leverage in our model. The input data to your model is a mix of time series and tabular data. Architecting a deep learning model to work well in this scenario is an interesting problem.
One example scenario is: You have data from a device like fitbit and you want to predict a sleep stage at any given minute:
You have a mixture of:
Time series inputs:
sequence of heart rate
sequence of respiratory rate
Tabular features:
time since sleep onset
personalized embedding representing this users sleep pattern
and bunch of other features.
One way to approach this is treat it as multimodal deep learning.
And mix in “wide and deep learning” as introduced by google research here
Pass in time series sequence though an RNN or LSTM or 1D CNN and capture the hidden state or CNN embedding as a representation of the sequence.Concatenate embeddings for each of the sequence with other tabular features.
Pass in time series sequence though an RNN or LSTM or 1D CNN and capture the hidden state or CNN embedding as a representation of the sequence.
Concatenate embeddings for each of the sequence with other tabular features.
For the multiple time series input sequences:
do you treat the sequences independent and fuse/concatenate the representations late (late fusion)?
Or do you treat them as multi-channel input with each time series as a channel (early fusion)?
In general late fusion seems to work better than early fusion and also does not require padding the input when different input sequences are not of same length. However it is really dependent on the problem space and correlation of input sequences.
In general RNN seems to work better for shorter sequences and bidirectional LSTM for longer sequences. In late fusion you can mix and match RNN/LSTM/1d CNN for different sequences.
This example uses 2 layer bidi LSTM with late fusion.
For each of the time series features (feature_1 and feature_2) we also have the baseline values, hence we have fusion layers where we fuse representation of sequence (hidden state of LSTM) with the baseline values. However this fusion layer is not necessary and is not required in the absence of baseline values.
class TestModel(nn.Module): def __init__(self): super().__init__() self.input_size = 70 self.hidden_size = 8 self.num_layers = 2 self.output_dim = 2 self.lstm_feature_1 = nn.LSTM(self.input_size, self.hidden_size, self.num_layers, batch_first=True, bidirectional=True) self.lstm_feature_2 = nn.LSTM(self.input_size, self.hidden_size, self.num_layers, batch_first=True, bidirectional=True) self.fc_feature_1 = nn.Linear((self.hidden_size * 2) + 1, 1) self.fc_feature_2 = nn.Linear((self.hidden_size * 2) + 1, 1) self.fc = nn.Linear(4, self.output_dim) def forward(self, f, device=None): if not device: device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") x_f1, f1, x_f2, f2, f3, f4 = f # x_f1 is feature_1_seq # f1 is feature_1_baseline # x_f2 is feature_2_seq # f2 is feature_2_baseline # f3 and f4 are tabular features x_f1 = x_f1.view(x_f1.shape[0], 1, -1) h0_f1, c0_f1 = self.init_hidden(x_f1, device) h_t_f1, c_t_f1 = self.lstm_feature_1(x_f1, (h0_f1, c0_f1)) x_f1 = h_t_f1 x_f1 = x_f1.view(x_f1.shape[0], -1) x_f2 = x_f2.view(x_f2.shape[0], 1, -1) h0_f2, c0_f2 = self.init_hidden(x_f2, device) h_t_f2, c_t_f2 = self.lstm_feature_2(x_f2, (h0_f2, c0_f2)) x_f2 = h_t_f2 x_f2 = x_f2.view(x_f2.shape[0], -1) x_f1 = torch.cat((x_f1, f1), 1) x_f1 = self.fc_feature_1(x_f1) x_f2 = torch.cat((x_f2, f2), 1) x_f2 = self.fc_feature_2(x_f2) x = torch.cat((x_f1, x_f2, f3, f4), 1) x = self.fc(x) x = F.log_softmax(x, dim=1) return x def init_hidden(self, x, device): batch_size = x.size(0) h0 = torch.zeros(self.num_layers * 2, batch_size, self.hidden_size).to(device) c0 = torch.zeros(self.num_layers * 2, batch_size, self.hidden_size).to(device) return h0, c0
If you have worked on a problem that has involved similar style of input: I would love to hear from you on what has worked for you or any other ways you have tried to approach it.
|
[
{
"code": null,
"e": 340,
"s": 47,
"text": "We often times find ourself in a situation where we have combination of different features that we want to leverage in our model. The input data to your model is a mix of time series and tabular data. Architecting a deep learning model to work well in this scenario is an interesting problem."
},
{
"code": null,
"e": 464,
"s": 340,
"text": "One example scenario is: You have data from a device like fitbit and you want to predict a sleep stage at any given minute:"
},
{
"code": null,
"e": 487,
"s": 464,
"text": "You have a mixture of:"
},
{
"code": null,
"e": 507,
"s": 487,
"text": "Time series inputs:"
},
{
"code": null,
"e": 530,
"s": 507,
"text": "sequence of heart rate"
},
{
"code": null,
"e": 559,
"s": 530,
"text": "sequence of respiratory rate"
},
{
"code": null,
"e": 577,
"s": 559,
"text": "Tabular features:"
},
{
"code": null,
"e": 600,
"s": 577,
"text": "time since sleep onset"
},
{
"code": null,
"e": 661,
"s": 600,
"text": "personalized embedding representing this users sleep pattern"
},
{
"code": null,
"e": 690,
"s": 661,
"text": "and bunch of other features."
},
{
"code": null,
"e": 756,
"s": 690,
"text": "One way to approach this is treat it as multimodal deep learning."
},
{
"code": null,
"e": 830,
"s": 756,
"text": "And mix in “wide and deep learning” as introduced by google research here"
},
{
"code": null,
"e": 1050,
"s": 830,
"text": "Pass in time series sequence though an RNN or LSTM or 1D CNN and capture the hidden state or CNN embedding as a representation of the sequence.Concatenate embeddings for each of the sequence with other tabular features."
},
{
"code": null,
"e": 1194,
"s": 1050,
"text": "Pass in time series sequence though an RNN or LSTM or 1D CNN and capture the hidden state or CNN embedding as a representation of the sequence."
},
{
"code": null,
"e": 1271,
"s": 1194,
"text": "Concatenate embeddings for each of the sequence with other tabular features."
},
{
"code": null,
"e": 1317,
"s": 1271,
"text": "For the multiple time series input sequences:"
},
{
"code": null,
"e": 1417,
"s": 1317,
"text": "do you treat the sequences independent and fuse/concatenate the representations late (late fusion)?"
},
{
"code": null,
"e": 1512,
"s": 1417,
"text": "Or do you treat them as multi-channel input with each time series as a channel (early fusion)?"
},
{
"code": null,
"e": 1761,
"s": 1512,
"text": "In general late fusion seems to work better than early fusion and also does not require padding the input when different input sequences are not of same length. However it is really dependent on the problem space and correlation of input sequences."
},
{
"code": null,
"e": 1942,
"s": 1761,
"text": "In general RNN seems to work better for shorter sequences and bidirectional LSTM for longer sequences. In late fusion you can mix and match RNN/LSTM/1d CNN for different sequences."
},
{
"code": null,
"e": 1996,
"s": 1942,
"text": "This example uses 2 layer bidi LSTM with late fusion."
},
{
"code": null,
"e": 2309,
"s": 1996,
"text": "For each of the time series features (feature_1 and feature_2) we also have the baseline values, hence we have fusion layers where we fuse representation of sequence (hidden state of LSTM) with the baseline values. However this fusion layer is not necessary and is not required in the absence of baseline values."
},
{
"code": null,
"e": 4349,
"s": 2309,
"text": "class TestModel(nn.Module): def __init__(self): super().__init__() self.input_size = 70 self.hidden_size = 8 self.num_layers = 2 self.output_dim = 2 self.lstm_feature_1 = nn.LSTM(self.input_size, self.hidden_size, self.num_layers, batch_first=True, bidirectional=True) self.lstm_feature_2 = nn.LSTM(self.input_size, self.hidden_size, self.num_layers, batch_first=True, bidirectional=True) self.fc_feature_1 = nn.Linear((self.hidden_size * 2) + 1, 1) self.fc_feature_2 = nn.Linear((self.hidden_size * 2) + 1, 1) self.fc = nn.Linear(4, self.output_dim) def forward(self, f, device=None): if not device: device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\") x_f1, f1, x_f2, f2, f3, f4 = f # x_f1 is feature_1_seq # f1 is feature_1_baseline # x_f2 is feature_2_seq # f2 is feature_2_baseline # f3 and f4 are tabular features x_f1 = x_f1.view(x_f1.shape[0], 1, -1) h0_f1, c0_f1 = self.init_hidden(x_f1, device) h_t_f1, c_t_f1 = self.lstm_feature_1(x_f1, (h0_f1, c0_f1)) x_f1 = h_t_f1 x_f1 = x_f1.view(x_f1.shape[0], -1) x_f2 = x_f2.view(x_f2.shape[0], 1, -1) h0_f2, c0_f2 = self.init_hidden(x_f2, device) h_t_f2, c_t_f2 = self.lstm_feature_2(x_f2, (h0_f2, c0_f2)) x_f2 = h_t_f2 x_f2 = x_f2.view(x_f2.shape[0], -1) x_f1 = torch.cat((x_f1, f1), 1) x_f1 = self.fc_feature_1(x_f1) x_f2 = torch.cat((x_f2, f2), 1) x_f2 = self.fc_feature_2(x_f2) x = torch.cat((x_f1, x_f2, f3, f4), 1) x = self.fc(x) x = F.log_softmax(x, dim=1) return x def init_hidden(self, x, device): batch_size = x.size(0) h0 = torch.zeros(self.num_layers * 2, batch_size, self.hidden_size).to(device) c0 = torch.zeros(self.num_layers * 2, batch_size, self.hidden_size).to(device) return h0, c0"
}
] |
Chain Code for 2D Line - GeeksforGeeks
|
06 Sep, 2021
Chain code is a lossless compression technique used for representing an object in images. The co-ordinates of any continuous boundary of an object can be represented as a string of numbers where each number represents a particular direction in which the next point on the connected line is present. One point is taken as the reference/starting point and on plotting the points generated from the chain, the original figure can be re-drawn.
This article describes how to generate a 8-neighbourhood chain code of a 2-D straight line. In a rectangular grid, a point can have at most 8 surrounding points as shown below. The next point on the line has to be one of these 8 surrounding points. Each direction is assigned a code. Using this code we can find out which of the surrounding point should be plotted next.
The chain codes could be generated by using conditional statements for each direction but it becomes very tedious to describe for systems having large number of directions(3-D grids can have up to 26 directions). Instead we use a hash function. The difference in X() and Y() co-ordinates of two successive points are calculated and hashed to generate the key for the chain code between the two points.
Chain code list:
Hash function:
Hash table:-
The function does not generate the value 4 so a dummy value is stored there.
Examples:
Input : (2, -3), (-4, 2)
Output : Chain code for the straight line from (2, -3) to (-4, 2) is 333433
Input : (-7, -4), (9, 3)
Output : Chain code for the straight line from (-7, -4) to (9, 3) is 0101010100101010
Python3
# Python3 code for generating 8-neighbourhood chain# code for a 2-D line codeList = [5, 6, 7, 4, -1, 0, 3, 2, 1] # This function generates the chaincode# for transition between two neighbour pointsdef getChainCode(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 hashKey = 3 * dy + dx + 4 return codeList[hashKey] '''This function generates the list ofchaincodes for given list of points'''def generateChainCode(ListOfPoints): chainCode = [] for i in range(len(ListOfPoints) - 1): a = ListOfPoints[i] b = ListOfPoints[i + 1] chainCode.append(getChainCode(a[0], a[1], b[0], b[1])) return chainCode '''This function generates the list of points fora straight line using Bresenham's Algorithm'''def Bresenham2D(x1, y1, x2, y2): ListOfPoints = [] ListOfPoints.append([x1, y1]) xdif = x2 - x1 ydif = y2 - y1 dx = abs(xdif) dy = abs(ydif) if(xdif > 0): xs = 1 else: xs = -1 if (ydif > 0): ys = 1 else: ys = -1 if (dx > dy): # Driving axis is the X-axis p = 2 * dy - dx while (x1 != x2): x1 += xs if (p >= 0): y1 += ys p -= 2 * dx p += 2 * dy ListOfPoints.append([x1, y1]) else: # Driving axis is the Y-axis p = 2 * dx-dy while(y1 != y2): y1 += ys if (p >= 0): x1 += xs p -= 2 * dy p += 2 * dx ListOfPoints.append([x1, y1]) return ListOfPoints def DriverFunction(): (x1, y1) = (-9, -3) (x2, y2) = (10, 1) ListOfPoints = Bresenham2D(x1, y1, x2, y2) chainCode = generateChainCode(ListOfPoints) chainCodeString = "".join(str(e) for e in chainCode) print ('Chain code for the straight line from', (x1, y1), 'to', (x2, y2), 'is', chainCodeString) DriverFunction()
Chain code for the straight line from (-9, -3) to (10, 1) is 0010000100010000100
rs1686740
computer-graphics
encoding-decoding
Image-Processing
Geometric
Python
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convex Hull using Divide and Conquer Algorithm
Equation of circle when three points on the circle are given
Circle and Lattice Points
Orientation of 3 ordered points
Program to find slope of a line
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": 25302,
"s": 25274,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 25742,
"s": 25302,
"text": "Chain code is a lossless compression technique used for representing an object in images. The co-ordinates of any continuous boundary of an object can be represented as a string of numbers where each number represents a particular direction in which the next point on the connected line is present. One point is taken as the reference/starting point and on plotting the points generated from the chain, the original figure can be re-drawn."
},
{
"code": null,
"e": 26116,
"s": 25745,
"text": "This article describes how to generate a 8-neighbourhood chain code of a 2-D straight line. In a rectangular grid, a point can have at most 8 surrounding points as shown below. The next point on the line has to be one of these 8 surrounding points. Each direction is assigned a code. Using this code we can find out which of the surrounding point should be plotted next."
},
{
"code": null,
"e": 26522,
"s": 26120,
"text": "The chain codes could be generated by using conditional statements for each direction but it becomes very tedious to describe for systems having large number of directions(3-D grids can have up to 26 directions). Instead we use a hash function. The difference in X() and Y() co-ordinates of two successive points are calculated and hashed to generate the key for the chain code between the two points."
},
{
"code": null,
"e": 26542,
"s": 26524,
"text": "Chain code list: "
},
{
"code": null,
"e": 26560,
"s": 26544,
"text": "Hash function: "
},
{
"code": null,
"e": 26577,
"s": 26562,
"text": "Hash table:- "
},
{
"code": null,
"e": 26656,
"s": 26579,
"text": "The function does not generate the value 4 so a dummy value is stored there."
},
{
"code": null,
"e": 26668,
"s": 26656,
"text": "Examples: "
},
{
"code": null,
"e": 26769,
"s": 26668,
"text": "Input : (2, -3), (-4, 2)\nOutput : Chain code for the straight line from (2, -3) to (-4, 2) is 333433"
},
{
"code": null,
"e": 26881,
"s": 26769,
"text": "\nInput : (-7, -4), (9, 3)\nOutput : Chain code for the straight line from (-7, -4) to (9, 3) is 0101010100101010"
},
{
"code": null,
"e": 26891,
"s": 26883,
"text": "Python3"
},
{
"code": "# Python3 code for generating 8-neighbourhood chain# code for a 2-D line codeList = [5, 6, 7, 4, -1, 0, 3, 2, 1] # This function generates the chaincode# for transition between two neighbour pointsdef getChainCode(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 hashKey = 3 * dy + dx + 4 return codeList[hashKey] '''This function generates the list ofchaincodes for given list of points'''def generateChainCode(ListOfPoints): chainCode = [] for i in range(len(ListOfPoints) - 1): a = ListOfPoints[i] b = ListOfPoints[i + 1] chainCode.append(getChainCode(a[0], a[1], b[0], b[1])) return chainCode '''This function generates the list of points fora straight line using Bresenham's Algorithm'''def Bresenham2D(x1, y1, x2, y2): ListOfPoints = [] ListOfPoints.append([x1, y1]) xdif = x2 - x1 ydif = y2 - y1 dx = abs(xdif) dy = abs(ydif) if(xdif > 0): xs = 1 else: xs = -1 if (ydif > 0): ys = 1 else: ys = -1 if (dx > dy): # Driving axis is the X-axis p = 2 * dy - dx while (x1 != x2): x1 += xs if (p >= 0): y1 += ys p -= 2 * dx p += 2 * dy ListOfPoints.append([x1, y1]) else: # Driving axis is the Y-axis p = 2 * dx-dy while(y1 != y2): y1 += ys if (p >= 0): x1 += xs p -= 2 * dy p += 2 * dx ListOfPoints.append([x1, y1]) return ListOfPoints def DriverFunction(): (x1, y1) = (-9, -3) (x2, y2) = (10, 1) ListOfPoints = Bresenham2D(x1, y1, x2, y2) chainCode = generateChainCode(ListOfPoints) chainCodeString = \"\".join(str(e) for e in chainCode) print ('Chain code for the straight line from', (x1, y1), 'to', (x2, y2), 'is', chainCodeString) DriverFunction()",
"e": 28768,
"s": 26891,
"text": null
},
{
"code": null,
"e": 28849,
"s": 28768,
"text": "Chain code for the straight line from (-9, -3) to (10, 1) is 0010000100010000100"
},
{
"code": null,
"e": 28861,
"s": 28851,
"text": "rs1686740"
},
{
"code": null,
"e": 28879,
"s": 28861,
"text": "computer-graphics"
},
{
"code": null,
"e": 28897,
"s": 28879,
"text": "encoding-decoding"
},
{
"code": null,
"e": 28914,
"s": 28897,
"text": "Image-Processing"
},
{
"code": null,
"e": 28924,
"s": 28914,
"text": "Geometric"
},
{
"code": null,
"e": 28931,
"s": 28924,
"text": "Python"
},
{
"code": null,
"e": 28941,
"s": 28931,
"text": "Geometric"
},
{
"code": null,
"e": 29039,
"s": 28941,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29086,
"s": 29039,
"text": "Convex Hull using Divide and Conquer Algorithm"
},
{
"code": null,
"e": 29147,
"s": 29086,
"text": "Equation of circle when three points on the circle are given"
},
{
"code": null,
"e": 29173,
"s": 29147,
"text": "Circle and Lattice Points"
},
{
"code": null,
"e": 29205,
"s": 29173,
"text": "Orientation of 3 ordered points"
},
{
"code": null,
"e": 29237,
"s": 29205,
"text": "Program to find slope of a line"
},
{
"code": null,
"e": 29265,
"s": 29237,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 29315,
"s": 29265,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 29337,
"s": 29315,
"text": "Python map() function"
}
] |
Operating Systems | Set 3 - GeeksforGeeks
|
17 Jun, 2021
Following questions have been asked in GATE CS exam.
1. Suppose the time to service a page fault is on the average 10 milliseconds, while a memory access takes 1 microsecond. Then a 99.99% hit ratio results in average memory access time of (GATE CS 2000) (a) 1.9999 milliseconds (b) 1 millisecond (c) 9.999 microseconds (d) 1.9999 microseconds
Answer: (d) Explanation:
Average memory access time =
[(% of page miss)*(time to service a page fault) +
(% of page hit)*(memory access time)]/100
So, average memory access time in microseconds is. (0.01*10*1000 + 99.99*1)/100 = (100+99.99)/100 = 199.99/100 =1.9999 μs
2. Which of the following need not necessarily be saved on a context switch between processes? (GATE CS 2000) (a) General purpose registers (b) Translation look-aside buffer (c) Program counter (d) All of the above
Answer: (b) Explanation: In a process context switch, the state of the first process must be saved somehow, so that, when the scheduler gets back to the execution of the first process, it can restore this state and continue.
The state of the process includes all the registers that the process may be using, especially the program counter, plus any other operating system specific data that may be necessary.
A Translation lookaside buffer (TLB) is a CPU cache that memory management hardware uses to improve virtual address translation speed. A TLB has a fixed number of slots that contain page table entries, which map virtual addresses to physical addresses. On a context switch, some TLB entries can become invalid, since the virtual-to-physical mapping is different. The simplest strategy to deal with this is to completely flush the TLB. References: http://en.wikipedia.org/wiki/Context_switch http://en.wikipedia.org/wiki/Translation_lookaside_buffer#Context_switch
3. Where does the swap space reside ? (GATE 2001) (a) RAM (b) Disk (c) ROM (d) On-chip cache Answer: (b) Explanation: Swap space is an area on disk that temporarily holds a process memory image. When physical memory demand is sufficiently low, process memory images are brought back into physical memory from the swap area. Having sufficient swap space enables the system to keep some physical memory free at all times. References: http://docs.hp.com/en/B2355-90672/ch06s02.html
4. Which of the following does not interrupt a running process? (GATE CS 2001) (a) A device (b) Timer (c) Scheduler process (d) Power failure
Answer: (c) Explanation: Scheduler process doesn’t interrupt any process, it’s Job is to select the processes for following three purposes. Long-term scheduler(or job scheduler) –selects which processes should be brought into the ready queue Short-term scheduler(or CPU scheduler) –selects which process should be executed next and allocates CPU. Mid-term Scheduler (Swapper)- present in all systems with virtual memory, temporarily removes processes from main memory and places them on secondary memory (such as a disk drive) or vice versa. The mid-term scheduler may decide to swap out a process which has not been active for some time, or a process which has a low priority, or a process which is page faulting frequently, or a process which is taking up a large amount of memory in order to free up main memory for other processes, swapping the process back in later when more memory is available, or when the process has been unblocked and is no longer waiting for a resource.
5. Which of the following scheduling algorithms is non-preemptive? (GATE CS 2002)
a) Round Robin b) First-In First-Out c) Multilevel Queue Scheduling d) Multilevel Queue Scheduling with Feedback
Answer: (b)
mohit17067
GATE CS
MCQ
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Normal Forms in DBMS
Differences between TCP and UDP
Practice questions on Height balanced/AVL Tree
Computer Networks | Set 1
Computer Networks | Set 2
Compiler Theory | Set 1
Database Management Systems | Set 1
|
[
{
"code": null,
"e": 28186,
"s": 28158,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 28240,
"s": 28186,
"text": "Following questions have been asked in GATE CS exam. "
},
{
"code": null,
"e": 28532,
"s": 28240,
"text": "1. Suppose the time to service a page fault is on the average 10 milliseconds, while a memory access takes 1 microsecond. Then a 99.99% hit ratio results in average memory access time of (GATE CS 2000) (a) 1.9999 milliseconds (b) 1 millisecond (c) 9.999 microseconds (d) 1.9999 microseconds "
},
{
"code": null,
"e": 28559,
"s": 28532,
"text": "Answer: (d) Explanation: "
},
{
"code": null,
"e": 28705,
"s": 28559,
"text": "Average memory access time =\n [(% of page miss)*(time to service a page fault) +\n (% of page hit)*(memory access time)]/100"
},
{
"code": null,
"e": 28828,
"s": 28705,
"text": "So, average memory access time in microseconds is. (0.01*10*1000 + 99.99*1)/100 = (100+99.99)/100 = 199.99/100 =1.9999 μs "
},
{
"code": null,
"e": 29044,
"s": 28828,
"text": "2. Which of the following need not necessarily be saved on a context switch between processes? (GATE CS 2000) (a) General purpose registers (b) Translation look-aside buffer (c) Program counter (d) All of the above "
},
{
"code": null,
"e": 29270,
"s": 29044,
"text": "Answer: (b) Explanation: In a process context switch, the state of the first process must be saved somehow, so that, when the scheduler gets back to the execution of the first process, it can restore this state and continue. "
},
{
"code": null,
"e": 29455,
"s": 29270,
"text": "The state of the process includes all the registers that the process may be using, especially the program counter, plus any other operating system specific data that may be necessary. "
},
{
"code": null,
"e": 30020,
"s": 29455,
"text": "A Translation lookaside buffer (TLB) is a CPU cache that memory management hardware uses to improve virtual address translation speed. A TLB has a fixed number of slots that contain page table entries, which map virtual addresses to physical addresses. On a context switch, some TLB entries can become invalid, since the virtual-to-physical mapping is different. The simplest strategy to deal with this is to completely flush the TLB. References: http://en.wikipedia.org/wiki/Context_switch http://en.wikipedia.org/wiki/Translation_lookaside_buffer#Context_switch "
},
{
"code": null,
"e": 30500,
"s": 30020,
"text": "3. Where does the swap space reside ? (GATE 2001) (a) RAM (b) Disk (c) ROM (d) On-chip cache Answer: (b) Explanation: Swap space is an area on disk that temporarily holds a process memory image. When physical memory demand is sufficiently low, process memory images are brought back into physical memory from the swap area. Having sufficient swap space enables the system to keep some physical memory free at all times. References: http://docs.hp.com/en/B2355-90672/ch06s02.html "
},
{
"code": null,
"e": 30643,
"s": 30500,
"text": "4. Which of the following does not interrupt a running process? (GATE CS 2001) (a) A device (b) Timer (c) Scheduler process (d) Power failure "
},
{
"code": null,
"e": 31626,
"s": 30643,
"text": "Answer: (c) Explanation: Scheduler process doesn’t interrupt any process, it’s Job is to select the processes for following three purposes. Long-term scheduler(or job scheduler) –selects which processes should be brought into the ready queue Short-term scheduler(or CPU scheduler) –selects which process should be executed next and allocates CPU. Mid-term Scheduler (Swapper)- present in all systems with virtual memory, temporarily removes processes from main memory and places them on secondary memory (such as a disk drive) or vice versa. The mid-term scheduler may decide to swap out a process which has not been active for some time, or a process which has a low priority, or a process which is page faulting frequently, or a process which is taking up a large amount of memory in order to free up main memory for other processes, swapping the process back in later when more memory is available, or when the process has been unblocked and is no longer waiting for a resource. "
},
{
"code": null,
"e": 31709,
"s": 31626,
"text": "5. Which of the following scheduling algorithms is non-preemptive? (GATE CS 2002) "
},
{
"code": null,
"e": 31823,
"s": 31709,
"text": "a) Round Robin b) First-In First-Out c) Multilevel Queue Scheduling d) Multilevel Queue Scheduling with Feedback "
},
{
"code": null,
"e": 31836,
"s": 31823,
"text": "Answer: (b) "
},
{
"code": null,
"e": 31847,
"s": 31836,
"text": "mohit17067"
},
{
"code": null,
"e": 31855,
"s": 31847,
"text": "GATE CS"
},
{
"code": null,
"e": 31859,
"s": 31855,
"text": "MCQ"
},
{
"code": null,
"e": 31877,
"s": 31859,
"text": "Operating Systems"
},
{
"code": null,
"e": 31895,
"s": 31877,
"text": "Operating Systems"
},
{
"code": null,
"e": 31993,
"s": 31895,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32013,
"s": 31993,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 32037,
"s": 32013,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 32050,
"s": 32037,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 32071,
"s": 32050,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 32103,
"s": 32071,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 32150,
"s": 32103,
"text": "Practice questions on Height balanced/AVL Tree"
},
{
"code": null,
"e": 32176,
"s": 32150,
"text": "Computer Networks | Set 1"
},
{
"code": null,
"e": 32202,
"s": 32176,
"text": "Computer Networks | Set 2"
},
{
"code": null,
"e": 32226,
"s": 32202,
"text": "Compiler Theory | Set 1"
}
] |
Changing Column in MySQL from int to double?
|
To change the column in MySQL from int to double you need to use ALTER TABLE command.
The syntax is as follows:
ALTER TABLE yourTableName modify column yourColumnName DOUBLE NOT NULL;
If you want NULL value then remove NOT NULL from the above syntax. The syntax is as follows:
ALTER TABLE yourTableName modify column yourColumnName DOUBLE;
To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table IntToDoubleDemo
-> (
-> Id int NOT NULL AUTO_INCREMENT,
-> Name varchar(10),
-> CylinderVolume int,
-> PRIMARY KEY(Id)
-> );
Query OK, 0 rows affected (0.63 sec)
Check the description of the table using DESC command. The syntax is as follows:
DESC yourTableName;
Apply the above query for your table to get the description of the table:
mysql> desc IntToDoubleDemo;
The following is the output:
+----------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+----------------+
| Id | int(11) | NO | PRI | NULL | auto_increment |
| Name | varchar(10) | YES | | NULL | |
| CylinderVolume | int(11) | YES | | NULL | |
+----------------+-------------+------+-----+---------+----------------+
3 rows in set (0.18 sec)
Look at the above sample output, the field ‘CylinderVolume’ is a type of int. Now you can convert from int to double.
Change the column in MySQL from int to double. The query is as follows:
mysql> alter table IntToDoubleDemo MODIFY COLUMN CylinderVolume double NOT NULL;
Query OK, 0 rows affected (2.79 sec)
Records: 0 Duplicates: 0 Warnings: 0
Once again check the description of the table. The query is as follows:
mysql> desc IntToDoubleDemo\G
The following is the output:
*************************** 1. row ***************************
Field: Id
Type: int(11)
Null: NO
Key: PRI
Default: NULL
Extra: auto_increment
*************************** 2. row ***************************
Field: Name
Type: varchar(10)
Null: YES
Key:
Default: NULL
Extra:
*************************** 3. row ***************************
Field: CylinderVolume
Type: double
Null: NO
Key:
Default: NULL
Extra:
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1148,
"s": 1062,
"text": "To change the column in MySQL from int to double you need to use ALTER TABLE command."
},
{
"code": null,
"e": 1174,
"s": 1148,
"text": "The syntax is as follows:"
},
{
"code": null,
"e": 1246,
"s": 1174,
"text": "ALTER TABLE yourTableName modify column yourColumnName DOUBLE NOT NULL;"
},
{
"code": null,
"e": 1339,
"s": 1246,
"text": "If you want NULL value then remove NOT NULL from the above syntax. The syntax is as follows:"
},
{
"code": null,
"e": 1402,
"s": 1339,
"text": "ALTER TABLE yourTableName modify column yourColumnName DOUBLE;"
},
{
"code": null,
"e": 1500,
"s": 1402,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows:"
},
{
"code": null,
"e": 1700,
"s": 1500,
"text": "mysql> create table IntToDoubleDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> Name varchar(10),\n -> CylinderVolume int,\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.63 sec)"
},
{
"code": null,
"e": 1781,
"s": 1700,
"text": "Check the description of the table using DESC command. The syntax is as follows:"
},
{
"code": null,
"e": 1801,
"s": 1781,
"text": "DESC yourTableName;"
},
{
"code": null,
"e": 1875,
"s": 1801,
"text": "Apply the above query for your table to get the description of the table:"
},
{
"code": null,
"e": 1904,
"s": 1875,
"text": "mysql> desc IntToDoubleDemo;"
},
{
"code": null,
"e": 1933,
"s": 1904,
"text": "The following is the output:"
},
{
"code": null,
"e": 2469,
"s": 1933,
"text": "+----------------+-------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+----------------+-------------+------+-----+---------+----------------+\n| Id | int(11) | NO | PRI | NULL | auto_increment |\n| Name | varchar(10) | YES | | NULL | |\n| CylinderVolume | int(11) | YES | | NULL | |\n+----------------+-------------+------+-----+---------+----------------+\n3 rows in set (0.18 sec)"
},
{
"code": null,
"e": 2587,
"s": 2469,
"text": "Look at the above sample output, the field ‘CylinderVolume’ is a type of int. Now you can convert from int to double."
},
{
"code": null,
"e": 2659,
"s": 2587,
"text": "Change the column in MySQL from int to double. The query is as follows:"
},
{
"code": null,
"e": 2814,
"s": 2659,
"text": "mysql> alter table IntToDoubleDemo MODIFY COLUMN CylinderVolume double NOT NULL;\nQuery OK, 0 rows affected (2.79 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2886,
"s": 2814,
"text": "Once again check the description of the table. The query is as follows:"
},
{
"code": null,
"e": 2916,
"s": 2886,
"text": "mysql> desc IntToDoubleDemo\\G"
},
{
"code": null,
"e": 2945,
"s": 2916,
"text": "The following is the output:"
},
{
"code": null,
"e": 3373,
"s": 2945,
"text": "*************************** 1. row ***************************\nField: Id\nType: int(11)\nNull: NO\nKey: PRI\nDefault: NULL\nExtra: auto_increment\n*************************** 2. row ***************************\nField: Name\nType: varchar(10)\nNull: YES\nKey:\nDefault: NULL\nExtra:\n*************************** 3. row ***************************\nField: CylinderVolume\nType: double\nNull: NO\nKey:\nDefault: NULL\nExtra:\n3 rows in set (0.00 sec)"
}
] |
How to remove gaps between bars in Matplotlib bar chart?
|
To remove gaps between bars, we can change the align value to center in the argument of bar() method.
Create a dictionary called data with two keys, milk and water.
Create a dictionary called data with two keys, milk and water.
Get the list of keys and values in the dictionay.
Get the list of keys and values in the dictionay.
Using subplots() method, create a figure and add a set of two subplots.
Using subplots() method, create a figure and add a set of two subplots.
On axis 2, use bar method to plot bars without gaps. Set the width attribute as 1.0. Set the title using set_title() method.
On axis 2, use bar method to plot bars without gaps. Set the width attribute as 1.0. Set the title using set_title() method.
Use tight_layout() to adjust the padding between and around the subplots.
Use tight_layout() to adjust the padding between and around the subplots.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
data = {'milk': 12, 'water': 10}
names = list(data.keys())
values = list(data.values())
fif, (ax1, ax2) = plt.subplots(2)
ax1.bar(range(len(data)), values, align='center', width=.05, color='yellow')
ax1.set_title("with gap")
ax2.bar(range(len(data)), values, align='edge', width=1.0, color='yellow')
ax2.set_title("without gap")
plt.tight_layout()
plt.show()
|
[
{
"code": null,
"e": 1164,
"s": 1062,
"text": "To remove gaps between bars, we can change the align value to center in the argument of bar() method."
},
{
"code": null,
"e": 1227,
"s": 1164,
"text": "Create a dictionary called data with two keys, milk and water."
},
{
"code": null,
"e": 1290,
"s": 1227,
"text": "Create a dictionary called data with two keys, milk and water."
},
{
"code": null,
"e": 1340,
"s": 1290,
"text": "Get the list of keys and values in the dictionay."
},
{
"code": null,
"e": 1390,
"s": 1340,
"text": "Get the list of keys and values in the dictionay."
},
{
"code": null,
"e": 1462,
"s": 1390,
"text": "Using subplots() method, create a figure and add a set of two subplots."
},
{
"code": null,
"e": 1534,
"s": 1462,
"text": "Using subplots() method, create a figure and add a set of two subplots."
},
{
"code": null,
"e": 1659,
"s": 1534,
"text": "On axis 2, use bar method to plot bars without gaps. Set the width attribute as 1.0. Set the title using set_title() method."
},
{
"code": null,
"e": 1784,
"s": 1659,
"text": "On axis 2, use bar method to plot bars without gaps. Set the width attribute as 1.0. Set the title using set_title() method."
},
{
"code": null,
"e": 1858,
"s": 1784,
"text": "Use tight_layout() to adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1932,
"s": 1858,
"text": "Use tight_layout() to adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1974,
"s": 1932,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2016,
"s": 1974,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2494,
"s": 2016,
"text": "import matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndata = {'milk': 12, 'water': 10}\nnames = list(data.keys())\nvalues = list(data.values())\nfif, (ax1, ax2) = plt.subplots(2)\nax1.bar(range(len(data)), values, align='center', width=.05, color='yellow')\nax1.set_title(\"with gap\")\nax2.bar(range(len(data)), values, align='edge', width=1.0, color='yellow')\nax2.set_title(\"without gap\")\nplt.tight_layout()\nplt.show()"
}
] |
Principal Components Analysis (PCA) In Python In Under 5 Minutes | by Wei Hao Khoong | Towards Data Science
|
Existing knowledge of linear algebra and matrix factorization
Python 3 programming proficiency
In a nutshell, PCA is arguably the most popular dimensionality reduction algorithm for datasets with a large number of features. It serves to remove highly correlated features and redundant ones, and also trims away noise in the data.
Recent machine learning (ML) algorithms and neural networks work well with datasets of high dimensions, often times with hundreds of thousands or over a million features. Note that due to recent advancements in compute technology (PCs/GPUs), it has been increasingly efficient to deal with high-dimensional data without the need to reduce their dimensions for use due to compute constraints. However, dimensionality reduction algorithms like PCA are still used for various considerations, such as reducing overfitting of the ML model by eliminating features with high correlation, by creating new uncorrelated variables that successively maximize variance.
Recall from literature that we can obtain the principal components matrix V via Singular Value Decomposition (SVD), a matrix factorization technique. Here, we have
where there are n principal components in V.
In other words, SVD decomposes the data matrix X into three matrices:
where U comprises of the left singular vectors, Σ is a diagonal matrix with the same dimensions as X containing the singular values, and V contains the right singular vectors/principal components.
In Python, we utilize Numpy’s svd() function to obtain all the principal components of X:
U, S, V_T = np.linalg.svd(X)# transpose to get V, with number of components as V.shape[1]V = V_T.T# first componentc1 = V[:, 0]# last (n-th) componentcn = V[:, -1]
Now, we are ready to reduce the dimensions of X using the components found! To reduce the dimension to d, we have to project the data onto the hyperplane defined by the first d components. Doing so results in the hyperplane preserving as much of the variance as possible. Mathematically, we compute the multiplication of X by the matrix W, which is the matrix comprising of the first d principal components:
In Python, we have the following:
W = V[:, :d] # d is the number of componentsX_d = X.dot(W)
Fortunately for us, the Scikit-learn Python library has all this set up for us. Suppose that we have defined d and X previously. We can then use the following code to obtain the resulting X matrix after dimensionality reduction by utilizing the first d principal components:
from sklearn.decomposition import PCApca = PCA(n_components = d)X_d = pca.fit_transform(X)
To access the individual components, it is slightly different. We have to use the components_ variable:
# first componentc1 = pca.components_.T[:, 0]
A side remark here is that the components are horizontal vectors, so you’ll have to transpose them with a .T as above.
A common practice is to choose a number of dimensions that add up to a sufficiently large portion of the variance. Usually, a convention will be to retain 95% of the variance, but that depends on your needs. For example, if you seek to reduce the dimensions to visualize the data better, you will have to reduce it to 2 or at most 3 dimensions as humans cannot read more than 3 dimensions visually.
In this approach, we iterate through the proportions of variance explained by the components until a certain threshold is reached — the desired proportion of variance explained to be retained. We do so using the following function:
def get_pca_components(pca, var): cumm_var = pca.explained_variance_ratio_ total_var = 0. N_COMPONENTS = 0 for i in cumm_var: N_COMPONENTS += 1 total_var += i if total_var >= var: break return N_COMPONENTS
Here, cumm_var contains the proportions of variance explained by each component, from the largest to the smallest (n-th component). Next, we fit the PCA() object to the data X and extract the number of components such that 95% of the variance is retained:
pca = PCA().fit(X)n_components = get_pca_components(pca, 0.95)
Finally, we can transform the data to reduce its dimensions:
pca = PCA(n_components=n_components)X_d = pca.fit_transform(X)
Luckily for us, Scikit-learn has made life for us much simpler. We only need two lines of code:
pca = PCA(n_components=0.95)X_d = pca.fit_transform(X)
In the PCA() object, you can specify n_components to be a floating point between 0 and 1, to specify the ratio of variance to be preserved. You could also specify the number of components as a positive integer up to d, should you wish to approach the dimensionality reduction that way.
Now that you have obtained the transformed data X_d, you can proceed to analyze/visualize it and fit a ML model on it!
|
[
{
"code": null,
"e": 108,
"s": 46,
"text": "Existing knowledge of linear algebra and matrix factorization"
},
{
"code": null,
"e": 141,
"s": 108,
"text": "Python 3 programming proficiency"
},
{
"code": null,
"e": 376,
"s": 141,
"text": "In a nutshell, PCA is arguably the most popular dimensionality reduction algorithm for datasets with a large number of features. It serves to remove highly correlated features and redundant ones, and also trims away noise in the data."
},
{
"code": null,
"e": 1033,
"s": 376,
"text": "Recent machine learning (ML) algorithms and neural networks work well with datasets of high dimensions, often times with hundreds of thousands or over a million features. Note that due to recent advancements in compute technology (PCs/GPUs), it has been increasingly efficient to deal with high-dimensional data without the need to reduce their dimensions for use due to compute constraints. However, dimensionality reduction algorithms like PCA are still used for various considerations, such as reducing overfitting of the ML model by eliminating features with high correlation, by creating new uncorrelated variables that successively maximize variance."
},
{
"code": null,
"e": 1197,
"s": 1033,
"text": "Recall from literature that we can obtain the principal components matrix V via Singular Value Decomposition (SVD), a matrix factorization technique. Here, we have"
},
{
"code": null,
"e": 1242,
"s": 1197,
"text": "where there are n principal components in V."
},
{
"code": null,
"e": 1312,
"s": 1242,
"text": "In other words, SVD decomposes the data matrix X into three matrices:"
},
{
"code": null,
"e": 1509,
"s": 1312,
"text": "where U comprises of the left singular vectors, Σ is a diagonal matrix with the same dimensions as X containing the singular values, and V contains the right singular vectors/principal components."
},
{
"code": null,
"e": 1599,
"s": 1509,
"text": "In Python, we utilize Numpy’s svd() function to obtain all the principal components of X:"
},
{
"code": null,
"e": 1763,
"s": 1599,
"text": "U, S, V_T = np.linalg.svd(X)# transpose to get V, with number of components as V.shape[1]V = V_T.T# first componentc1 = V[:, 0]# last (n-th) componentcn = V[:, -1]"
},
{
"code": null,
"e": 2171,
"s": 1763,
"text": "Now, we are ready to reduce the dimensions of X using the components found! To reduce the dimension to d, we have to project the data onto the hyperplane defined by the first d components. Doing so results in the hyperplane preserving as much of the variance as possible. Mathematically, we compute the multiplication of X by the matrix W, which is the matrix comprising of the first d principal components:"
},
{
"code": null,
"e": 2205,
"s": 2171,
"text": "In Python, we have the following:"
},
{
"code": null,
"e": 2265,
"s": 2205,
"text": "W = V[:, :d] # d is the number of componentsX_d = X.dot(W) "
},
{
"code": null,
"e": 2540,
"s": 2265,
"text": "Fortunately for us, the Scikit-learn Python library has all this set up for us. Suppose that we have defined d and X previously. We can then use the following code to obtain the resulting X matrix after dimensionality reduction by utilizing the first d principal components:"
},
{
"code": null,
"e": 2631,
"s": 2540,
"text": "from sklearn.decomposition import PCApca = PCA(n_components = d)X_d = pca.fit_transform(X)"
},
{
"code": null,
"e": 2735,
"s": 2631,
"text": "To access the individual components, it is slightly different. We have to use the components_ variable:"
},
{
"code": null,
"e": 2781,
"s": 2735,
"text": "# first componentc1 = pca.components_.T[:, 0]"
},
{
"code": null,
"e": 2900,
"s": 2781,
"text": "A side remark here is that the components are horizontal vectors, so you’ll have to transpose them with a .T as above."
},
{
"code": null,
"e": 3299,
"s": 2900,
"text": "A common practice is to choose a number of dimensions that add up to a sufficiently large portion of the variance. Usually, a convention will be to retain 95% of the variance, but that depends on your needs. For example, if you seek to reduce the dimensions to visualize the data better, you will have to reduce it to 2 or at most 3 dimensions as humans cannot read more than 3 dimensions visually."
},
{
"code": null,
"e": 3531,
"s": 3299,
"text": "In this approach, we iterate through the proportions of variance explained by the components until a certain threshold is reached — the desired proportion of variance explained to be retained. We do so using the following function:"
},
{
"code": null,
"e": 3784,
"s": 3531,
"text": "def get_pca_components(pca, var): cumm_var = pca.explained_variance_ratio_ total_var = 0. N_COMPONENTS = 0 for i in cumm_var: N_COMPONENTS += 1 total_var += i if total_var >= var: break return N_COMPONENTS"
},
{
"code": null,
"e": 4040,
"s": 3784,
"text": "Here, cumm_var contains the proportions of variance explained by each component, from the largest to the smallest (n-th component). Next, we fit the PCA() object to the data X and extract the number of components such that 95% of the variance is retained:"
},
{
"code": null,
"e": 4103,
"s": 4040,
"text": "pca = PCA().fit(X)n_components = get_pca_components(pca, 0.95)"
},
{
"code": null,
"e": 4164,
"s": 4103,
"text": "Finally, we can transform the data to reduce its dimensions:"
},
{
"code": null,
"e": 4227,
"s": 4164,
"text": "pca = PCA(n_components=n_components)X_d = pca.fit_transform(X)"
},
{
"code": null,
"e": 4323,
"s": 4227,
"text": "Luckily for us, Scikit-learn has made life for us much simpler. We only need two lines of code:"
},
{
"code": null,
"e": 4378,
"s": 4323,
"text": "pca = PCA(n_components=0.95)X_d = pca.fit_transform(X)"
},
{
"code": null,
"e": 4664,
"s": 4378,
"text": "In the PCA() object, you can specify n_components to be a floating point between 0 and 1, to specify the ratio of variance to be preserved. You could also specify the number of components as a positive integer up to d, should you wish to approach the dimensionality reduction that way."
}
] |
How to remove an element from an array in Java
|
Following example shows how to remove an element from array.
import java.util.ArrayList; public class Main {
public static void main(String[] args) {
ArrayList objArray = new ArrayList();
objArray.clear();
objArray.add(0,"0th element");
objArray.add(1,"1st element");
objArray.add(2,"2nd element");
System.out.println("Array before removing an element"+objArray);
objArray.remove(1);
objArray.remove("0th element");
System.out.println("Array after removing an element"+objArray);
}
}
The above code sample will produce the following result.
Array before removing an element[0th element, 1st element, 2nd element]
Array after removing an element[2nd element]
|
[
{
"code": null,
"e": 1124,
"s": 1062,
"text": "Following example shows how to remove an element from array. "
},
{
"code": null,
"e": 1607,
"s": 1124,
"text": "import java.util.ArrayList; public class Main {\n public static void main(String[] args) {\n ArrayList objArray = new ArrayList();\n objArray.clear();\n objArray.add(0,\"0th element\");\n objArray.add(1,\"1st element\");\n objArray.add(2,\"2nd element\");\n System.out.println(\"Array before removing an element\"+objArray);\n objArray.remove(1);\n objArray.remove(\"0th element\");\n System.out.println(\"Array after removing an element\"+objArray);\n }\n}"
},
{
"code": null,
"e": 1665,
"s": 1607,
"text": "The above code sample will produce the following result. "
},
{
"code": null,
"e": 1782,
"s": 1665,
"text": "Array before removing an element[0th element, 1st element, 2nd element]\nArray after removing an element[2nd element]"
}
] |
ASIN(), ACOS() and ATAN() Function in MariaDB - GeeksforGeeks
|
01 Oct, 2020
1. ASIN Function :In MariaDB, the ASIN function is used for finding arc sine of a number. In this function, a number will be passed as a parameter and this function will return the arcsine of that number. The function will return valid output only if the number is in the range of -1 to 1, otherwise, it will return NULL as output.
Syntax :
ASIN(number)
Parameter : Required. A numeric value.number : A number used to calculate the arcsine. The range of number must in the range -1 to 1.
Example-1 :
SELECT ASIN(1);
Output :
1.5707963267948966
Example-2 :
SELECT ASIN(2.3);
Output :
NULL
Example-3 :
SELECT ASIN(0.41);
Output :
0.42245406218675574
2. ACOS Function :In MariaDB, the ACOS function is used for finding arc cosine of a number. In this function, a number will be passed as a parameter and this function will return the arc cosine of that number. The function will return valid output only if the number is in the range of -1 to 1, otherwise, it will return NULL as output.
Syntax :
ACOS(number)
Parameter : Required. A numeric value.number : A number used to calculate the arc cosine. The range of number must in the range -1 to 1.
Example-1 :
SELECT ACOS(-0.6);
Output :
2.214297435588181
Example-2 :
SELECT ACOS(1);
Output :
0
Example-3 :
SELECT ACOS(1.9);
Output :
NULL
3. ATAN Function :In MariaDB, the ATAN function is used for finding arc tangent of a number or arc tangent of n and m. In this function, a number will be passed as a parameter or n and m will be passed for the second type of syntax. this function will return the arc tangent of that number. When the second type of syntax is used then the sign of m, n is used for deciding the quadrant for the result.
Syntax-1 :
ATAN(number)
Parameter : Required. A numeric value.number : A number used to calculate the arc tangent.
Syntax-2 :
ATAN(n, m)
Parameters : Required. Two numeric values.n, m : Two values used to calculate the arc tangent.
Example-1 :
SELECT ATAN(-1.4);
Output :
-0.9505468408120751
Example-2 :
SELECT ATAN(1, 3);
Output :
0.3217505543966422
Example-3 :
SELECT ATAN(0.6);
Output :
0.5404195002705842
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
Introduction of Relational Algebra in DBMS
What is Temporary Table in SQL?
Two Phase Locking Protocol
KDD Process in Data Mining
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
MySQL | Group_CONCAT() Function
|
[
{
"code": null,
"e": 24304,
"s": 24276,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 24636,
"s": 24304,
"text": "1. ASIN Function :In MariaDB, the ASIN function is used for finding arc sine of a number. In this function, a number will be passed as a parameter and this function will return the arcsine of that number. The function will return valid output only if the number is in the range of -1 to 1, otherwise, it will return NULL as output."
},
{
"code": null,
"e": 24645,
"s": 24636,
"text": "Syntax :"
},
{
"code": null,
"e": 24658,
"s": 24645,
"text": "ASIN(number)"
},
{
"code": null,
"e": 24792,
"s": 24658,
"text": "Parameter : Required. A numeric value.number : A number used to calculate the arcsine. The range of number must in the range -1 to 1."
},
{
"code": null,
"e": 24804,
"s": 24792,
"text": "Example-1 :"
},
{
"code": null,
"e": 24820,
"s": 24804,
"text": "SELECT ASIN(1);"
},
{
"code": null,
"e": 24829,
"s": 24820,
"text": "Output :"
},
{
"code": null,
"e": 24848,
"s": 24829,
"text": "1.5707963267948966"
},
{
"code": null,
"e": 24860,
"s": 24848,
"text": "Example-2 :"
},
{
"code": null,
"e": 24878,
"s": 24860,
"text": "SELECT ASIN(2.3);"
},
{
"code": null,
"e": 24887,
"s": 24878,
"text": "Output :"
},
{
"code": null,
"e": 24892,
"s": 24887,
"text": "NULL"
},
{
"code": null,
"e": 24904,
"s": 24892,
"text": "Example-3 :"
},
{
"code": null,
"e": 24923,
"s": 24904,
"text": "SELECT ASIN(0.41);"
},
{
"code": null,
"e": 24932,
"s": 24923,
"text": "Output :"
},
{
"code": null,
"e": 24952,
"s": 24932,
"text": "0.42245406218675574"
},
{
"code": null,
"e": 25289,
"s": 24952,
"text": "2. ACOS Function :In MariaDB, the ACOS function is used for finding arc cosine of a number. In this function, a number will be passed as a parameter and this function will return the arc cosine of that number. The function will return valid output only if the number is in the range of -1 to 1, otherwise, it will return NULL as output."
},
{
"code": null,
"e": 25298,
"s": 25289,
"text": "Syntax :"
},
{
"code": null,
"e": 25311,
"s": 25298,
"text": "ACOS(number)"
},
{
"code": null,
"e": 25448,
"s": 25311,
"text": "Parameter : Required. A numeric value.number : A number used to calculate the arc cosine. The range of number must in the range -1 to 1."
},
{
"code": null,
"e": 25460,
"s": 25448,
"text": "Example-1 :"
},
{
"code": null,
"e": 25479,
"s": 25460,
"text": "SELECT ACOS(-0.6);"
},
{
"code": null,
"e": 25488,
"s": 25479,
"text": "Output :"
},
{
"code": null,
"e": 25506,
"s": 25488,
"text": "2.214297435588181"
},
{
"code": null,
"e": 25518,
"s": 25506,
"text": "Example-2 :"
},
{
"code": null,
"e": 25534,
"s": 25518,
"text": "SELECT ACOS(1);"
},
{
"code": null,
"e": 25543,
"s": 25534,
"text": "Output :"
},
{
"code": null,
"e": 25545,
"s": 25543,
"text": "0"
},
{
"code": null,
"e": 25557,
"s": 25545,
"text": "Example-3 :"
},
{
"code": null,
"e": 25575,
"s": 25557,
"text": "SELECT ACOS(1.9);"
},
{
"code": null,
"e": 25584,
"s": 25575,
"text": "Output :"
},
{
"code": null,
"e": 25589,
"s": 25584,
"text": "NULL"
},
{
"code": null,
"e": 25991,
"s": 25589,
"text": "3. ATAN Function :In MariaDB, the ATAN function is used for finding arc tangent of a number or arc tangent of n and m. In this function, a number will be passed as a parameter or n and m will be passed for the second type of syntax. this function will return the arc tangent of that number. When the second type of syntax is used then the sign of m, n is used for deciding the quadrant for the result."
},
{
"code": null,
"e": 26002,
"s": 25991,
"text": "Syntax-1 :"
},
{
"code": null,
"e": 26015,
"s": 26002,
"text": "ATAN(number)"
},
{
"code": null,
"e": 26106,
"s": 26015,
"text": "Parameter : Required. A numeric value.number : A number used to calculate the arc tangent."
},
{
"code": null,
"e": 26117,
"s": 26106,
"text": "Syntax-2 :"
},
{
"code": null,
"e": 26128,
"s": 26117,
"text": "ATAN(n, m)"
},
{
"code": null,
"e": 26223,
"s": 26128,
"text": "Parameters : Required. Two numeric values.n, m : Two values used to calculate the arc tangent."
},
{
"code": null,
"e": 26235,
"s": 26223,
"text": "Example-1 :"
},
{
"code": null,
"e": 26254,
"s": 26235,
"text": "SELECT ATAN(-1.4);"
},
{
"code": null,
"e": 26263,
"s": 26254,
"text": "Output :"
},
{
"code": null,
"e": 26283,
"s": 26263,
"text": "-0.9505468408120751"
},
{
"code": null,
"e": 26295,
"s": 26283,
"text": "Example-2 :"
},
{
"code": null,
"e": 26314,
"s": 26295,
"text": "SELECT ATAN(1, 3);"
},
{
"code": null,
"e": 26323,
"s": 26314,
"text": "Output :"
},
{
"code": null,
"e": 26342,
"s": 26323,
"text": "0.3217505543966422"
},
{
"code": null,
"e": 26354,
"s": 26342,
"text": "Example-3 :"
},
{
"code": null,
"e": 26372,
"s": 26354,
"text": "SELECT ATAN(0.6);"
},
{
"code": null,
"e": 26381,
"s": 26372,
"text": "Output :"
},
{
"code": null,
"e": 26400,
"s": 26381,
"text": "0.5404195002705842"
},
{
"code": null,
"e": 26405,
"s": 26400,
"text": "DBMS"
},
{
"code": null,
"e": 26409,
"s": 26405,
"text": "SQL"
},
{
"code": null,
"e": 26414,
"s": 26409,
"text": "DBMS"
},
{
"code": null,
"e": 26418,
"s": 26414,
"text": "SQL"
},
{
"code": null,
"e": 26516,
"s": 26418,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26557,
"s": 26516,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 26600,
"s": 26557,
"text": "Introduction of Relational Algebra in DBMS"
},
{
"code": null,
"e": 26632,
"s": 26600,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 26659,
"s": 26632,
"text": "Two Phase Locking Protocol"
},
{
"code": null,
"e": 26686,
"s": 26659,
"text": "KDD Process in Data Mining"
},
{
"code": null,
"e": 26728,
"s": 26686,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 26772,
"s": 26728,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 26793,
"s": 26772,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 26859,
"s": 26793,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
}
] |
Sentiment Analysis through LSTMs. Build your own model in less than 50... | by Rohith Gandhi | Towards Data Science
|
Language bonds humans together. Language acts as a tool for us to convey our thoughts and feelings to another person and with the help of the same tool we are able to understand their thoughts and feelings as well. Most of us start talking from around 18 months old to 2 years. It is not yet completely understood how the human brain is able to grasp such vast amounts of knowledge at such a tender age. But, it has been found that most of the language processing functions happen within the cerebral cortex of the brain.
Humans ourselves are not able to understand how exactly language is processed by our brains. So, is it possible for us to teach a machine to learn our language?? Yes, through extensive research, a lot of methods have been developed that could help machines understand our languages. NLP or Natural Language Processing is the field of study that focuses on the interactions between human language and computers. One subproblem of NLP is sentiment analysis, i.e classifying a statement as positive or negative. What is the use of classifying a statement as positive or negative?? Let’s take an example of Amazon website. On Amazon, it’s users can leave a comment about a product stating whether it was good, bad or it could even be neutral. Now, using a human to read all the comments and obtaining the overall customer feedback on the product would be expensive and time-consuming. Enter our machine learning model. The machine learning model can churn through a vast amount of data, making inferences and classifying the comment. Using this ML model, Amazon can better its products through the customer reviews which would bring in more revenue for the company.
Sentiment analysis isn’t as straightforward as it may seem. If you think that the comments which contain the words “good”, “awesome”, etc can be classified as a positive comment and the comments which the words “bad”, “miserable” etc can be classified as a negative comment, think again. E.x: “Completely lacking in good taste” and “Good for a quick meal but nothing special” represent a negative and neutral feedback respectively even though they have the word “good” in them. Therefore, as I mentioned the task may not be as easy as it may seem. Let’s move on to the data we will be working with.
We are going to look at comments from Amazon products reviews, IMDB movie criticisms and Yelp reviews to build our sentiment analysis model. The data can be downloaded from this link. All the data has been annotated, 0 represents a negative feedback and 1 represents a positive feedback. A few lines of the Amazon data looks similar to the below image.
Let’s write some code!
The data is present in different text files. We open each of this file and read all the lines of text which also includes the labels for each text. We then store them in a list called “lines”.
At each line in the dataset, we have the text and four character spaces after, we have the label for that text(0 or 1). Therefore, we take the first part which has the text and add it to our features(x) and then we take the label, which has ‘\n’ at the end. So, its removed and then added to our list of labels(y).
Keras has a built-in API that makes preparing text for computation easier. The Tokenizer class has 4 attributes which you can use to prepare your features. Take a look at the example below to understand what tokenizer actually does.
## CODEtokenizer = Tokenizer()texts = ["The sun is shining in June!","September is grey.","Life is beautiful in August.","I like it","This and other things?"]tokenizer.fit_on_texts(texts)print(tokenizer.word_index)tokenizer.texts_to_sequences(["June is beautiful and I like it!"])## OUPUT{'sun': 3, 'september': 4, 'june': 5, 'other': 6, 'the': 7, 'and': 8, 'like': 9, 'in': 2, 'beautiful': 11, 'grey': 12, 'life': 17, 'it': 16, 'i': 14, 'is': 1, 'august': 15, 'things': 10, 'shining': 13, 'this': 18}[[5, 1, 11, 8, 14, 9, 16]]
Tokenizer assigns index values to each word in the sentence and a new sentence can represented using this index values. Since the text corpus we are using contains a huge number of different words, we set a upper bound and use only the most recurring 2500 words.
We now convert the text into these number sequences as shown above and pad the sequence of numbers. Since sentences can be of different length, their sequence length will also be different. Therefore, pad_sequences finds the longest sentence and pads all other statements with 0 to match that length.
## Pad Sequences Examplepad_sequences([[1, 2, 3], [3, 4, 5, 6], [7, 8]])array([[0, 1, 2, 3], [3, 4, 5, 6], [0, 0, 7, 8]], dtype=int32)
We convert the labels into one hot encoding. This helps the LSTM network in predicting the label for the text. Now, we have prepared our text data, we can split it into training and test samples. 80% of the data is used for training and 20% is kept aside for testing the model.
We now build the model, compile it, train it and test it. The model has an embedding layer. The input sequences are sparse representations of the text because the vocabulary would be huge and a given word would be represented by a large vector. It would be easier for the network to predict if we are able to build some dense representation of the sequence. The word embeddings/dense representation for the 2500 words are derived from training the model by the embedding layer. We then add LSTM and Dense layers to the model. The LSTM cell is responsible for making contextual inferences and aids in predicting whether a sentence is positive or not. The Dense layer outputs the probabilities for each class. I have not given much detail on LSTMs. To know more about them, please refer this blog.
You have just build a sentiment classifier under 50 lines of code.
|
[
{
"code": null,
"e": 569,
"s": 47,
"text": "Language bonds humans together. Language acts as a tool for us to convey our thoughts and feelings to another person and with the help of the same tool we are able to understand their thoughts and feelings as well. Most of us start talking from around 18 months old to 2 years. It is not yet completely understood how the human brain is able to grasp such vast amounts of knowledge at such a tender age. But, it has been found that most of the language processing functions happen within the cerebral cortex of the brain."
},
{
"code": null,
"e": 1731,
"s": 569,
"text": "Humans ourselves are not able to understand how exactly language is processed by our brains. So, is it possible for us to teach a machine to learn our language?? Yes, through extensive research, a lot of methods have been developed that could help machines understand our languages. NLP or Natural Language Processing is the field of study that focuses on the interactions between human language and computers. One subproblem of NLP is sentiment analysis, i.e classifying a statement as positive or negative. What is the use of classifying a statement as positive or negative?? Let’s take an example of Amazon website. On Amazon, it’s users can leave a comment about a product stating whether it was good, bad or it could even be neutral. Now, using a human to read all the comments and obtaining the overall customer feedback on the product would be expensive and time-consuming. Enter our machine learning model. The machine learning model can churn through a vast amount of data, making inferences and classifying the comment. Using this ML model, Amazon can better its products through the customer reviews which would bring in more revenue for the company."
},
{
"code": null,
"e": 2330,
"s": 1731,
"text": "Sentiment analysis isn’t as straightforward as it may seem. If you think that the comments which contain the words “good”, “awesome”, etc can be classified as a positive comment and the comments which the words “bad”, “miserable” etc can be classified as a negative comment, think again. E.x: “Completely lacking in good taste” and “Good for a quick meal but nothing special” represent a negative and neutral feedback respectively even though they have the word “good” in them. Therefore, as I mentioned the task may not be as easy as it may seem. Let’s move on to the data we will be working with."
},
{
"code": null,
"e": 2683,
"s": 2330,
"text": "We are going to look at comments from Amazon products reviews, IMDB movie criticisms and Yelp reviews to build our sentiment analysis model. The data can be downloaded from this link. All the data has been annotated, 0 represents a negative feedback and 1 represents a positive feedback. A few lines of the Amazon data looks similar to the below image."
},
{
"code": null,
"e": 2706,
"s": 2683,
"text": "Let’s write some code!"
},
{
"code": null,
"e": 2899,
"s": 2706,
"text": "The data is present in different text files. We open each of this file and read all the lines of text which also includes the labels for each text. We then store them in a list called “lines”."
},
{
"code": null,
"e": 3214,
"s": 2899,
"text": "At each line in the dataset, we have the text and four character spaces after, we have the label for that text(0 or 1). Therefore, we take the first part which has the text and add it to our features(x) and then we take the label, which has ‘\\n’ at the end. So, its removed and then added to our list of labels(y)."
},
{
"code": null,
"e": 3447,
"s": 3214,
"text": "Keras has a built-in API that makes preparing text for computation easier. The Tokenizer class has 4 attributes which you can use to prepare your features. Take a look at the example below to understand what tokenizer actually does."
},
{
"code": null,
"e": 3975,
"s": 3447,
"text": "## CODEtokenizer = Tokenizer()texts = [\"The sun is shining in June!\",\"September is grey.\",\"Life is beautiful in August.\",\"I like it\",\"This and other things?\"]tokenizer.fit_on_texts(texts)print(tokenizer.word_index)tokenizer.texts_to_sequences([\"June is beautiful and I like it!\"])## OUPUT{'sun': 3, 'september': 4, 'june': 5, 'other': 6, 'the': 7, 'and': 8, 'like': 9, 'in': 2, 'beautiful': 11, 'grey': 12, 'life': 17, 'it': 16, 'i': 14, 'is': 1, 'august': 15, 'things': 10, 'shining': 13, 'this': 18}[[5, 1, 11, 8, 14, 9, 16]]"
},
{
"code": null,
"e": 4238,
"s": 3975,
"text": "Tokenizer assigns index values to each word in the sentence and a new sentence can represented using this index values. Since the text corpus we are using contains a huge number of different words, we set a upper bound and use only the most recurring 2500 words."
},
{
"code": null,
"e": 4539,
"s": 4238,
"text": "We now convert the text into these number sequences as shown above and pad the sequence of numbers. Since sentences can be of different length, their sequence length will also be different. Therefore, pad_sequences finds the longest sentence and pads all other statements with 0 to match that length."
},
{
"code": null,
"e": 4686,
"s": 4539,
"text": "## Pad Sequences Examplepad_sequences([[1, 2, 3], [3, 4, 5, 6], [7, 8]])array([[0, 1, 2, 3], [3, 4, 5, 6], [0, 0, 7, 8]], dtype=int32)"
},
{
"code": null,
"e": 4964,
"s": 4686,
"text": "We convert the labels into one hot encoding. This helps the LSTM network in predicting the label for the text. Now, we have prepared our text data, we can split it into training and test samples. 80% of the data is used for training and 20% is kept aside for testing the model."
},
{
"code": null,
"e": 5760,
"s": 4964,
"text": "We now build the model, compile it, train it and test it. The model has an embedding layer. The input sequences are sparse representations of the text because the vocabulary would be huge and a given word would be represented by a large vector. It would be easier for the network to predict if we are able to build some dense representation of the sequence. The word embeddings/dense representation for the 2500 words are derived from training the model by the embedding layer. We then add LSTM and Dense layers to the model. The LSTM cell is responsible for making contextual inferences and aids in predicting whether a sentence is positive or not. The Dense layer outputs the probabilities for each class. I have not given much detail on LSTMs. To know more about them, please refer this blog."
}
] |
ML | Kolmogorov-Smirnov Test - GeeksforGeeks
|
17 Jan, 2022
Kolmogorov–Smirnov test a very efficient way to determine if two samples are significantly different from each other. It is usually used to check the uniformity of random numbers. Uniformity is one of the most important properties of any random number generator and Kolmogorov–Smirnov test can be used to test it. The Kolmogorov–Smirnov test may also be used to test whether two underlying one-dimensional probability distributions differ. It is a very efficient way to determine if two samples are significantly different from each other.
The Kolmogorov–Smirnov statistic quantifies a distance between the empirical distribution function of the sample and the cumulative distribution function of the reference distribution, or between the empirical distribution functions of two samples.
To use the test for checking the uniformity of random numbers, we use the CDF (Cumulative distribution function) of U[0, 1].
F(x)=x for 0<=x<=1
Empirical CDF, Sn(x)= (number of R1, R2...Rn < x) / N array of random numbers, the random numbers must be in the range of [0, 1].
H0(Null Hypothesis): Null hypothesis assumes that the numbers are uniformly distributed between 0-1. If we are able to reject the Null Hypothesis, this means that the numbers are not uniformly distributed between 0-1. Failure to reject the Null Hypothesis although does not necessarily mean that the numbers follow the uniform distribution.
Parameters:
Statistics: This is the calculated value of D, where D=|F(x)-Sn(x)|. -> This D is compared with Dalpha where alpha is the level of significance. Alpha is defined as the probability of rejecting the null hypothesis given the null hypothesis(H0) is true. For most of the practical applications, alpha is chosen as 0.05. p-value: This is calculated with the help of D. -> If pvalue> alpha, we fail to reject the null hypothesis. Otherwise, we conclude that the numbers are not uniform. Ideally, the p-value should be as large as possible. For perfect uniform distribution pvalue=1 and Statistics=0.
Python3
from scipy.stats import kstestimport random # N = int(input("Enter number of random numbers: "))N = 5 actual =[]print("Enter outcomes: ")for i in range(N): # x = float(input("Outcomes of class "+str(i + 1)+": ")) actual.append(random.random()) print(actual)x = kstest(actual, "uniform") print(x)
Output:
KS Test is a very powerful way to automatically differentiate samples from a different distribution. kstest function may also be used to check whether the data given follows Normal Distribution or not. It compares the observed versus the expected cumulative relative frequencies of the Normal Distribution. The Kolmogorov-Smirnov test uses the maximal absolute difference between the observed and expected cumulative distribution.
The Null hypothesis used here assumes that the numbers follow the normal distribution.
The functioning of the function remains exactly same. Again it returns statistics and p-value. If the p-value is < alpha, we reject the Null hypothesis.
Python3
from scipy.stats import kstestimport random # N = int(input("Enter number of random numbers: "))N = 10 actual =[]print("Enter outcomes: ") for i in range(N): # x = float(input("Outcomes of class "+str(i + 1)+": ")) actual.append(random.random()) print(actual)x = kstest(actual, "norm") print(x)
Output:
surinderdawra388
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree
Reinforcement learning
Decision Tree Introduction with example
Activation functions in Neural Networks
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": 25655,
"s": 25627,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 26197,
"s": 25655,
"text": "Kolmogorov–Smirnov test a very efficient way to determine if two samples are significantly different from each other. It is usually used to check the uniformity of random numbers. Uniformity is one of the most important properties of any random number generator and Kolmogorov–Smirnov test can be used to test it. The Kolmogorov–Smirnov test may also be used to test whether two underlying one-dimensional probability distributions differ. It is a very efficient way to determine if two samples are significantly different from each other. "
},
{
"code": null,
"e": 26446,
"s": 26197,
"text": "The Kolmogorov–Smirnov statistic quantifies a distance between the empirical distribution function of the sample and the cumulative distribution function of the reference distribution, or between the empirical distribution functions of two samples."
},
{
"code": null,
"e": 26573,
"s": 26446,
"text": "To use the test for checking the uniformity of random numbers, we use the CDF (Cumulative distribution function) of U[0, 1]. "
},
{
"code": null,
"e": 26594,
"s": 26573,
"text": "F(x)=x for 0<=x<=1 "
},
{
"code": null,
"e": 26725,
"s": 26594,
"text": "Empirical CDF, Sn(x)= (number of R1, R2...Rn < x) / N array of random numbers, the random numbers must be in the range of [0, 1]. "
},
{
"code": null,
"e": 27070,
"s": 26725,
"text": "H0(Null Hypothesis): Null hypothesis assumes that the numbers are uniformly distributed between 0-1. If we are able to reject the Null Hypothesis, this means that the numbers are not uniformly distributed between 0-1. Failure to reject the Null Hypothesis although does not necessarily mean that the numbers follow the uniform distribution. "
},
{
"code": null,
"e": 27083,
"s": 27070,
"text": "Parameters: "
},
{
"code": null,
"e": 27679,
"s": 27083,
"text": "Statistics: This is the calculated value of D, where D=|F(x)-Sn(x)|. -> This D is compared with Dalpha where alpha is the level of significance. Alpha is defined as the probability of rejecting the null hypothesis given the null hypothesis(H0) is true. For most of the practical applications, alpha is chosen as 0.05. p-value: This is calculated with the help of D. -> If pvalue> alpha, we fail to reject the null hypothesis. Otherwise, we conclude that the numbers are not uniform. Ideally, the p-value should be as large as possible. For perfect uniform distribution pvalue=1 and Statistics=0."
},
{
"code": null,
"e": 27689,
"s": 27681,
"text": "Python3"
},
{
"code": "from scipy.stats import kstestimport random # N = int(input(\"Enter number of random numbers: \"))N = 5 actual =[]print(\"Enter outcomes: \")for i in range(N): # x = float(input(\"Outcomes of class \"+str(i + 1)+\": \")) actual.append(random.random()) print(actual)x = kstest(actual, \"uniform\") print(x)",
"e": 27992,
"s": 27689,
"text": null
},
{
"code": null,
"e": 28002,
"s": 27992,
"text": "Output: "
},
{
"code": null,
"e": 28436,
"s": 28002,
"text": " KS Test is a very powerful way to automatically differentiate samples from a different distribution. kstest function may also be used to check whether the data given follows Normal Distribution or not. It compares the observed versus the expected cumulative relative frequencies of the Normal Distribution. The Kolmogorov-Smirnov test uses the maximal absolute difference between the observed and expected cumulative distribution. "
},
{
"code": null,
"e": 28523,
"s": 28436,
"text": "The Null hypothesis used here assumes that the numbers follow the normal distribution."
},
{
"code": null,
"e": 28676,
"s": 28523,
"text": "The functioning of the function remains exactly same. Again it returns statistics and p-value. If the p-value is < alpha, we reject the Null hypothesis."
},
{
"code": null,
"e": 28686,
"s": 28678,
"text": "Python3"
},
{
"code": "from scipy.stats import kstestimport random # N = int(input(\"Enter number of random numbers: \"))N = 10 actual =[]print(\"Enter outcomes: \") for i in range(N): # x = float(input(\"Outcomes of class \"+str(i + 1)+\": \")) actual.append(random.random()) print(actual)x = kstest(actual, \"norm\") print(x)",
"e": 28988,
"s": 28686,
"text": null
},
{
"code": null,
"e": 28998,
"s": 28988,
"text": "Output: "
},
{
"code": null,
"e": 29017,
"s": 29000,
"text": "surinderdawra388"
},
{
"code": null,
"e": 29034,
"s": 29017,
"text": "Machine Learning"
},
{
"code": null,
"e": 29041,
"s": 29034,
"text": "Python"
},
{
"code": null,
"e": 29058,
"s": 29041,
"text": "Machine Learning"
},
{
"code": null,
"e": 29156,
"s": 29058,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29179,
"s": 29156,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 29193,
"s": 29179,
"text": "Decision Tree"
},
{
"code": null,
"e": 29216,
"s": 29193,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 29256,
"s": 29216,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 29296,
"s": 29256,
"text": "Activation functions in Neural Networks"
},
{
"code": null,
"e": 29324,
"s": 29296,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 29374,
"s": 29324,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 29396,
"s": 29374,
"text": "Python map() function"
}
] |
Using styled API in ReactJS - GeeksforGeeks
|
28 Dec, 2020
Styled components in ReactJS is a CSS-in-JS library that can be used for a better UI design. This API allows us to create a styled component and apply all styling properties. For using Styled API in React we need to install styled components.
Prerequisites:
Basics of ReactJS
Already created ReactJS app
Step 1: Before moving further, firstly we have to install the styled component, by running the following command in your project directory, with the help of terminal in your src folder or you can also run this command in Visual Studio Code’s terminal in your project folder.
npm install --save styled-components
Step 2: After installing the modules, now open your App.js file which is present inside your project’s directory, under src folder.
Step 3: Now import React and styled modules.
Step 4: In your App.js file, add this code snippet to import React and styled modules.
import React from 'react';
import styled from 'styled-components';
Below is a sample program to illustrate the use of styled-components:
Example 1: Changing the background color of the button to green.
App.js:
Javascript
import React from 'react'; // Importing styled from styled-componentsimport styled from 'styled-components'; // Importing the background-color of your // choice to the button using css// Button component that will render an <a> // tag with some styles using styled.const Button = styled.a` background-color:green; color: white; padding: 1rem 2rem; margin-top:100px; width: 150px; display: block;`const App = () => { return ( <center><Button>GeeksforGeeks</Button></center> )} export default App;
Output:
Example 2: Adding a border to the button.
App.js:
Javascript
import React from 'react'; // Importing styled from styled componentsimport styled from 'styled-components'; // Importing the background-color of your // choice to the button using css// Button component that will render an <a>// tag with some styles using styled.const Button = styled.a` background-color:green; color: white; padding: 1rem 2rem; margin-top:100px; width: 150px; display: block; border:8px solid black;`const App = () => { return ( <center><Button>GeeksforGeeks</Button></center> )} export default App;
Output:
Hence, using the above-mentioned steps, we can use the Styled-components to import and change the style of components in React.
react-js
Technical Scripter 2020
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
How to create footer to stay at the bottom of a Web page?
|
[
{
"code": null,
"e": 25745,
"s": 25717,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 25988,
"s": 25745,
"text": "Styled components in ReactJS is a CSS-in-JS library that can be used for a better UI design. This API allows us to create a styled component and apply all styling properties. For using Styled API in React we need to install styled components."
},
{
"code": null,
"e": 26003,
"s": 25988,
"text": "Prerequisites:"
},
{
"code": null,
"e": 26021,
"s": 26003,
"text": "Basics of ReactJS"
},
{
"code": null,
"e": 26049,
"s": 26021,
"text": "Already created ReactJS app"
},
{
"code": null,
"e": 26324,
"s": 26049,
"text": "Step 1: Before moving further, firstly we have to install the styled component, by running the following command in your project directory, with the help of terminal in your src folder or you can also run this command in Visual Studio Code’s terminal in your project folder."
},
{
"code": null,
"e": 26361,
"s": 26324,
"text": "npm install --save styled-components"
},
{
"code": null,
"e": 26493,
"s": 26361,
"text": "Step 2: After installing the modules, now open your App.js file which is present inside your project’s directory, under src folder."
},
{
"code": null,
"e": 26538,
"s": 26493,
"text": "Step 3: Now import React and styled modules."
},
{
"code": null,
"e": 26625,
"s": 26538,
"text": "Step 4: In your App.js file, add this code snippet to import React and styled modules."
},
{
"code": null,
"e": 26692,
"s": 26625,
"text": "import React from 'react';\nimport styled from 'styled-components';"
},
{
"code": null,
"e": 26762,
"s": 26692,
"text": "Below is a sample program to illustrate the use of styled-components:"
},
{
"code": null,
"e": 26827,
"s": 26762,
"text": "Example 1: Changing the background color of the button to green."
},
{
"code": null,
"e": 26835,
"s": 26827,
"text": "App.js:"
},
{
"code": null,
"e": 26846,
"s": 26835,
"text": "Javascript"
},
{
"code": "import React from 'react'; // Importing styled from styled-componentsimport styled from 'styled-components'; // Importing the background-color of your // choice to the button using css// Button component that will render an <a> // tag with some styles using styled.const Button = styled.a` background-color:green; color: white; padding: 1rem 2rem; margin-top:100px; width: 150px; display: block;`const App = () => { return ( <center><Button>GeeksforGeeks</Button></center> )} export default App;",
"e": 27356,
"s": 26846,
"text": null
},
{
"code": null,
"e": 27364,
"s": 27356,
"text": "Output:"
},
{
"code": null,
"e": 27406,
"s": 27364,
"text": "Example 2: Adding a border to the button."
},
{
"code": null,
"e": 27414,
"s": 27406,
"text": "App.js:"
},
{
"code": null,
"e": 27425,
"s": 27414,
"text": "Javascript"
},
{
"code": "import React from 'react'; // Importing styled from styled componentsimport styled from 'styled-components'; // Importing the background-color of your // choice to the button using css// Button component that will render an <a>// tag with some styles using styled.const Button = styled.a` background-color:green; color: white; padding: 1rem 2rem; margin-top:100px; width: 150px; display: block; border:8px solid black;`const App = () => { return ( <center><Button>GeeksforGeeks</Button></center> )} export default App;",
"e": 27959,
"s": 27425,
"text": null
},
{
"code": null,
"e": 27967,
"s": 27959,
"text": "Output:"
},
{
"code": null,
"e": 28096,
"s": 27967,
"text": "Hence, using the above-mentioned steps, we can use the Styled-components to import and change the style of components in React. "
},
{
"code": null,
"e": 28105,
"s": 28096,
"text": "react-js"
},
{
"code": null,
"e": 28129,
"s": 28105,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28148,
"s": 28129,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28165,
"s": 28148,
"text": "Web Technologies"
},
{
"code": null,
"e": 28263,
"s": 28165,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28303,
"s": 28263,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28336,
"s": 28303,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28381,
"s": 28336,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28424,
"s": 28381,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28474,
"s": 28424,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 28535,
"s": 28474,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28597,
"s": 28535,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28669,
"s": 28597,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28738,
"s": 28669,
"text": "How to calculate the number of days between two dates in javascript?"
}
] |
Practical SQL: Designing and Creating a Relational Database | by Soner Yıldırım | Towards Data Science
|
SQL is a programming language that is used by most relational database management systems (RDBMS) to manage data stored in tabular form (i.e. tables).
A relational database consists of multiple tables that relate to each other. The relation between tables is formed in the sense of shared columns.
There are many different relational database management systems (e.g. MySQL, PostgreSQL, SQL Server). The SQL syntax they adapt might differ slightly. However, the difference is very small so if you learn how to use one, you can easily switch to another one.
In this post, we will design a simple relational database for a retail business and create it using MySQL.
Below is the schema of the sales database. It contains 4 relational tables. The first line is the name of table. The other lines represent the columns in table.
Customer: Contains customer data and the id of the store that a customer most frequently goes.
Purchase: Contains the details of a purchase (Each item is recorded as a separate purchase in our case)
Item: Contains the item descriptions and prices. This retail business owns a few stores. Although items are sold at all locations, there is an owner store for each item. The “store_id” column in the item table indicates the store that owns the item.
Store: Contains store related information.
You may have noticed the initials “PK” (primary key) and “FK” (foreign key) next to some column names.
Primary key is the column that uniquely identifies each row. It is like the index of a pandas dataframe.
Foreign key is what relates a table to another one. Foreign key contains the primary key of another table. For instance, the “item_id” in the purchase table is a foreign key. It stores the rows from the primary key in the item table.
Foreign keys are fundamental in creating relational tables. Consider a case where we store item descriptions and prices in the purchase table instead of storing them in a separate item table.
If the price of an item changes, we need to change the price for all the rows in the purchase table that contains that item. It is a lot of work. When the item prices are stored in a separate table, we just need to make one update.
Since the purchase table is related to the item table by using the “item_id” as foreign key, we don’t have to worry about updating the purchase table.
The design of the database is set. We can start to build it now. I will be using the terminal to write SQL syntax. There are also other options such as MySQL Workbench.
We first need to connect to the MySQL server from the terminal:
~$ sudo mysql -u root
The next step is to create the sales database and enter it:
mysql> create database sales;mysql> use sales;
We are now in the sales database but it does not contain any table yet. We can start creating the tables.
The first one is the store table because all the other ones have foreign keys that relate to another table. The related tables through foreign keys must be created first.
mysql> CREATE TABLE store( -> store_id INT PRIMARY KEY, -> address VARCHAR(20) NOT NULL, -> manager VARCHAR(20) NOT NULL -> );
The syntax of CREATE TABLE statement consists of the table name and column descriptions in parenthesis. The primary key phrase is used to indicate the primary key column.
Each column description contains the column name and data type. Here are the data types used by SQL:
Int: integer
Decimal(M, N): Floating point number. M is total number of digits, N is the number of decimal digits.
Varchar(N): String (text) of lenght N
Blob: Binary large object
Date: ‘YYYY-MM-DD’
Timestamp: ‘YYYY-MM-DD HH:MM:SS’
We can now create the customer table.
mysql> CREATE TABLE customer( -> cust_id INT PRIMARY KEY, -> f_name VARCHAR(20) NOT NULL, -> l_name VARCHAR(20) NOT NULL, -> gender CHAR(1), -> store_id INT, -> FOREIGN KEY (store_id) REFERENCES store(store_id) -> ON DELETE SET NULL -> );
You may have notices that we used the phrase “NOT NULL” in the description of some columns. It indicates that rows in this column cannot contain any null values (i.e. cannot be empty).
Note: The primary key columns cannot have any null values but we do not need to specify it explicitly by using the “NOT NULL” phrase.
The store_id column in customer table is a foreign key. We first need to create and then set as foreign key.
The foreign key statement also requires to specify the reference table and column names.
ON DELETE statement is used to specify what will happen to the values in the foreign key column when the values they refer to get deleted. For instance, the store_id column in the customer table is a foreign key. It refers to the store_id column in the store table (primary key of the store table). If a store gets deleted from the store table, some values in the customer table are also affected. ON DELETE SET NULL indicates that these values will be replaced with NULL.
We have two more tables to create which are purchase and item tables. Since purchase table contains a foreign key related to the item table, we need to create the item table first.
mysql> CREATE TABLE item( -> item_id INT, -> description VARCHAR(20), -> price DECIMAL(6,2) NOT NULL, -> store_id INT, -> PRIMARY KEY(item_id), -> FOREIGN KEY(store_id) REFERENCES store(store_id) -> ON DELETE SET NULL -> );
As you can see, we can also declare a column as primary key after it is created.
The last table is the purchase table which contains 6 columns and three of them are foreign keys.
mysql> CREATE TABLE purchase( -> purchase_id INT PRIMARY KEY, -> item_qty INT NOT NULL, -> date DATE NOT NULL, -> item_id INT, -> cust_id INT, -> store_id INT, -> FOREIGN KEY(item_id) REFERENCES item(item_id) -> ON DELETE SET NULL, -> FOREIGN KEY(cust_id) REFERENCES customer(cust_id) -> ON DELETE SET NULL, -> FOREIGN KEY(store_id) REFERENCES store(store_id) -> ON DELETE SET NULL -> );
We now have 4 tables in our database. We can check them with SHOW TABLES statement.
mysql> show tables;+-----------------+| Tables_in_sales |+-----------------+| customer || item || purchase || store |+-----------------+
We have successfully created a simple relational database. The structure of table can be viewed using the DESCRIBE statement.
mysql> describe customer;+----------+-------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+----------+-------------+------+-----+---------+-------+| cust_id | int(11) | NO | PRI | NULL | || f_name | varchar(20) | NO | | NULL | || l_name | varchar(20) | NO | | NULL | || gender | char(1) | YES | | NULL | || store_id | int(11) | YES | MUL | NULL | |+----------+-------------+------+-----+---------+-------+5 rows in set (0.11 sec)
The tables do not contain any data now. In the next post, I will explain how to populate these tables with appropriate data and run queries to retrieve data.
The SELECT statement is used to create queries and retrieve data from tables. If you are or plan to be a data scientist, you are likely to use the select statement much more than the other ones.
The queries can be as simple as getting all the data in a table. However, we are more likely to run complex queries to retrieve the data partially. The SELECT statement allows us to create queries based on conditions, relations, and statistical measures.
Thank you for reading. Please let me know if you have any feedback.
|
[
{
"code": null,
"e": 323,
"s": 172,
"text": "SQL is a programming language that is used by most relational database management systems (RDBMS) to manage data stored in tabular form (i.e. tables)."
},
{
"code": null,
"e": 470,
"s": 323,
"text": "A relational database consists of multiple tables that relate to each other. The relation between tables is formed in the sense of shared columns."
},
{
"code": null,
"e": 729,
"s": 470,
"text": "There are many different relational database management systems (e.g. MySQL, PostgreSQL, SQL Server). The SQL syntax they adapt might differ slightly. However, the difference is very small so if you learn how to use one, you can easily switch to another one."
},
{
"code": null,
"e": 836,
"s": 729,
"text": "In this post, we will design a simple relational database for a retail business and create it using MySQL."
},
{
"code": null,
"e": 997,
"s": 836,
"text": "Below is the schema of the sales database. It contains 4 relational tables. The first line is the name of table. The other lines represent the columns in table."
},
{
"code": null,
"e": 1092,
"s": 997,
"text": "Customer: Contains customer data and the id of the store that a customer most frequently goes."
},
{
"code": null,
"e": 1196,
"s": 1092,
"text": "Purchase: Contains the details of a purchase (Each item is recorded as a separate purchase in our case)"
},
{
"code": null,
"e": 1446,
"s": 1196,
"text": "Item: Contains the item descriptions and prices. This retail business owns a few stores. Although items are sold at all locations, there is an owner store for each item. The “store_id” column in the item table indicates the store that owns the item."
},
{
"code": null,
"e": 1489,
"s": 1446,
"text": "Store: Contains store related information."
},
{
"code": null,
"e": 1592,
"s": 1489,
"text": "You may have noticed the initials “PK” (primary key) and “FK” (foreign key) next to some column names."
},
{
"code": null,
"e": 1697,
"s": 1592,
"text": "Primary key is the column that uniquely identifies each row. It is like the index of a pandas dataframe."
},
{
"code": null,
"e": 1931,
"s": 1697,
"text": "Foreign key is what relates a table to another one. Foreign key contains the primary key of another table. For instance, the “item_id” in the purchase table is a foreign key. It stores the rows from the primary key in the item table."
},
{
"code": null,
"e": 2123,
"s": 1931,
"text": "Foreign keys are fundamental in creating relational tables. Consider a case where we store item descriptions and prices in the purchase table instead of storing them in a separate item table."
},
{
"code": null,
"e": 2355,
"s": 2123,
"text": "If the price of an item changes, we need to change the price for all the rows in the purchase table that contains that item. It is a lot of work. When the item prices are stored in a separate table, we just need to make one update."
},
{
"code": null,
"e": 2506,
"s": 2355,
"text": "Since the purchase table is related to the item table by using the “item_id” as foreign key, we don’t have to worry about updating the purchase table."
},
{
"code": null,
"e": 2675,
"s": 2506,
"text": "The design of the database is set. We can start to build it now. I will be using the terminal to write SQL syntax. There are also other options such as MySQL Workbench."
},
{
"code": null,
"e": 2739,
"s": 2675,
"text": "We first need to connect to the MySQL server from the terminal:"
},
{
"code": null,
"e": 2761,
"s": 2739,
"text": "~$ sudo mysql -u root"
},
{
"code": null,
"e": 2821,
"s": 2761,
"text": "The next step is to create the sales database and enter it:"
},
{
"code": null,
"e": 2868,
"s": 2821,
"text": "mysql> create database sales;mysql> use sales;"
},
{
"code": null,
"e": 2974,
"s": 2868,
"text": "We are now in the sales database but it does not contain any table yet. We can start creating the tables."
},
{
"code": null,
"e": 3145,
"s": 2974,
"text": "The first one is the store table because all the other ones have foreign keys that relate to another table. The related tables through foreign keys must be created first."
},
{
"code": null,
"e": 3284,
"s": 3145,
"text": "mysql> CREATE TABLE store( -> store_id INT PRIMARY KEY, -> address VARCHAR(20) NOT NULL, -> manager VARCHAR(20) NOT NULL -> );"
},
{
"code": null,
"e": 3455,
"s": 3284,
"text": "The syntax of CREATE TABLE statement consists of the table name and column descriptions in parenthesis. The primary key phrase is used to indicate the primary key column."
},
{
"code": null,
"e": 3556,
"s": 3455,
"text": "Each column description contains the column name and data type. Here are the data types used by SQL:"
},
{
"code": null,
"e": 3569,
"s": 3556,
"text": "Int: integer"
},
{
"code": null,
"e": 3671,
"s": 3569,
"text": "Decimal(M, N): Floating point number. M is total number of digits, N is the number of decimal digits."
},
{
"code": null,
"e": 3709,
"s": 3671,
"text": "Varchar(N): String (text) of lenght N"
},
{
"code": null,
"e": 3735,
"s": 3709,
"text": "Blob: Binary large object"
},
{
"code": null,
"e": 3754,
"s": 3735,
"text": "Date: ‘YYYY-MM-DD’"
},
{
"code": null,
"e": 3787,
"s": 3754,
"text": "Timestamp: ‘YYYY-MM-DD HH:MM:SS’"
},
{
"code": null,
"e": 3825,
"s": 3787,
"text": "We can now create the customer table."
},
{
"code": null,
"e": 4089,
"s": 3825,
"text": "mysql> CREATE TABLE customer( -> cust_id INT PRIMARY KEY, -> f_name VARCHAR(20) NOT NULL, -> l_name VARCHAR(20) NOT NULL, -> gender CHAR(1), -> store_id INT, -> FOREIGN KEY (store_id) REFERENCES store(store_id) -> ON DELETE SET NULL -> );"
},
{
"code": null,
"e": 4274,
"s": 4089,
"text": "You may have notices that we used the phrase “NOT NULL” in the description of some columns. It indicates that rows in this column cannot contain any null values (i.e. cannot be empty)."
},
{
"code": null,
"e": 4408,
"s": 4274,
"text": "Note: The primary key columns cannot have any null values but we do not need to specify it explicitly by using the “NOT NULL” phrase."
},
{
"code": null,
"e": 4517,
"s": 4408,
"text": "The store_id column in customer table is a foreign key. We first need to create and then set as foreign key."
},
{
"code": null,
"e": 4606,
"s": 4517,
"text": "The foreign key statement also requires to specify the reference table and column names."
},
{
"code": null,
"e": 5079,
"s": 4606,
"text": "ON DELETE statement is used to specify what will happen to the values in the foreign key column when the values they refer to get deleted. For instance, the store_id column in the customer table is a foreign key. It refers to the store_id column in the store table (primary key of the store table). If a store gets deleted from the store table, some values in the customer table are also affected. ON DELETE SET NULL indicates that these values will be replaced with NULL."
},
{
"code": null,
"e": 5260,
"s": 5079,
"text": "We have two more tables to create which are purchase and item tables. Since purchase table contains a foreign key related to the item table, we need to create the item table first."
},
{
"code": null,
"e": 5509,
"s": 5260,
"text": "mysql> CREATE TABLE item( -> item_id INT, -> description VARCHAR(20), -> price DECIMAL(6,2) NOT NULL, -> store_id INT, -> PRIMARY KEY(item_id), -> FOREIGN KEY(store_id) REFERENCES store(store_id) -> ON DELETE SET NULL -> );"
},
{
"code": null,
"e": 5590,
"s": 5509,
"text": "As you can see, we can also declare a column as primary key after it is created."
},
{
"code": null,
"e": 5688,
"s": 5590,
"text": "The last table is the purchase table which contains 6 columns and three of them are foreign keys."
},
{
"code": null,
"e": 6115,
"s": 5688,
"text": "mysql> CREATE TABLE purchase( -> purchase_id INT PRIMARY KEY, -> item_qty INT NOT NULL, -> date DATE NOT NULL, -> item_id INT, -> cust_id INT, -> store_id INT, -> FOREIGN KEY(item_id) REFERENCES item(item_id) -> ON DELETE SET NULL, -> FOREIGN KEY(cust_id) REFERENCES customer(cust_id) -> ON DELETE SET NULL, -> FOREIGN KEY(store_id) REFERENCES store(store_id) -> ON DELETE SET NULL -> );"
},
{
"code": null,
"e": 6199,
"s": 6115,
"text": "We now have 4 tables in our database. We can check them with SHOW TABLES statement."
},
{
"code": null,
"e": 6371,
"s": 6199,
"text": "mysql> show tables;+-----------------+| Tables_in_sales |+-----------------+| customer || item || purchase || store |+-----------------+"
},
{
"code": null,
"e": 6497,
"s": 6371,
"text": "We have successfully created a simple relational database. The structure of table can be viewed using the DESCRIBE statement."
},
{
"code": null,
"e": 7060,
"s": 6497,
"text": "mysql> describe customer;+----------+-------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+----------+-------------+------+-----+---------+-------+| cust_id | int(11) | NO | PRI | NULL | || f_name | varchar(20) | NO | | NULL | || l_name | varchar(20) | NO | | NULL | || gender | char(1) | YES | | NULL | || store_id | int(11) | YES | MUL | NULL | |+----------+-------------+------+-----+---------+-------+5 rows in set (0.11 sec)"
},
{
"code": null,
"e": 7218,
"s": 7060,
"text": "The tables do not contain any data now. In the next post, I will explain how to populate these tables with appropriate data and run queries to retrieve data."
},
{
"code": null,
"e": 7413,
"s": 7218,
"text": "The SELECT statement is used to create queries and retrieve data from tables. If you are or plan to be a data scientist, you are likely to use the select statement much more than the other ones."
},
{
"code": null,
"e": 7668,
"s": 7413,
"text": "The queries can be as simple as getting all the data in a table. However, we are more likely to run complex queries to retrieve the data partially. The SELECT statement allows us to create queries based on conditions, relations, and statistical measures."
}
] |
Style Rules in CSS
|
CSS comprises of style rules interpreted by the browser and then applied to the corresponding elements in your document. A style rule is made of three parts −
Selector - A selector is an HTML tag at which a style will be applied. This could be any tag like <h1> or <table> etc.
Property - A property is a type of attribute of HTML tag. Put simply, all the HTML attributes are converted into CSS properties. They could be color, border etc.
Value - Values assigned to properties. For example, the color property can have value either red or #F1F1F1 etc
You can put CSS Style Rule Syntax as follows:
selector { property: value }
|
[
{
"code": null,
"e": 1221,
"s": 1062,
"text": "CSS comprises of style rules interpreted by the browser and then applied to the corresponding elements in your document. A style rule is made of three parts −"
},
{
"code": null,
"e": 1341,
"s": 1221,
"text": "Selector - A selector is an HTML tag at which a style will be applied. This could be any tag like <h1> or <table> etc."
},
{
"code": null,
"e": 1503,
"s": 1341,
"text": "Property - A property is a type of attribute of HTML tag. Put simply, all the HTML attributes are converted into CSS properties. They could be color, border etc."
},
{
"code": null,
"e": 1615,
"s": 1503,
"text": "Value - Values assigned to properties. For example, the color property can have value either red or #F1F1F1 etc"
},
{
"code": null,
"e": 1661,
"s": 1615,
"text": "You can put CSS Style Rule Syntax as follows:"
},
{
"code": null,
"e": 1690,
"s": 1661,
"text": "selector { property: value }"
}
] |
Convert a string to uppercase in Julia - uppercase() and uppercasefirst() Methods - GeeksforGeeks
|
01 Apr, 2020
The uppercase() is an inbuilt function in julia which is used to return a string with all characters converted to uppercase.
Syntax: uppercase(s::AbstractString)
Parameters:
s::AbstractString: Specified string.
Returns: It returns a string with all characters converted to uppercase.
Example:
# Julia program to illustrate # the use of uppercase() method # Getting a string with all # characters converted to uppercaseprintln(uppercase("gfg"))println(uppercase("geeks"))println(uppercase("geeksforgeeks"))
Output:
GFG
GEEKS
GEEKSFORGEEKS
The uppercasefirst() is an inbuilt function in julia which is used to return a string with first character converted to uppercase.
Syntax: uppercasefirst(s::AbstractString)
Parameters:
s::AbstractString: Specified string.
Returns: It returns a string with first character converted to uppercase.
Example:
# Julia program to illustrate # the use of uppercasefirst() method # Getting a string with first# character converted to uppercaseprintln(uppercasefirst("gfg"))println(uppercasefirst("geeks"))println(uppercasefirst("geeksforgeeks"))
Output:
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Get array dimensions and size of a dimension in Julia - size() Method
Getting the maximum value from a list in Julia - max() Method
Searching in Array for a given element in Julia
Find maximum element along with its index in Julia - findmax() Method
Working with Date and Time in Julia
Working with Excel Files in Julia
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Exception handling in Julia
Functions in Julia
Replacing elements of a collection in Julia - replace() and replace!() Methods
|
[
{
"code": null,
"e": 24464,
"s": 24436,
"text": "\n01 Apr, 2020"
},
{
"code": null,
"e": 24589,
"s": 24464,
"text": "The uppercase() is an inbuilt function in julia which is used to return a string with all characters converted to uppercase."
},
{
"code": null,
"e": 24626,
"s": 24589,
"text": "Syntax: uppercase(s::AbstractString)"
},
{
"code": null,
"e": 24638,
"s": 24626,
"text": "Parameters:"
},
{
"code": null,
"e": 24675,
"s": 24638,
"text": "s::AbstractString: Specified string."
},
{
"code": null,
"e": 24748,
"s": 24675,
"text": "Returns: It returns a string with all characters converted to uppercase."
},
{
"code": null,
"e": 24757,
"s": 24748,
"text": "Example:"
},
{
"code": "# Julia program to illustrate # the use of uppercase() method # Getting a string with all # characters converted to uppercaseprintln(uppercase(\"gfg\"))println(uppercase(\"geeks\"))println(uppercase(\"geeksforgeeks\"))",
"e": 24972,
"s": 24757,
"text": null
},
{
"code": null,
"e": 24980,
"s": 24972,
"text": "Output:"
},
{
"code": null,
"e": 25005,
"s": 24980,
"text": "GFG\nGEEKS\nGEEKSFORGEEKS\n"
},
{
"code": null,
"e": 25136,
"s": 25005,
"text": "The uppercasefirst() is an inbuilt function in julia which is used to return a string with first character converted to uppercase."
},
{
"code": null,
"e": 25178,
"s": 25136,
"text": "Syntax: uppercasefirst(s::AbstractString)"
},
{
"code": null,
"e": 25190,
"s": 25178,
"text": "Parameters:"
},
{
"code": null,
"e": 25227,
"s": 25190,
"text": "s::AbstractString: Specified string."
},
{
"code": null,
"e": 25301,
"s": 25227,
"text": "Returns: It returns a string with first character converted to uppercase."
},
{
"code": null,
"e": 25310,
"s": 25301,
"text": "Example:"
},
{
"code": "# Julia program to illustrate # the use of uppercasefirst() method # Getting a string with first# character converted to uppercaseprintln(uppercasefirst(\"gfg\"))println(uppercasefirst(\"geeks\"))println(uppercasefirst(\"geeksforgeeks\"))",
"e": 25545,
"s": 25310,
"text": null
},
{
"code": null,
"e": 25553,
"s": 25545,
"text": "Output:"
},
{
"code": null,
"e": 25559,
"s": 25553,
"text": "Julia"
},
{
"code": null,
"e": 25657,
"s": 25559,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25666,
"s": 25657,
"text": "Comments"
},
{
"code": null,
"e": 25679,
"s": 25666,
"text": "Old Comments"
},
{
"code": null,
"e": 25749,
"s": 25679,
"text": "Get array dimensions and size of a dimension in Julia - size() Method"
},
{
"code": null,
"e": 25811,
"s": 25749,
"text": "Getting the maximum value from a list in Julia - max() Method"
},
{
"code": null,
"e": 25859,
"s": 25811,
"text": "Searching in Array for a given element in Julia"
},
{
"code": null,
"e": 25929,
"s": 25859,
"text": "Find maximum element along with its index in Julia - findmax() Method"
},
{
"code": null,
"e": 25965,
"s": 25929,
"text": "Working with Date and Time in Julia"
},
{
"code": null,
"e": 25999,
"s": 25965,
"text": "Working with Excel Files in Julia"
},
{
"code": null,
"e": 26072,
"s": 25999,
"text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)"
},
{
"code": null,
"e": 26100,
"s": 26072,
"text": "Exception handling in Julia"
},
{
"code": null,
"e": 26119,
"s": 26100,
"text": "Functions in Julia"
}
] |
Tutorial: Data Wrangling and Mapping in R | by Pres Nichols | Towards Data Science
|
I think I’ve said this before ... but I love maps. Almost everyone uses them, making maps an amazing way of instantly communicating huge amounts of data without worrying about overwhelming your audience.
One of my favorite tools for working with spatial data is R. Apart from being great for data wrangling, its broad user-base means that there are loads of packages that make custom map making super quick and easy.
This tutorial is meant to provide a rough, end-to-end example of using R to manipulate and map data. The goal is to create a map that will illustrate the concentration of residential building ownership throughout the borough of Brooklyn, New York.
We’ll be using a number of data sets from New York City’s OpenData portal, in addition to the recently released Cartography package.
To complete this tutorial, you’ll need the following tools:
R
R Studio or any other IDE
1) Clone the GitHub repository
git clone https://github.com/spnichol/mapping_tutorial.gitcd mapping_tutorial
2) Create a new R script and set your working directory
setwd("/home/you/mapping_tutorial")
3) Install packages and load first two data sets
install.packages(c("cartography", "rgdal", "sp"))#ownership registrations owners <- read.csv("data/owners.csv")#building data bldgs <- read.csv("data/bldg.csv")
The first file is the Multiple Dwelling Registrations, a registry of residential buildings with three units or more. The second is Registration Contacts, which contains information relating to the owners of the buildings from the previous file.
Our goal with this project is to get an idea of the concentration of building ownership in Brooklyn. So, a natural place to start out would be with the ownership file.
Let’s look at a few records to get a sense of what we have.
head(owners)
Your output should look like this:
It looks like we have two ID variables: RegistrationContactID and RegistrationID. The first refers to the individual/company that is listed in that row, while the second refers to a specific building registration that person/entity made.
We also have the CorporationName column, which could provide some insight into who owns what in Brooklyn. Let’s use the aggregate function on RegistrationContactID and CorporationName.
owner_count <- aggregate(RegistrationID ~ RegistrationContactID, data=owners, FUN=length)names(owner_count) <- c("RegistrationContactID", "Building_Count")head(owner_count)nrow(owner_count[owner_count$Building_Count > 2 ,])
Your output should look like this:
Now we have one column with each unique RegistrationContactID and the number of buildings corresponding to it. Besides some odd looking IDs (just messy data), it’s a bit strange that we only have 274 owners with more than two buildings. Let’s try with CorporationName.
owner_count <- aggregate(org_agg <- aggregate(RegistrationID ~ CorporationName, data=owners, FUN=length)names(org_agg) <- c("CorporationName", "Building_Count")head(org_agg)nrow(org_agg[org_agg$Building_Count > 2 ,])
The output:
Yikes. The building count is much better, but those are some nasty typos. Let’s fix them by removing all non-alphanumeric characters and then subsetting to keep only non-empty rows.
org_agg$CorporationName<- gsub("[^[:alnum:][:blank:]]", "", org_agg$CorporationName)org_agg <- org_agg[org_agg$CorporationName !="" ,]head(org_agg)nrow(org_agg[org_agg$Building_Count > 2 ,])
The output:
Mmmm. The company names look a bit better, but I’m still not convinced about the number of owners with more than 2 buildings. This data set includes all of New York City. This city has a lot of buildings with a lot of landlords. Could it be that the same landlord or management company is registering different buildings under different names/IDs?
What if we looked at their mailing address? Let’s assume that a landlord registering under different names is still going to want to receive his/her mail at just one office. We can create a new variable by combining the BusinessHouseNumber and BusinessStreetName columns and run our aggregation again.
owners$RealID <- paste(owners$BusinessHouseNumber, owners$BusinessStreetName, sep=" ")real_agg <- aggregate(RegistrationID ~ RealID, data=owners, FUN=length)names(real_agg) <- c("RealID", "Building_Count")nrow(real_agg[real_agg$Building_Count > 2 ,])
Yeah — that makes more sense. We can’t be 100% sure that some of these aren’t actually different landlords that share the same mailing address, but I think we can assume this isn’t the case for the sake of this tutorial.
However, there’s a problem. If you hadn’t already noticed, many of the RegistrationIDs include multiple contacts, each with a different value for Type. Before we start filtering them out, let’s get an idea of the scope of the values.
summary(owners$Type)
This is what we get:
Now we could subset our dataframe to keep only Types that are owner-related roles. But that could lead to some problems, since owners aren’t required to be the “contact” for these types of registrations.
Instead, let’s just remove duplicate RegistrationIDs and re-run our aggregate function.
owners <- owners[! duplicated(owners$RegistrationID) ,]real_agg <- aggregate(RegistrationID ~ RealID, data=owners, FUN=length)names(real_agg) <- c("RealID", "Building_Count")nrow(real_agg[real_agg$Building_Count > 2 ,])
It looks like that, after removing duplicate RegistrationIDs, we have about 5,000 owners with more than two buildings.
Before we move on to the next step of the tutorial, let’s combine the Building_Count column with the main owners dataframe. We can do this with a simple merge.
owners <- merge(x=owners, y=real_agg, by="RealID")
Now that we have a strategy for how to define building ownership, we need to merge the recently updated owners dataframe with the buildings data set. This will give us the GIS information we’ll need for the mapping part of the tutorial.
1) Explore variables for buildings dataframe
head(bldgs)
My output looks like this:
Nice, it looks like both data sets share the RegistrationID variable. This means that each entry in this dataframe corresponds to a RegistrationID in the owners dataframe. We can use this column as our ID for the merge function.
2) Merge on RegistrationID
bldg_counts<- merge(x=bldgs, y=owners, by="RegistrationID")
The merge worked, but we lost a few rows. Annoyingly, it turns out that some types of properties are allowed to use the same RegistrationID, even when they have different addresses. This is explained in more detail in the data documentation.
Now for the fun stuff. We need to figure out what sort of GIS variables we can use to aggregate and plot this information. Let’s take another look at our recently combined dataframe.
bldg_counts<- merge(x=bldgs, y=owners, by="RegistrationID")
Output:
So, it looks like we have two options for geo variables. The first is the building address, which can be derived by combining the HouseNumber and StreetName columns. However, in order to plot this information we’d have to geocode the addresses first. Too much work.
We also have the Block and Lot variables. Block numbers in New York City are unique, meaning we could aggregate the number of buildings per block with landlords owning more than one building. The city also offers shape files with block-level polygons, allowing us to plot our data, as well. However, there are tens of thousands of blocks in Brooklyn, each with only a handful of buildings, so this probably wouldn’t be too meaningful.
In reality, none of these variables offer exactly what we need. Instead, let’s introduce a new data set: PLUTO. The PLUTO data set is the holy grail of New York City building stats, including everything from latitude and longitude to property value.
1) Read in PLUTO CSV file and explore variables
pluto_bk <- read.csv("data/pluto.csv")names(pluto_bk)
Output:
See what I was saying? Let’s keep only the relevant columns.
2) Remove unnecessary columns
pluto_bk <- pluto_bk[, c(4, 5, 6, 58,71, 73, 74, 75)]
We’re left with the following columns:
Now we have tons of options. I chose to go with Census tract, represented in different forms by the CT2010 and Tract2010 variables. This seems to be a good level of aggregation, as there are about 750 Census tracts in Brooklyn. Plus, the Census Bureau offers tract-level shape files, making it a breeze to map.
We need to merge this information with our building list we created earlier. Unfortunately, PLUTO doesn’t have the RegistrationID variable we used earlier. Instead, they use the more common BBL, which stands for “Borough, Block, Lot.”
Our buildings data doesn’t have a BBL variable, but we can make one by combining the borough, building and lot columns. However, first, we’ll use the sprintf function to pad our Block and Lot variables.
Padding adds extra zeros to values that are less than a certain number of digits. This allows our final BBL to be ten digits long, regardless of the value of the components that make it up.
We’ll also take this opportunity to subset our buildings dataframe to only include properties in Brooklyn. We do this using the BoroID of 3.
3) Create BBL variable in buildings dataframe
#subset dataframe for just Brooklyn bldg_counts <- bldg_counts [bldg_counts $BoroID == 3 ,]#create new columns with padded values bldg_counts ["New_Block"] <- lapply(bldg_counts ["Block"], function(x) sprintf("%05d", x))bldg_counts ["New_Lot"] <- lapply(bldg_counts ["Lot"], function(x) sprintf("%04d", x))#use paste function to combine everything into one variable bldg_counts ["BBL"] <- as.numeric(paste(bldg_counts $BoroID, bldg_counts $New_Block, bldg_counts $New_Lot, sep=""))
Looks good to me. Let’s go ahead and merge this dataframe with the PLUTO data. All we want is each building’s Census tract, so we can subset accordingly.
4) Merge tract info with buildings data set
names(pluto_bk)pluto_bk <- pluto_bk[, c(5, 2)]nrow(bldg_counts)bldg_counts <- merge(x=bldg_counts, y=pluto_bk1, by="BBL")nrow(bldg_counts)
We lost a few hundred rows that, for whatever reason, were not in the PLUTO data set.
One important side-note about BBLs: This value isn’t actually a unique identifier — some Lots have more than one building. This isn’t a huge deal, since all we need to extract from the PLUTO dataframe is Census tract, which would be the same for buildings that reside on the same lot.
If we wanted to be more precise, we could have created a unique ID variable by combining BBL with the street number for each building.
5) Aggregate by Census tract
#aggregate by census tract multiple <- bldg_counts[bldg_counts$Building_Count > 2 ,]tract_counts <- aggregate(Building_Count ~ CT2010, data=multiple, FUN=length )names(tract_counts)[1] <- "CTLabel"nrow(tract_counts)length(unique(pluto_bk$CT2010))
The first thing that jumps out at me is that we lost a bunch of Census tracts. The explanation is simple. While there are a total of 761 tracts in the borough, some of them are either 1) really small or 2) consist almost entirely of one-storey homes, which are not required to register with the city. Since these tracts have no “multiple-building” landlords, they won’t show up on aggregated list.
Alright. We have our dataframe with each Census tract and the number of properties owned by “multiple-building” landlords. It’s surprisingly few, but then again, Census tracts aren’t actually that big. Let’s map!
The first step in any mapping project in R is to read in our shapefile. The shapefile we are going to use for this tutorial is from the New York City Department of Planning. While the Census Bureau is normally the go-to resource for shapefiles, the NYC Department of Planning version already has the water areas clipped, so it is much neater.
1) Load shapefile
bk_shape <- readOGR(dsn = "shapefiles", layer = "nyct2010")head(bk_shape@data)
We can see that this shapefile actually has 2166 different census tracts, as it includes all boroughs. We can also see that it has data bound to the polygons, making it a spatial polygons dataframe (SPDF). This data includes the Census tract label, in addition to information about the polygons themselves. We’re going to want to bind our data to the SPDF, but first we need to fix a few things.
2) Subset SPDFSubsetting an SPDF in R is absurdly easy. You can do it just like a normal dataframe.
#remember "3" is the BoroCode for Brooklyn bk_shape <- bk_shape[bk_shape@data$BoroCode == "3" ,]head(bk_shape@data)
3) Merge our data with SPDF
Adding data to polygons in R is also pretty easy. In this case, we just need to make sure the ID variables have the same name, and we’re good to go.
bk_shape <- merge(bk_shape, tract_counts, by="CTLabel")
There ya go — you can see that we have now bound our data to the SPDF and we are ready to start with the map.
4) Plot base mapHere is where the Cartography package comes in. To start plotting our map, we need to first plot the “extent” of the map (i.e. the spatial region it will occupy), followed by the land mass.
plot(bk_shape, border = NA, col = NA, bg = "#A6CAE0")plot(bk_shape, col = "#E3DEBF", border=NA, add=TRUE)
It should look like this:
5) Add border linesNow we’re going to add a third layer, which will be the borders of the Census tracts.
plot(bk_shape, col = "grey60",border = "white", lwd=0.4, add=TRUE)
Now you should have this:
6) Choose color paletteThe Cartography package has lots of nice pre-made color palettes. I chose a simple green, but you can have a look at the others here on Page 4. I also chose to use 8 different colors, although this will always depend on the distribution of the data you are using.
cols <- carto.pal(pal1 = "green.pal" ,n1 = 8)
7) Add choropleth layerThis package has loads of different features for displaying data, but we’re going to stick to a simple choropleth map.
choroLayer(spdf = bk_shape, df = bk_shape@data, var = "Building_Count", breaks = c(0, 10, 30, 50, 70, 90, 110, 150), col = cols, border = "grey40", lwd = 0.5, legend.pos = "left", legend.title.txt = "Number of Buildings", legend.values.rnd = 10, add = TRUE)
Boooom. This actually turned out quite nice, as it corresponds very closely to what I know anecdotally to be true from several years of dealing with Brooklyn landlords. The dark green areas also correspond very closely to the areas of the borough that have experienced the most gentrification.
Many of the maps I made for the Brooklyn Public Library looked very similar, especially when looking at changes in median income and rent pre/post gentrification.
8) Add layout layerWe can add a little bit of metadata to the map by creating a layout layer.
layoutLayer(title = "Census Tracts by Building Ownership Concentration", author = "Pres Nichols", sources = "Source: NYC OpenData", scale = NULL, col = NA, coltitle = "black", frame = FALSE, bg = NA)
There is one important aspect that I didn’t take into account: what if the northern areas of the map, with supposedly more concentrated ownership, just have more buildings in total?
If you’re following this tutorial, I’ll leave it up to you to figure that out and report back your findings!
Note: Those not familiar with Brooklyn’s geography might be a bit concerned by all the white tracts on the map. It looks way worse than it is. This is because the largest white areas (Prospect Park, Greenwood Cemetery and the Rockaways) aren’t actually inhabited. If they still bother you, you can always give the uninhabited areas a different color.
|
[
{
"code": null,
"e": 376,
"s": 172,
"text": "I think I’ve said this before ... but I love maps. Almost everyone uses them, making maps an amazing way of instantly communicating huge amounts of data without worrying about overwhelming your audience."
},
{
"code": null,
"e": 589,
"s": 376,
"text": "One of my favorite tools for working with spatial data is R. Apart from being great for data wrangling, its broad user-base means that there are loads of packages that make custom map making super quick and easy."
},
{
"code": null,
"e": 837,
"s": 589,
"text": "This tutorial is meant to provide a rough, end-to-end example of using R to manipulate and map data. The goal is to create a map that will illustrate the concentration of residential building ownership throughout the borough of Brooklyn, New York."
},
{
"code": null,
"e": 970,
"s": 837,
"text": "We’ll be using a number of data sets from New York City’s OpenData portal, in addition to the recently released Cartography package."
},
{
"code": null,
"e": 1030,
"s": 970,
"text": "To complete this tutorial, you’ll need the following tools:"
},
{
"code": null,
"e": 1032,
"s": 1030,
"text": "R"
},
{
"code": null,
"e": 1058,
"s": 1032,
"text": "R Studio or any other IDE"
},
{
"code": null,
"e": 1089,
"s": 1058,
"text": "1) Clone the GitHub repository"
},
{
"code": null,
"e": 1167,
"s": 1089,
"text": "git clone https://github.com/spnichol/mapping_tutorial.gitcd mapping_tutorial"
},
{
"code": null,
"e": 1223,
"s": 1167,
"text": "2) Create a new R script and set your working directory"
},
{
"code": null,
"e": 1259,
"s": 1223,
"text": "setwd(\"/home/you/mapping_tutorial\")"
},
{
"code": null,
"e": 1308,
"s": 1259,
"text": "3) Install packages and load first two data sets"
},
{
"code": null,
"e": 1469,
"s": 1308,
"text": "install.packages(c(\"cartography\", \"rgdal\", \"sp\"))#ownership registrations owners <- read.csv(\"data/owners.csv\")#building data bldgs <- read.csv(\"data/bldg.csv\")"
},
{
"code": null,
"e": 1714,
"s": 1469,
"text": "The first file is the Multiple Dwelling Registrations, a registry of residential buildings with three units or more. The second is Registration Contacts, which contains information relating to the owners of the buildings from the previous file."
},
{
"code": null,
"e": 1882,
"s": 1714,
"text": "Our goal with this project is to get an idea of the concentration of building ownership in Brooklyn. So, a natural place to start out would be with the ownership file."
},
{
"code": null,
"e": 1942,
"s": 1882,
"text": "Let’s look at a few records to get a sense of what we have."
},
{
"code": null,
"e": 1955,
"s": 1942,
"text": "head(owners)"
},
{
"code": null,
"e": 1990,
"s": 1955,
"text": "Your output should look like this:"
},
{
"code": null,
"e": 2228,
"s": 1990,
"text": "It looks like we have two ID variables: RegistrationContactID and RegistrationID. The first refers to the individual/company that is listed in that row, while the second refers to a specific building registration that person/entity made."
},
{
"code": null,
"e": 2413,
"s": 2228,
"text": "We also have the CorporationName column, which could provide some insight into who owns what in Brooklyn. Let’s use the aggregate function on RegistrationContactID and CorporationName."
},
{
"code": null,
"e": 2637,
"s": 2413,
"text": "owner_count <- aggregate(RegistrationID ~ RegistrationContactID, data=owners, FUN=length)names(owner_count) <- c(\"RegistrationContactID\", \"Building_Count\")head(owner_count)nrow(owner_count[owner_count$Building_Count > 2 ,])"
},
{
"code": null,
"e": 2672,
"s": 2637,
"text": "Your output should look like this:"
},
{
"code": null,
"e": 2941,
"s": 2672,
"text": "Now we have one column with each unique RegistrationContactID and the number of buildings corresponding to it. Besides some odd looking IDs (just messy data), it’s a bit strange that we only have 274 owners with more than two buildings. Let’s try with CorporationName."
},
{
"code": null,
"e": 3158,
"s": 2941,
"text": "owner_count <- aggregate(org_agg <- aggregate(RegistrationID ~ CorporationName, data=owners, FUN=length)names(org_agg) <- c(\"CorporationName\", \"Building_Count\")head(org_agg)nrow(org_agg[org_agg$Building_Count > 2 ,])"
},
{
"code": null,
"e": 3170,
"s": 3158,
"text": "The output:"
},
{
"code": null,
"e": 3352,
"s": 3170,
"text": "Yikes. The building count is much better, but those are some nasty typos. Let’s fix them by removing all non-alphanumeric characters and then subsetting to keep only non-empty rows."
},
{
"code": null,
"e": 3543,
"s": 3352,
"text": "org_agg$CorporationName<- gsub(\"[^[:alnum:][:blank:]]\", \"\", org_agg$CorporationName)org_agg <- org_agg[org_agg$CorporationName !=\"\" ,]head(org_agg)nrow(org_agg[org_agg$Building_Count > 2 ,])"
},
{
"code": null,
"e": 3555,
"s": 3543,
"text": "The output:"
},
{
"code": null,
"e": 3903,
"s": 3555,
"text": "Mmmm. The company names look a bit better, but I’m still not convinced about the number of owners with more than 2 buildings. This data set includes all of New York City. This city has a lot of buildings with a lot of landlords. Could it be that the same landlord or management company is registering different buildings under different names/IDs?"
},
{
"code": null,
"e": 4205,
"s": 3903,
"text": "What if we looked at their mailing address? Let’s assume that a landlord registering under different names is still going to want to receive his/her mail at just one office. We can create a new variable by combining the BusinessHouseNumber and BusinessStreetName columns and run our aggregation again."
},
{
"code": null,
"e": 4456,
"s": 4205,
"text": "owners$RealID <- paste(owners$BusinessHouseNumber, owners$BusinessStreetName, sep=\" \")real_agg <- aggregate(RegistrationID ~ RealID, data=owners, FUN=length)names(real_agg) <- c(\"RealID\", \"Building_Count\")nrow(real_agg[real_agg$Building_Count > 2 ,])"
},
{
"code": null,
"e": 4677,
"s": 4456,
"text": "Yeah — that makes more sense. We can’t be 100% sure that some of these aren’t actually different landlords that share the same mailing address, but I think we can assume this isn’t the case for the sake of this tutorial."
},
{
"code": null,
"e": 4911,
"s": 4677,
"text": "However, there’s a problem. If you hadn’t already noticed, many of the RegistrationIDs include multiple contacts, each with a different value for Type. Before we start filtering them out, let’s get an idea of the scope of the values."
},
{
"code": null,
"e": 4932,
"s": 4911,
"text": "summary(owners$Type)"
},
{
"code": null,
"e": 4953,
"s": 4932,
"text": "This is what we get:"
},
{
"code": null,
"e": 5157,
"s": 4953,
"text": "Now we could subset our dataframe to keep only Types that are owner-related roles. But that could lead to some problems, since owners aren’t required to be the “contact” for these types of registrations."
},
{
"code": null,
"e": 5245,
"s": 5157,
"text": "Instead, let’s just remove duplicate RegistrationIDs and re-run our aggregate function."
},
{
"code": null,
"e": 5465,
"s": 5245,
"text": "owners <- owners[! duplicated(owners$RegistrationID) ,]real_agg <- aggregate(RegistrationID ~ RealID, data=owners, FUN=length)names(real_agg) <- c(\"RealID\", \"Building_Count\")nrow(real_agg[real_agg$Building_Count > 2 ,])"
},
{
"code": null,
"e": 5584,
"s": 5465,
"text": "It looks like that, after removing duplicate RegistrationIDs, we have about 5,000 owners with more than two buildings."
},
{
"code": null,
"e": 5744,
"s": 5584,
"text": "Before we move on to the next step of the tutorial, let’s combine the Building_Count column with the main owners dataframe. We can do this with a simple merge."
},
{
"code": null,
"e": 5795,
"s": 5744,
"text": "owners <- merge(x=owners, y=real_agg, by=\"RealID\")"
},
{
"code": null,
"e": 6032,
"s": 5795,
"text": "Now that we have a strategy for how to define building ownership, we need to merge the recently updated owners dataframe with the buildings data set. This will give us the GIS information we’ll need for the mapping part of the tutorial."
},
{
"code": null,
"e": 6077,
"s": 6032,
"text": "1) Explore variables for buildings dataframe"
},
{
"code": null,
"e": 6089,
"s": 6077,
"text": "head(bldgs)"
},
{
"code": null,
"e": 6116,
"s": 6089,
"text": "My output looks like this:"
},
{
"code": null,
"e": 6345,
"s": 6116,
"text": "Nice, it looks like both data sets share the RegistrationID variable. This means that each entry in this dataframe corresponds to a RegistrationID in the owners dataframe. We can use this column as our ID for the merge function."
},
{
"code": null,
"e": 6372,
"s": 6345,
"text": "2) Merge on RegistrationID"
},
{
"code": null,
"e": 6432,
"s": 6372,
"text": "bldg_counts<- merge(x=bldgs, y=owners, by=\"RegistrationID\")"
},
{
"code": null,
"e": 6674,
"s": 6432,
"text": "The merge worked, but we lost a few rows. Annoyingly, it turns out that some types of properties are allowed to use the same RegistrationID, even when they have different addresses. This is explained in more detail in the data documentation."
},
{
"code": null,
"e": 6857,
"s": 6674,
"text": "Now for the fun stuff. We need to figure out what sort of GIS variables we can use to aggregate and plot this information. Let’s take another look at our recently combined dataframe."
},
{
"code": null,
"e": 6917,
"s": 6857,
"text": "bldg_counts<- merge(x=bldgs, y=owners, by=\"RegistrationID\")"
},
{
"code": null,
"e": 6925,
"s": 6917,
"text": "Output:"
},
{
"code": null,
"e": 7191,
"s": 6925,
"text": "So, it looks like we have two options for geo variables. The first is the building address, which can be derived by combining the HouseNumber and StreetName columns. However, in order to plot this information we’d have to geocode the addresses first. Too much work."
},
{
"code": null,
"e": 7626,
"s": 7191,
"text": "We also have the Block and Lot variables. Block numbers in New York City are unique, meaning we could aggregate the number of buildings per block with landlords owning more than one building. The city also offers shape files with block-level polygons, allowing us to plot our data, as well. However, there are tens of thousands of blocks in Brooklyn, each with only a handful of buildings, so this probably wouldn’t be too meaningful."
},
{
"code": null,
"e": 7876,
"s": 7626,
"text": "In reality, none of these variables offer exactly what we need. Instead, let’s introduce a new data set: PLUTO. The PLUTO data set is the holy grail of New York City building stats, including everything from latitude and longitude to property value."
},
{
"code": null,
"e": 7924,
"s": 7876,
"text": "1) Read in PLUTO CSV file and explore variables"
},
{
"code": null,
"e": 7978,
"s": 7924,
"text": "pluto_bk <- read.csv(\"data/pluto.csv\")names(pluto_bk)"
},
{
"code": null,
"e": 7986,
"s": 7978,
"text": "Output:"
},
{
"code": null,
"e": 8047,
"s": 7986,
"text": "See what I was saying? Let’s keep only the relevant columns."
},
{
"code": null,
"e": 8077,
"s": 8047,
"text": "2) Remove unnecessary columns"
},
{
"code": null,
"e": 8131,
"s": 8077,
"text": "pluto_bk <- pluto_bk[, c(4, 5, 6, 58,71, 73, 74, 75)]"
},
{
"code": null,
"e": 8170,
"s": 8131,
"text": "We’re left with the following columns:"
},
{
"code": null,
"e": 8481,
"s": 8170,
"text": "Now we have tons of options. I chose to go with Census tract, represented in different forms by the CT2010 and Tract2010 variables. This seems to be a good level of aggregation, as there are about 750 Census tracts in Brooklyn. Plus, the Census Bureau offers tract-level shape files, making it a breeze to map."
},
{
"code": null,
"e": 8716,
"s": 8481,
"text": "We need to merge this information with our building list we created earlier. Unfortunately, PLUTO doesn’t have the RegistrationID variable we used earlier. Instead, they use the more common BBL, which stands for “Borough, Block, Lot.”"
},
{
"code": null,
"e": 8919,
"s": 8716,
"text": "Our buildings data doesn’t have a BBL variable, but we can make one by combining the borough, building and lot columns. However, first, we’ll use the sprintf function to pad our Block and Lot variables."
},
{
"code": null,
"e": 9109,
"s": 8919,
"text": "Padding adds extra zeros to values that are less than a certain number of digits. This allows our final BBL to be ten digits long, regardless of the value of the components that make it up."
},
{
"code": null,
"e": 9250,
"s": 9109,
"text": "We’ll also take this opportunity to subset our buildings dataframe to only include properties in Brooklyn. We do this using the BoroID of 3."
},
{
"code": null,
"e": 9296,
"s": 9250,
"text": "3) Create BBL variable in buildings dataframe"
},
{
"code": null,
"e": 9779,
"s": 9296,
"text": "#subset dataframe for just Brooklyn bldg_counts <- bldg_counts [bldg_counts $BoroID == 3 ,]#create new columns with padded values bldg_counts [\"New_Block\"] <- lapply(bldg_counts [\"Block\"], function(x) sprintf(\"%05d\", x))bldg_counts [\"New_Lot\"] <- lapply(bldg_counts [\"Lot\"], function(x) sprintf(\"%04d\", x))#use paste function to combine everything into one variable bldg_counts [\"BBL\"] <- as.numeric(paste(bldg_counts $BoroID, bldg_counts $New_Block, bldg_counts $New_Lot, sep=\"\"))"
},
{
"code": null,
"e": 9933,
"s": 9779,
"text": "Looks good to me. Let’s go ahead and merge this dataframe with the PLUTO data. All we want is each building’s Census tract, so we can subset accordingly."
},
{
"code": null,
"e": 9977,
"s": 9933,
"text": "4) Merge tract info with buildings data set"
},
{
"code": null,
"e": 10116,
"s": 9977,
"text": "names(pluto_bk)pluto_bk <- pluto_bk[, c(5, 2)]nrow(bldg_counts)bldg_counts <- merge(x=bldg_counts, y=pluto_bk1, by=\"BBL\")nrow(bldg_counts)"
},
{
"code": null,
"e": 10202,
"s": 10116,
"text": "We lost a few hundred rows that, for whatever reason, were not in the PLUTO data set."
},
{
"code": null,
"e": 10487,
"s": 10202,
"text": "One important side-note about BBLs: This value isn’t actually a unique identifier — some Lots have more than one building. This isn’t a huge deal, since all we need to extract from the PLUTO dataframe is Census tract, which would be the same for buildings that reside on the same lot."
},
{
"code": null,
"e": 10622,
"s": 10487,
"text": "If we wanted to be more precise, we could have created a unique ID variable by combining BBL with the street number for each building."
},
{
"code": null,
"e": 10651,
"s": 10622,
"text": "5) Aggregate by Census tract"
},
{
"code": null,
"e": 10898,
"s": 10651,
"text": "#aggregate by census tract multiple <- bldg_counts[bldg_counts$Building_Count > 2 ,]tract_counts <- aggregate(Building_Count ~ CT2010, data=multiple, FUN=length )names(tract_counts)[1] <- \"CTLabel\"nrow(tract_counts)length(unique(pluto_bk$CT2010))"
},
{
"code": null,
"e": 11296,
"s": 10898,
"text": "The first thing that jumps out at me is that we lost a bunch of Census tracts. The explanation is simple. While there are a total of 761 tracts in the borough, some of them are either 1) really small or 2) consist almost entirely of one-storey homes, which are not required to register with the city. Since these tracts have no “multiple-building” landlords, they won’t show up on aggregated list."
},
{
"code": null,
"e": 11509,
"s": 11296,
"text": "Alright. We have our dataframe with each Census tract and the number of properties owned by “multiple-building” landlords. It’s surprisingly few, but then again, Census tracts aren’t actually that big. Let’s map!"
},
{
"code": null,
"e": 11852,
"s": 11509,
"text": "The first step in any mapping project in R is to read in our shapefile. The shapefile we are going to use for this tutorial is from the New York City Department of Planning. While the Census Bureau is normally the go-to resource for shapefiles, the NYC Department of Planning version already has the water areas clipped, so it is much neater."
},
{
"code": null,
"e": 11870,
"s": 11852,
"text": "1) Load shapefile"
},
{
"code": null,
"e": 11949,
"s": 11870,
"text": "bk_shape <- readOGR(dsn = \"shapefiles\", layer = \"nyct2010\")head(bk_shape@data)"
},
{
"code": null,
"e": 12345,
"s": 11949,
"text": "We can see that this shapefile actually has 2166 different census tracts, as it includes all boroughs. We can also see that it has data bound to the polygons, making it a spatial polygons dataframe (SPDF). This data includes the Census tract label, in addition to information about the polygons themselves. We’re going to want to bind our data to the SPDF, but first we need to fix a few things."
},
{
"code": null,
"e": 12445,
"s": 12345,
"text": "2) Subset SPDFSubsetting an SPDF in R is absurdly easy. You can do it just like a normal dataframe."
},
{
"code": null,
"e": 12561,
"s": 12445,
"text": "#remember \"3\" is the BoroCode for Brooklyn bk_shape <- bk_shape[bk_shape@data$BoroCode == \"3\" ,]head(bk_shape@data)"
},
{
"code": null,
"e": 12589,
"s": 12561,
"text": "3) Merge our data with SPDF"
},
{
"code": null,
"e": 12738,
"s": 12589,
"text": "Adding data to polygons in R is also pretty easy. In this case, we just need to make sure the ID variables have the same name, and we’re good to go."
},
{
"code": null,
"e": 12794,
"s": 12738,
"text": "bk_shape <- merge(bk_shape, tract_counts, by=\"CTLabel\")"
},
{
"code": null,
"e": 12904,
"s": 12794,
"text": "There ya go — you can see that we have now bound our data to the SPDF and we are ready to start with the map."
},
{
"code": null,
"e": 13110,
"s": 12904,
"text": "4) Plot base mapHere is where the Cartography package comes in. To start plotting our map, we need to first plot the “extent” of the map (i.e. the spatial region it will occupy), followed by the land mass."
},
{
"code": null,
"e": 13217,
"s": 13110,
"text": "plot(bk_shape, border = NA, col = NA, bg = \"#A6CAE0\")plot(bk_shape, col = \"#E3DEBF\", border=NA, add=TRUE)"
},
{
"code": null,
"e": 13243,
"s": 13217,
"text": "It should look like this:"
},
{
"code": null,
"e": 13348,
"s": 13243,
"text": "5) Add border linesNow we’re going to add a third layer, which will be the borders of the Census tracts."
},
{
"code": null,
"e": 13415,
"s": 13348,
"text": "plot(bk_shape, col = \"grey60\",border = \"white\", lwd=0.4, add=TRUE)"
},
{
"code": null,
"e": 13441,
"s": 13415,
"text": "Now you should have this:"
},
{
"code": null,
"e": 13728,
"s": 13441,
"text": "6) Choose color paletteThe Cartography package has lots of nice pre-made color palettes. I chose a simple green, but you can have a look at the others here on Page 4. I also chose to use 8 different colors, although this will always depend on the distribution of the data you are using."
},
{
"code": null,
"e": 13774,
"s": 13728,
"text": "cols <- carto.pal(pal1 = \"green.pal\" ,n1 = 8)"
},
{
"code": null,
"e": 13916,
"s": 13774,
"text": "7) Add choropleth layerThis package has loads of different features for displaying data, but we’re going to stick to a simple choropleth map."
},
{
"code": null,
"e": 14282,
"s": 13916,
"text": "choroLayer(spdf = bk_shape, df = bk_shape@data, var = \"Building_Count\", breaks = c(0, 10, 30, 50, 70, 90, 110, 150), col = cols, border = \"grey40\", lwd = 0.5, legend.pos = \"left\", legend.title.txt = \"Number of Buildings\", legend.values.rnd = 10, add = TRUE)"
},
{
"code": null,
"e": 14576,
"s": 14282,
"text": "Boooom. This actually turned out quite nice, as it corresponds very closely to what I know anecdotally to be true from several years of dealing with Brooklyn landlords. The dark green areas also correspond very closely to the areas of the borough that have experienced the most gentrification."
},
{
"code": null,
"e": 14739,
"s": 14576,
"text": "Many of the maps I made for the Brooklyn Public Library looked very similar, especially when looking at changes in median income and rent pre/post gentrification."
},
{
"code": null,
"e": 14833,
"s": 14739,
"text": "8) Add layout layerWe can add a little bit of metadata to the map by creating a layout layer."
},
{
"code": null,
"e": 15119,
"s": 14833,
"text": "layoutLayer(title = \"Census Tracts by Building Ownership Concentration\", author = \"Pres Nichols\", sources = \"Source: NYC OpenData\", scale = NULL, col = NA, coltitle = \"black\", frame = FALSE, bg = NA)"
},
{
"code": null,
"e": 15301,
"s": 15119,
"text": "There is one important aspect that I didn’t take into account: what if the northern areas of the map, with supposedly more concentrated ownership, just have more buildings in total?"
},
{
"code": null,
"e": 15410,
"s": 15301,
"text": "If you’re following this tutorial, I’ll leave it up to you to figure that out and report back your findings!"
}
] |
Convert XML to POJO using the Jackson library in Java?
|
The JSON Jackson is a library for Java. It has very powerful data binding capabilities and provides a framework to serialize custom java objects to JSON and deserialize JSON back to Java object. We can also convert an XML format to the POJO object using the readValue() method of the XmlMapper class.
public <T> T readValue(XMLStreamReader r, Class<T> valueType) throws IOException
import com.fasterxml.jackson.dataformat.xml.*;
public class XMLToPOJOTest {
public static void main(String args[]) throws Exception {
try {
XmlMapper xmlMapper = new XmlMapper();
Person pojo = xmlMapper.readValue(getXmlString(), Person.class);
System.out.println(pojo);
} catch(Exception e) {
e.printStackTrace();
}
}
private static String getXmlString() {
return "<person> <firstName>Adithya</firstName>"
+ "<lastName>Jai</lastName>"
+ "<address>Bangalore</address>" + "</person>";
}
}
// Person class (POJO)
class Person {
private String firstName;
private String lastName;
private String address;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String toString() {
return "Person[ " +
"firstName = " + firstName +
", lastName = " + lastName +
", address = " + address +
" ]";
}
}
Person[ firstName = Adithya, lastName = Jai, address = Bangalore ]
|
[
{
"code": null,
"e": 1363,
"s": 1062,
"text": "The JSON Jackson is a library for Java. It has very powerful data binding capabilities and provides a framework to serialize custom java objects to JSON and deserialize JSON back to Java object. We can also convert an XML format to the POJO object using the readValue() method of the XmlMapper class."
},
{
"code": null,
"e": 1444,
"s": 1363,
"text": "public <T> T readValue(XMLStreamReader r, Class<T> valueType) throws IOException"
},
{
"code": null,
"e": 2803,
"s": 1444,
"text": "import com.fasterxml.jackson.dataformat.xml.*;\npublic class XMLToPOJOTest {\n public static void main(String args[]) throws Exception {\n try {\n XmlMapper xmlMapper = new XmlMapper();\n Person pojo = xmlMapper.readValue(getXmlString(), Person.class);\n System.out.println(pojo);\n } catch(Exception e) {\n e.printStackTrace();\n }\n }\n private static String getXmlString() {\n return \"<person> <firstName>Adithya</firstName>\"\n + \"<lastName>Jai</lastName>\"\n + \"<address>Bangalore</address>\" + \"</person>\";\n }\n}\n// Person class (POJO)\nclass Person {\n private String firstName;\n private String lastName;\n private String address;\n public String getFirstName() {\n return firstName;\n }\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n public String getLastName() {\n return lastName;\n }\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n public String getAddress() {\n return address;\n }\n public void setAddress(String address) {\n this.address = address;\n }\n public String toString() {\n return \"Person[ \" +\n \"firstName = \" + firstName +\n \", lastName = \" + lastName +\n \", address = \" + address +\n \" ]\";\n }\n}"
},
{
"code": null,
"e": 2870,
"s": 2803,
"text": "Person[ firstName = Adithya, lastName = Jai, address = Bangalore ]"
}
] |
How to Create a Forest Plot in R? - GeeksforGeeks
|
04 Jan, 2022
In this article, we will discuss how to create a Forest Plot in the R programming language.
A forest plot is also known as a blobbogram. It helps us to visualize estimated results from a certain number of studies together along with the overall results in a single plot. It is extensively used in medical research for visualizing a meta-analysis of the results of randomized controlled trials. The x-axis of the plot contains the value of the interest in the studies and the y-axis displays the results from the different trials.
To create a Forest Plot in the R Language, we use a combination of scatter plots along with the error bar. The geom_point() function of the ggplot package helps us to create a scatter plot. To create an error bar plot as an overlay on top of the scatter plot, we use the geom_errorbarh() function. The geom_errorbarh() function is used to draw a horizontal error bar plot.
Syntax:
ggplot(data, aes( y, x, xmin, xmax )) + geom_point() + geom_errorbarh( height )
Parameter:
data: determines the data frame to be used for plotting.
x and y: determines the axes variables
xmin and xmax: determines the x-axis limits
height: determines the width of the error bar
Example: Basic forest plot.
R
# create sample datasample_data <- data.frame(study=c('G1', 'G2', 'G3', 'G4', 'G5'), index=1:5, result=c(-.23, -.45, -.16, .6, .65), error_lower=c(-.35, -.59, -.37, -.12, .24), error_upper=c(-.17, -.25, -.03, .82, .91)) #load library ggplot2library(ggplot2) #create forest plotggplot(data=sample_data, aes(y=index, x=result, xmin=error_lower, xmax=error_upper)) + geom_point() + geom_errorbarh(height=.1) + scale_y_continuous(labels=sample_data$study)
Output:
To add the title to the plot, we use the title argument of the labs() function of the R Language. We can also change axis labels of the x-axis and y-axis using the x and y argument of the labs() function respectively.
Syntax:
plot() + labs( title, x, y )
Parameter:
title: determines the title of the plot.
x and y: determines the axis titles for the x-axis and y-axis respectively.
Example: Forest plot with a custom title for the plot and both axes.
R
# create sample datasample_data <- data.frame(study=c('G1', 'G2', 'G3', 'G4', 'G5'), index=1:5, result=c(-.23, -.45, -.16, .6, .65), error_lower=c(-.35, -.59, -.37, -.12, .24), error_upper=c(-.17, -.25, -.03, .82, .91)) #load library ggplot2library(ggplot2) #create forest plotggplot(data=sample_data, aes(y=index, x=result, xmin=error_lower, xmax=error_upper)) + geom_point() + geom_errorbarh(height=.1) + scale_y_continuous(labels=sample_data$study)+ labs(title='Title Of Plot', x='X-axis Title', y = 'Y-axis Title')
Output:
To add a vertical line to the plot as an overlay in the R Language by using the geom_vline() function. We can add a vertical line in the plot to show the position of zero for better visualization of the data. We can use the xintercept, linetype, color, and alpha argument of the geom_vline() function to customize the position, the shape of the line, color, and transparency of the vertical line respectively.
Syntax:
plot + geom_vline( xintercept, linetype, color, alpha )
Parameter:
xintercept: determines the position of the line on the x-axis.
linetype: determines the shape of the line.
color: determines the color of the line.
alpha: determines the transparency of the line.
Example: Forest plot with a vertical line at x=0.
R
# create sample datasample_data <- data.frame(study=c('G1', 'G2', 'G3', 'G4', 'G5'), index=1:5, result=c(-.23, -.45, -.16, .6, .65), error_lower=c(-.35, -.59, -.37, -.12, .24), error_upper=c(-.17, -.25, -.03, .82, .91)) #load library ggplot2library(ggplot2) #create forest plotggplot(data=sample_data, aes(y=index, x=result, xmin=error_lower, xmax=error_upper)) + geom_point() + geom_errorbarh(height=.1) + scale_y_continuous(labels=sample_data$study)+ geom_vline(xintercept=0, color='green', linetype='dashed', alpha=.8)
Output:
To customize the forest plot, we can change the color and shape of the bar and point to make it more informative as well as aesthetically pleasing. For changing color and size we can use basic aesthetic arguments such as color, lwd, pch, etc.
Syntax:
ggplot(data, aes(y, x, xmin, xmax)) + geom_errorbarh(height, color, lwd) + geom_point( color, pch, size)
Parameter:
color: determines the color of point or errorbar
lwd: determines the line width of error bar
pch: determines the shape of point.
Example:
Here, is a completely customized forest plot.
R
# create sample datasample_data <- data.frame(study=c('G1', 'G2', 'G3', 'G4', 'G5'), index=1:5, result=c(-.23, -.45, -.16, .6, .65), error_lower=c(-.35, -.59, -.37, -.12, .24), error_upper=c(-.17, -.25, -.03, .82, .91)) #load library ggplot2library(ggplot2) #create forest plotggplot(data=sample_data, aes(y=index, x=result, xmin=error_lower, xmax=error_upper)) + geom_errorbarh(height=.1, color= "green", lwd=1.2) + geom_point( color= "red", pch= 9, size=3) + scale_y_continuous(labels=sample_data$study)+ labs(title="Forest Plot")+ geom_vline(xintercept=0, color='blue', linetype='dashed', alpha=.5)
Output:
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.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
Logistic Regression in R Programming
How to Split Column Into Multiple Columns in R DataFrame?
Control Statements in R Programming
How to import an Excel File into R ?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
|
[
{
"code": null,
"e": 25162,
"s": 25134,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 25254,
"s": 25162,
"text": "In this article, we will discuss how to create a Forest Plot in the R programming language."
},
{
"code": null,
"e": 25692,
"s": 25254,
"text": "A forest plot is also known as a blobbogram. It helps us to visualize estimated results from a certain number of studies together along with the overall results in a single plot. It is extensively used in medical research for visualizing a meta-analysis of the results of randomized controlled trials. The x-axis of the plot contains the value of the interest in the studies and the y-axis displays the results from the different trials."
},
{
"code": null,
"e": 26065,
"s": 25692,
"text": "To create a Forest Plot in the R Language, we use a combination of scatter plots along with the error bar. The geom_point() function of the ggplot package helps us to create a scatter plot. To create an error bar plot as an overlay on top of the scatter plot, we use the geom_errorbarh() function. The geom_errorbarh() function is used to draw a horizontal error bar plot."
},
{
"code": null,
"e": 26073,
"s": 26065,
"text": "Syntax:"
},
{
"code": null,
"e": 26154,
"s": 26073,
"text": "ggplot(data, aes( y, x, xmin, xmax )) + geom_point() + geom_errorbarh( height )"
},
{
"code": null,
"e": 26165,
"s": 26154,
"text": "Parameter:"
},
{
"code": null,
"e": 26222,
"s": 26165,
"text": "data: determines the data frame to be used for plotting."
},
{
"code": null,
"e": 26261,
"s": 26222,
"text": "x and y: determines the axes variables"
},
{
"code": null,
"e": 26305,
"s": 26261,
"text": "xmin and xmax: determines the x-axis limits"
},
{
"code": null,
"e": 26351,
"s": 26305,
"text": "height: determines the width of the error bar"
},
{
"code": null,
"e": 26379,
"s": 26351,
"text": "Example: Basic forest plot."
},
{
"code": null,
"e": 26381,
"s": 26379,
"text": "R"
},
{
"code": "# create sample datasample_data <- data.frame(study=c('G1', 'G2', 'G3', 'G4', 'G5'), index=1:5, result=c(-.23, -.45, -.16, .6, .65), error_lower=c(-.35, -.59, -.37, -.12, .24), error_upper=c(-.17, -.25, -.03, .82, .91)) #load library ggplot2library(ggplot2) #create forest plotggplot(data=sample_data, aes(y=index, x=result, xmin=error_lower, xmax=error_upper)) + geom_point() + geom_errorbarh(height=.1) + scale_y_continuous(labels=sample_data$study)",
"e": 26960,
"s": 26381,
"text": null
},
{
"code": null,
"e": 26968,
"s": 26960,
"text": "Output:"
},
{
"code": null,
"e": 27187,
"s": 26968,
"text": "To add the title to the plot, we use the title argument of the labs() function of the R Language. We can also change axis labels of the x-axis and y-axis using the x and y argument of the labs() function respectively. "
},
{
"code": null,
"e": 27195,
"s": 27187,
"text": "Syntax:"
},
{
"code": null,
"e": 27224,
"s": 27195,
"text": "plot() + labs( title, x, y )"
},
{
"code": null,
"e": 27235,
"s": 27224,
"text": "Parameter:"
},
{
"code": null,
"e": 27276,
"s": 27235,
"text": "title: determines the title of the plot."
},
{
"code": null,
"e": 27352,
"s": 27276,
"text": "x and y: determines the axis titles for the x-axis and y-axis respectively."
},
{
"code": null,
"e": 27421,
"s": 27352,
"text": "Example: Forest plot with a custom title for the plot and both axes."
},
{
"code": null,
"e": 27423,
"s": 27421,
"text": "R"
},
{
"code": "# create sample datasample_data <- data.frame(study=c('G1', 'G2', 'G3', 'G4', 'G5'), index=1:5, result=c(-.23, -.45, -.16, .6, .65), error_lower=c(-.35, -.59, -.37, -.12, .24), error_upper=c(-.17, -.25, -.03, .82, .91)) #load library ggplot2library(ggplot2) #create forest plotggplot(data=sample_data, aes(y=index, x=result, xmin=error_lower, xmax=error_upper)) + geom_point() + geom_errorbarh(height=.1) + scale_y_continuous(labels=sample_data$study)+ labs(title='Title Of Plot', x='X-axis Title', y = 'Y-axis Title')",
"e": 28071,
"s": 27423,
"text": null
},
{
"code": null,
"e": 28079,
"s": 28071,
"text": "Output:"
},
{
"code": null,
"e": 28489,
"s": 28079,
"text": "To add a vertical line to the plot as an overlay in the R Language by using the geom_vline() function. We can add a vertical line in the plot to show the position of zero for better visualization of the data. We can use the xintercept, linetype, color, and alpha argument of the geom_vline() function to customize the position, the shape of the line, color, and transparency of the vertical line respectively."
},
{
"code": null,
"e": 28497,
"s": 28489,
"text": "Syntax:"
},
{
"code": null,
"e": 28553,
"s": 28497,
"text": "plot + geom_vline( xintercept, linetype, color, alpha )"
},
{
"code": null,
"e": 28564,
"s": 28553,
"text": "Parameter:"
},
{
"code": null,
"e": 28627,
"s": 28564,
"text": "xintercept: determines the position of the line on the x-axis."
},
{
"code": null,
"e": 28671,
"s": 28627,
"text": "linetype: determines the shape of the line."
},
{
"code": null,
"e": 28712,
"s": 28671,
"text": "color: determines the color of the line."
},
{
"code": null,
"e": 28760,
"s": 28712,
"text": "alpha: determines the transparency of the line."
},
{
"code": null,
"e": 28810,
"s": 28760,
"text": "Example: Forest plot with a vertical line at x=0."
},
{
"code": null,
"e": 28812,
"s": 28810,
"text": "R"
},
{
"code": "# create sample datasample_data <- data.frame(study=c('G1', 'G2', 'G3', 'G4', 'G5'), index=1:5, result=c(-.23, -.45, -.16, .6, .65), error_lower=c(-.35, -.59, -.37, -.12, .24), error_upper=c(-.17, -.25, -.03, .82, .91)) #load library ggplot2library(ggplot2) #create forest plotggplot(data=sample_data, aes(y=index, x=result, xmin=error_lower, xmax=error_upper)) + geom_point() + geom_errorbarh(height=.1) + scale_y_continuous(labels=sample_data$study)+ geom_vline(xintercept=0, color='green', linetype='dashed', alpha=.8)",
"e": 29462,
"s": 28812,
"text": null
},
{
"code": null,
"e": 29470,
"s": 29462,
"text": "Output:"
},
{
"code": null,
"e": 29713,
"s": 29470,
"text": "To customize the forest plot, we can change the color and shape of the bar and point to make it more informative as well as aesthetically pleasing. For changing color and size we can use basic aesthetic arguments such as color, lwd, pch, etc."
},
{
"code": null,
"e": 29721,
"s": 29713,
"text": "Syntax:"
},
{
"code": null,
"e": 29827,
"s": 29721,
"text": "ggplot(data, aes(y, x, xmin, xmax)) + geom_errorbarh(height, color, lwd) + geom_point( color, pch, size)"
},
{
"code": null,
"e": 29838,
"s": 29827,
"text": "Parameter:"
},
{
"code": null,
"e": 29887,
"s": 29838,
"text": "color: determines the color of point or errorbar"
},
{
"code": null,
"e": 29931,
"s": 29887,
"text": "lwd: determines the line width of error bar"
},
{
"code": null,
"e": 29967,
"s": 29931,
"text": "pch: determines the shape of point."
},
{
"code": null,
"e": 29976,
"s": 29967,
"text": "Example:"
},
{
"code": null,
"e": 30022,
"s": 29976,
"text": "Here, is a completely customized forest plot."
},
{
"code": null,
"e": 30024,
"s": 30022,
"text": "R"
},
{
"code": "# create sample datasample_data <- data.frame(study=c('G1', 'G2', 'G3', 'G4', 'G5'), index=1:5, result=c(-.23, -.45, -.16, .6, .65), error_lower=c(-.35, -.59, -.37, -.12, .24), error_upper=c(-.17, -.25, -.03, .82, .91)) #load library ggplot2library(ggplot2) #create forest plotggplot(data=sample_data, aes(y=index, x=result, xmin=error_lower, xmax=error_upper)) + geom_errorbarh(height=.1, color= \"green\", lwd=1.2) + geom_point( color= \"red\", pch= 9, size=3) + scale_y_continuous(labels=sample_data$study)+ labs(title=\"Forest Plot\")+ geom_vline(xintercept=0, color='blue', linetype='dashed', alpha=.5)",
"e": 30756,
"s": 30024,
"text": null
},
{
"code": null,
"e": 30764,
"s": 30756,
"text": "Output:"
},
{
"code": null,
"e": 30771,
"s": 30764,
"text": "Picked"
},
{
"code": null,
"e": 30780,
"s": 30771,
"text": "R-Charts"
},
{
"code": null,
"e": 30789,
"s": 30780,
"text": "R-Graphs"
},
{
"code": null,
"e": 30797,
"s": 30789,
"text": "R-plots"
},
{
"code": null,
"e": 30808,
"s": 30797,
"text": "R Language"
},
{
"code": null,
"e": 30906,
"s": 30808,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30915,
"s": 30906,
"text": "Comments"
},
{
"code": null,
"e": 30928,
"s": 30915,
"text": "Old Comments"
},
{
"code": null,
"e": 30980,
"s": 30928,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 31004,
"s": 30980,
"text": "Data Visualization in R"
},
{
"code": null,
"e": 31042,
"s": 31004,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 31077,
"s": 31042,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 31114,
"s": 31077,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 31172,
"s": 31114,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 31208,
"s": 31172,
"text": "Control Statements in R Programming"
},
{
"code": null,
"e": 31245,
"s": 31208,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 31288,
"s": 31245,
"text": "Replace Specific Characters in String in R"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.