title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
What is difference between internal and private modifiers in C#?
Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly. Any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined. The following is an example − using System; namespace RectangleApplication { class Rectangle { //member variables internal double length; internal double width; double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } }//end class Rectangle class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.length = 4.5; r.width = 3.5; r.Display(); Console.ReadLine(); } } } Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. The following is an example − using System; namespace RectangleApplication { class Rectangle { private double length; private double width; public void Acceptdetails() { length = 10; width = 15; } public double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } } class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.Acceptdetails(); r.Display(); Console.ReadLine(); } } }
[ { "code": null, "e": 1211, "s": 1062, "text": "Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly." }, { "code": null, "e": 1357, "s": 1211, "text": "Any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined." }, { "code": null, "e": 1387, "s": 1357, "text": "The following is an example −" }, { "code": null, "e": 2047, "s": 1387, "text": "using System;\n\nnamespace RectangleApplication {\n class Rectangle {\n //member variables\n internal double length;\n internal double width;\n\n double GetArea() {\n return length * width;\n }\n\n public void Display() {\n Console.WriteLine(\"Length: {0}\", length);\n Console.WriteLine(\"Width: {0}\", width);\n Console.WriteLine(\"Area: {0}\", GetArea());\n }\n }//end class Rectangle\n\n class ExecuteRectangle {\n static void Main(string[] args) {\n Rectangle r = new Rectangle();\n r.length = 4.5;\n r.width = 3.5;\n r.Display();\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2236, "s": 2047, "text": "Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members." }, { "code": null, "e": 2266, "s": 2236, "text": "The following is an example −" }, { "code": null, "e": 2952, "s": 2266, "text": "using System;\n\nnamespace RectangleApplication {\n class Rectangle {\n private double length;\n private double width;\n\n public void Acceptdetails() {\n length = 10;\n width = 15;\n }\n\n public double GetArea() {\n return length * width;\n }\n\n public void Display() {\n Console.WriteLine(\"Length: {0}\", length);\n Console.WriteLine(\"Width: {0}\", width);\n Console.WriteLine(\"Area: {0}\", GetArea());\n }\n }\n\n class ExecuteRectangle {\n static void Main(string[] args) {\n Rectangle r = new Rectangle();\n r.Acceptdetails();\n r.Display();\n Console.ReadLine();\n }\n }\n}" } ]
Convert JSON array into normal json in JavaScript
Suppose, we have a JSON array with key/value pair objects like this − const arr = [{ "key": "name", "value": "john" }, { "key": "number", "value": "1234" }, { "key": "price", "value": [{ "item": [{ "item": [{ "key": "quantity", "value": "20" }, { "key": "price", "value": "200" }] }] }] }]; We are required to write a JavaScript function that takes in one such array. The function should prepare a new array where data is simply listed against key value instead of this complex structure. Therefore, for the above array, the output should look like this − const output = { "name": "john", "number": "1234", "price": { "quantity": "20", "price": "200" } }; The code for this will be − const arr = [{ "key": "name", "value": "john" }, { "key": "number", "value": "1234" }, { "key": "price", "value": [{ "item": [{ "item": [{ "key": "quantity", "value": "20" }, { "key": "price", "value": "200" }] }] }] }]; const simplify = (arr = []) => { const res = {}; const recursiveEmbed = function(el){ if ('item' in el) { el.item.forEach(recursiveEmbed, this); return; }; if (Array.isArray(el.value)) { this[el.key] = {}; el.value.forEach(recursiveEmbed, this[el.key]); return; }; this[el.key] = el.value; }; arr.forEach(recursiveEmbed, res); return res; }; console.log(simplify(arr)); And the output in the console will be − { name: 'john', number: '1234', price: { quantity: '20', price: '200' } }
[ { "code": null, "e": 1132, "s": 1062, "text": "Suppose, we have a JSON array with key/value pair objects like this −" }, { "code": null, "e": 1470, "s": 1132, "text": "const arr = [{\n \"key\": \"name\",\n \"value\": \"john\"\n},\n{\n \"key\": \"number\",\n \"value\": \"1234\"\n},\n{\n \"key\": \"price\",\n \"value\": [{\n \"item\": [{\n \"item\": [{\n \"key\": \"quantity\",\n \"value\": \"20\"\n },\n {\n \"key\": \"price\",\n \"value\": \"200\"\n }]\n }]\n }]\n}];" }, { "code": null, "e": 1547, "s": 1470, "text": "We are required to write a JavaScript function that takes in one such array." }, { "code": null, "e": 1668, "s": 1547, "text": "The function should prepare a new array where data is simply listed against key value instead of this complex structure." }, { "code": null, "e": 1735, "s": 1668, "text": "Therefore, for the above array, the output should look like this −" }, { "code": null, "e": 1859, "s": 1735, "text": "const output = {\n \"name\": \"john\",\n \"number\": \"1234\",\n \"price\": {\n \"quantity\": \"20\",\n \"price\": \"200\"\n }\n};" }, { "code": null, "e": 1887, "s": 1859, "text": "The code for this will be −" }, { "code": null, "e": 2685, "s": 1887, "text": "const arr = [{\n \"key\": \"name\",\n \"value\": \"john\"\n},\n{\n \"key\": \"number\",\n \"value\": \"1234\"\n},\n{\n \"key\": \"price\",\n \"value\": [{\n \"item\": [{\n \"item\": [{\n \"key\": \"quantity\",\n \"value\": \"20\"\n },\n {\n \"key\": \"price\",\n \"value\": \"200\"\n }]\n }]\n }]\n}];\nconst simplify = (arr = []) => {\n const res = {};\n const recursiveEmbed = function(el){\n if ('item' in el) {\n el.item.forEach(recursiveEmbed, this);\n return;\n };\n if (Array.isArray(el.value)) {\n this[el.key] = {};\n el.value.forEach(recursiveEmbed, this[el.key]);\n return;\n };\n this[el.key] = el.value;\n };\n arr.forEach(recursiveEmbed, res);\n return res;\n};\nconsole.log(simplify(arr));" }, { "code": null, "e": 2725, "s": 2685, "text": "And the output in the console will be −" }, { "code": null, "e": 2808, "s": 2725, "text": "{\n name: 'john',\n number: '1234',\n price: { quantity: '20', price: '200' }\n}" } ]
Simulated Annealing and the Eight Queen Problem | by Sebastián Gerard Aguilar Kleimann | Towards Data Science
The Simulated Annealing (SA) algorithm is one of many random optimization algorithms. Unlike algorithms like the Hill Climbing algorithm where the intent is to only improve the optimization, SA allows for more exploration. The idea is that with this exploration it’s more likely to reach a global optima rather than a local optima (for more on local optima, global optima and the Hill Climbing Optimization algorithm follow this link). The term “annealing” is a term used in mettalurgy where the objective is to lower and increase the temperature of a metal. The process allows for the molecules to regroupe and get closer every time so that the metal becomes harder. The analogy is applied on the SA algorithm by getting closer to a solution, going farther from it by doing exploration and getting closer again to an even better solution. The algorithm can be decomposed in 4 simple steps: Start at a random point x.Choose a new point xj on a neighborhood N(x).Decide whether or not to move to the new point xj. The decision will be made based on the probability function P(x,xj,T) (explained ahead).Reduce T Start at a random point x. Choose a new point xj on a neighborhood N(x). Decide whether or not to move to the new point xj. The decision will be made based on the probability function P(x,xj,T) (explained ahead). Reduce T Like we mentioned before P(x,xj,T) is the function that will guide us on whether we move to the new point or not: Let’s explore what the function is telling us. F(x) is the objective function (the function for which we want to find the optimal point x). If the new point xj improves the result of the objective function, we will move to the new point with probability 1. When the new point doesn’t improve the objective function, we will move to the new point depending on the difference of F(xj)-F(x) and the variable T. When T is high the possibility of moving to the new point will also be high and when T is low the possibility of moving to the new point is also low. That’s why initially we’ll start with a high T to do more exploration, and gradually lower the value of T to reach the optimal point. Now that we know how the algorithm works it’s time to perform an example using python in order to take our understanding further. The eight queen problem consists in positioning 8 queens in an 8*8 table board without any of them being on the line of attack between each other. Queens can move horizontally, diagonally and vertically as seen in Image 1.1. Finding the solution to the problem is not easy since a great number of combinations exist. We can see some solutions in image 1.2 were only 6 and 7 queens were positioned in the board. Now that we understand the problem let’s go to python code and solve it. In python there exists a library called “mlrose” that is very helpful for implementing random optimization algorithms so the first few lines of code will be used to import this library as well as the numpy library that helps us handle arrays. ### Importing the necessary librariesimport mlroseimport numpy as np The next step is defining the objective function. The objective function will count the number of queens that are positioned in a place where they cannot be attacked. Given that queens move vertically, it’s reasonable to say that no queen should be placed in the same vertical and thus we can represent the position of each queen in a simple array of 8 positions. For example, in a chess board an array A=[0,2,1,3,7,4,5,6] would look like Image 2.1. Now it is time to code the objective function: ###Defining the objective functiondef queens_max(position): # We start the count no_attack_on_j = 0 queen_not_attacking=0 # Compare for each pair of queens for i in range(len(position) - 1): no_attack_on_j=0 for j in range(i + 1, len(position)): ### Check if there is any diagonal or horizontal attack. ###Iterative process for each column if (position[j] != position[i]) and (position[j] != position[i] + (j - i)) and (position[j] != position[i] - (j - i)): """If there isn't any attack on the evaluated column. The count is increased by one. This counter is only used as a reference .""" no_attack_on_j += 1 """If there is no attack on all the columns. The general counter is increased by one. This counter indicates the number of queens that are correctly positioned.""" if(no_attack_on_j==len(position)-1-i): queen_not_attacking+=1 """The return number is the number of queens not attacking each other. If this number is 7 we add 1 cause it means the last queen is also free of attack.""" if(queen_not_attacking==7): queen_not_attacking+=1 return queen_not_attacking The objective function previously defined is assigned as an argument to the method “CustomFitness” in mlrose. That’s how any objective function can work with this library. # Assign the objective function to "CustomFitness" method.objective= mlrose.CustomFitness(queens_max) Now, we finished the tricky part. The only thing remaining is to tell mlrose the type of problem is has to solve. The problem we are solving has discrete numbers (whole numbers) that’s why we’ll use the method “DiscreteOpt”. This method will hold the decription of the problem and it has 4 arguments: length- The size of the array we are working with (for the eight queen problem it’s 8).fitness_fn- The objective function we previously defined with the name “objective”.maximize-It must be “True” if we want to maximize the objective function and “False” otherwise.max_val- This parameter indicates the maximum value the function can take. It starts in 0 and ends in max_val-1. In our case the queen can be positioned from 0 to 7 so max_val=8. length- The size of the array we are working with (for the eight queen problem it’s 8). fitness_fn- The objective function we previously defined with the name “objective”. maximize-It must be “True” if we want to maximize the objective function and “False” otherwise. max_val- This parameter indicates the maximum value the function can take. It starts in 0 and ends in max_val-1. In our case the queen can be positioned from 0 to 7 so max_val=8. The line of code: #Description of the problemproblem = mlrose.DiscreteOpt(length = 8, fitness_fn = objective, maximize = True, max_val = 8) Finally, it’s time to tell mlrose how to solve the problem. We know we are going to use Simulated Annealing(SA) and it’s important to specify 5 parameters. problem-This parameter contains the information of the problem. We defined it earlier with the name “problem”.schedule-This parameter tells T how to decrease over each iteration. There are many ways to decrease T and it’s possible to check them on mlrose. This time T will be decreased exponentially using ExpDecay().max_attempts- It’s important to define the number of attempts the algorithm will try to search for a better solution. If the number of attempts reaches the maximum it should stop.max_iter-It indicates the maximum number of new points the algorithm can find or the maximum number of iteration it does.init_state-The parameter “init_state” is the inital position of the array. problem-This parameter contains the information of the problem. We defined it earlier with the name “problem”. schedule-This parameter tells T how to decrease over each iteration. There are many ways to decrease T and it’s possible to check them on mlrose. This time T will be decreased exponentially using ExpDecay(). max_attempts- It’s important to define the number of attempts the algorithm will try to search for a better solution. If the number of attempts reaches the maximum it should stop. max_iter-It indicates the maximum number of new points the algorithm can find or the maximum number of iteration it does. init_state-The parameter “init_state” is the inital position of the array. The last chunk of code looks like this: # Define decay scheduleT = mlrose.ExpDecay()# Define initial stateinitial_position = np.array([4, 6, 1, 5, 2, 0, 3, 7])# Solve problem using simulated annealingbest_position, best_objective = mlrose.simulated_annealing(problem=problem, schedule = T,max_attempts = 500, max_iters = 5000,init_state = initial_position)print('The best position found is: ', best_position)print('The number of queens that are not attacking each other is: ', best_objective)Output:The best position found is: [4 6 1 5 2 0 3 7]The number of queens that are not attacking each other is: 8.0 We solved the 8 queen problem succesfully as seen on Image 2.2 I hope you enjoyed the article and play with the eight queen problem. I leave you the code on google colab and github. It’s possible to run this code and with a few tweaks even solve the 9,10...n queen problem. # -*- coding: utf-8 -*- """ Created on Mon Aug 24 18:23:36 2020 @author: saguilark """ ### Install library !pip install mlrose ### Import necessary libraries import mlrose import numpy as np ###Defining the objective function def queens_max(position): # We start the count no_attack_on_j = 0 queen_not_attacking=0 # Compare for each pair of queens for i in range(len(position) - 1): no_attack_on_j=0 for j in range(i + 1, len(position)): ### Check if there is any diagonal or horizontal attack. ###Iterative process for each column if (position[j] != position[i]) and (position[j] != position[i] + (j - i)) and (position[j] != position[i] - (j - i)): """If there isn't any attack on the evaluated column. The count is increased by one. This counter is only used as a reference .""" no_attack_on_j += 1 """If there is no attack on all the columns. The general counter is increased by one. This counter indicates the number of queens that are correctly positioned.""" if(no_attack_on_j==len(position)-1-i): queen_not_attacking+=1 """The return number is the number of queens not attacking each other if this number is 7 we add one cause it means the last queen is also free of attack.""" if(queen_not_attacking==7): queen_not_attacking+=1 return queen_not_attacking # Assign the objective function to "CustomFitness" method. objective = mlrose.CustomFitness(queens_max) #Description of the problem problem = mlrose.DiscreteOpt(length = 8, fitness_fn = objective, maximize = True, max_val = 8) # Define decay schedule T = mlrose.ExpDecay() # Define initial state initial_position = np.array([4, 6, 1, 5, 2, 0, 3, 7]) # Solve problem using simulated annealing best_position, best_objective = mlrose.simulated_annealing(problem=problem, schedule = T, max_attempts = 500, max_iters = 5000, init_state = initial_position) print('The best position found is: ', best_position) print('The number of queens that are not attacking each other is: ', best_objective) Requirement already satisfied: mlrose in /usr/local/lib/python3.6/dist-packages (1.3.0) Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from mlrose) (1.4.1) Requirement already satisfied: sklearn in /usr/local/lib/python3.6/dist-packages (from mlrose) (0.0) Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from mlrose) (1.18.5) Requirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from sklearn->mlrose) (0.22.2.post1) Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->sklearn->mlrose) (0.16.0) The best position found is: [2 7 3 6 0 5 1 4] The number of queens that are not attacking each other is: 8.0 Bibliography: Machine Learning, Randomized Optimization and SEarch¶. (n.d.). Retrieved August 13, 2020, from https://mlrose.readthedocs.io/en/stable/ Brain Training. (n.d.). Retrieved August 13, 2020, from http://www.brainmetrix.com/8-queens/ Eight Queens. (n.d.). Retrieved September 10, 2020, from http://www.datagenetics.com/blog/august42012/ Originally published at https://www.estudiodedatos.com on August 25, 2020.
[ { "code": null, "e": 608, "s": 172, "text": "The Simulated Annealing (SA) algorithm is one of many random optimization algorithms. Unlike algorithms like the Hill Climbing algorithm where the intent is to only improve the optimization, SA allows for more exploration. The idea is that with this exploration it’s more likely to reach a global optima rather than a local optima (for more on local optima, global optima and the Hill Climbing Optimization algorithm follow this link)." }, { "code": null, "e": 1012, "s": 608, "text": "The term “annealing” is a term used in mettalurgy where the objective is to lower and increase the temperature of a metal. The process allows for the molecules to regroupe and get closer every time so that the metal becomes harder. The analogy is applied on the SA algorithm by getting closer to a solution, going farther from it by doing exploration and getting closer again to an even better solution." }, { "code": null, "e": 1063, "s": 1012, "text": "The algorithm can be decomposed in 4 simple steps:" }, { "code": null, "e": 1282, "s": 1063, "text": "Start at a random point x.Choose a new point xj on a neighborhood N(x).Decide whether or not to move to the new point xj. The decision will be made based on the probability function P(x,xj,T) (explained ahead).Reduce T" }, { "code": null, "e": 1309, "s": 1282, "text": "Start at a random point x." }, { "code": null, "e": 1355, "s": 1309, "text": "Choose a new point xj on a neighborhood N(x)." }, { "code": null, "e": 1495, "s": 1355, "text": "Decide whether or not to move to the new point xj. The decision will be made based on the probability function P(x,xj,T) (explained ahead)." }, { "code": null, "e": 1504, "s": 1495, "text": "Reduce T" }, { "code": null, "e": 1618, "s": 1504, "text": "Like we mentioned before P(x,xj,T) is the function that will guide us on whether we move to the new point or not:" }, { "code": null, "e": 1875, "s": 1618, "text": "Let’s explore what the function is telling us. F(x) is the objective function (the function for which we want to find the optimal point x). If the new point xj improves the result of the objective function, we will move to the new point with probability 1." }, { "code": null, "e": 2026, "s": 1875, "text": "When the new point doesn’t improve the objective function, we will move to the new point depending on the difference of F(xj)-F(x) and the variable T." }, { "code": null, "e": 2310, "s": 2026, "text": "When T is high the possibility of moving to the new point will also be high and when T is low the possibility of moving to the new point is also low. That’s why initially we’ll start with a high T to do more exploration, and gradually lower the value of T to reach the optimal point." }, { "code": null, "e": 2440, "s": 2310, "text": "Now that we know how the algorithm works it’s time to perform an example using python in order to take our understanding further." }, { "code": null, "e": 2665, "s": 2440, "text": "The eight queen problem consists in positioning 8 queens in an 8*8 table board without any of them being on the line of attack between each other. Queens can move horizontally, diagonally and vertically as seen in Image 1.1." }, { "code": null, "e": 2851, "s": 2665, "text": "Finding the solution to the problem is not easy since a great number of combinations exist. We can see some solutions in image 1.2 were only 6 and 7 queens were positioned in the board." }, { "code": null, "e": 2924, "s": 2851, "text": "Now that we understand the problem let’s go to python code and solve it." }, { "code": null, "e": 3167, "s": 2924, "text": "In python there exists a library called “mlrose” that is very helpful for implementing random optimization algorithms so the first few lines of code will be used to import this library as well as the numpy library that helps us handle arrays." }, { "code": null, "e": 3236, "s": 3167, "text": "### Importing the necessary librariesimport mlroseimport numpy as np" }, { "code": null, "e": 3686, "s": 3236, "text": "The next step is defining the objective function. The objective function will count the number of queens that are positioned in a place where they cannot be attacked. Given that queens move vertically, it’s reasonable to say that no queen should be placed in the same vertical and thus we can represent the position of each queen in a simple array of 8 positions. For example, in a chess board an array A=[0,2,1,3,7,4,5,6] would look like Image 2.1." }, { "code": null, "e": 3733, "s": 3686, "text": "Now it is time to code the objective function:" }, { "code": null, "e": 5076, "s": 3733, "text": "###Defining the objective functiondef queens_max(position): # We start the count no_attack_on_j = 0 queen_not_attacking=0 # Compare for each pair of queens for i in range(len(position) - 1): no_attack_on_j=0 for j in range(i + 1, len(position)): ### Check if there is any diagonal or horizontal attack. ###Iterative process for each column if (position[j] != position[i]) and (position[j] != position[i] + (j - i)) and (position[j] != position[i] - (j - i)): \"\"\"If there isn't any attack on the evaluated column. The count is increased by one. This counter is only used as a reference .\"\"\" no_attack_on_j += 1 \"\"\"If there is no attack on all the columns. The general counter is increased by one. This counter indicates the number of queens that are correctly positioned.\"\"\" if(no_attack_on_j==len(position)-1-i): queen_not_attacking+=1 \"\"\"The return number is the number of queens not attacking each other. If this number is 7 we add 1 cause it means the last queen is also free of attack.\"\"\" if(queen_not_attacking==7): queen_not_attacking+=1 return queen_not_attacking" }, { "code": null, "e": 5248, "s": 5076, "text": "The objective function previously defined is assigned as an argument to the method “CustomFitness” in mlrose. That’s how any objective function can work with this library." }, { "code": null, "e": 5350, "s": 5248, "text": "# Assign the objective function to \"CustomFitness\" method.objective= mlrose.CustomFitness(queens_max)" }, { "code": null, "e": 5651, "s": 5350, "text": "Now, we finished the tricky part. The only thing remaining is to tell mlrose the type of problem is has to solve. The problem we are solving has discrete numbers (whole numbers) that’s why we’ll use the method “DiscreteOpt”. This method will hold the decription of the problem and it has 4 arguments:" }, { "code": null, "e": 6095, "s": 5651, "text": "length- The size of the array we are working with (for the eight queen problem it’s 8).fitness_fn- The objective function we previously defined with the name “objective”.maximize-It must be “True” if we want to maximize the objective function and “False” otherwise.max_val- This parameter indicates the maximum value the function can take. It starts in 0 and ends in max_val-1. In our case the queen can be positioned from 0 to 7 so max_val=8." }, { "code": null, "e": 6183, "s": 6095, "text": "length- The size of the array we are working with (for the eight queen problem it’s 8)." }, { "code": null, "e": 6267, "s": 6183, "text": "fitness_fn- The objective function we previously defined with the name “objective”." }, { "code": null, "e": 6363, "s": 6267, "text": "maximize-It must be “True” if we want to maximize the objective function and “False” otherwise." }, { "code": null, "e": 6542, "s": 6363, "text": "max_val- This parameter indicates the maximum value the function can take. It starts in 0 and ends in max_val-1. In our case the queen can be positioned from 0 to 7 so max_val=8." }, { "code": null, "e": 6560, "s": 6542, "text": "The line of code:" }, { "code": null, "e": 6682, "s": 6560, "text": "#Description of the problemproblem = mlrose.DiscreteOpt(length = 8, fitness_fn = objective, maximize = True, max_val = 8)" }, { "code": null, "e": 6838, "s": 6682, "text": "Finally, it’s time to tell mlrose how to solve the problem. We know we are going to use Simulated Annealing(SA) and it’s important to specify 5 parameters." }, { "code": null, "e": 7530, "s": 6838, "text": "problem-This parameter contains the information of the problem. We defined it earlier with the name “problem”.schedule-This parameter tells T how to decrease over each iteration. There are many ways to decrease T and it’s possible to check them on mlrose. This time T will be decreased exponentially using ExpDecay().max_attempts- It’s important to define the number of attempts the algorithm will try to search for a better solution. If the number of attempts reaches the maximum it should stop.max_iter-It indicates the maximum number of new points the algorithm can find or the maximum number of iteration it does.init_state-The parameter “init_state” is the inital position of the array." }, { "code": null, "e": 7641, "s": 7530, "text": "problem-This parameter contains the information of the problem. We defined it earlier with the name “problem”." }, { "code": null, "e": 7849, "s": 7641, "text": "schedule-This parameter tells T how to decrease over each iteration. There are many ways to decrease T and it’s possible to check them on mlrose. This time T will be decreased exponentially using ExpDecay()." }, { "code": null, "e": 8029, "s": 7849, "text": "max_attempts- It’s important to define the number of attempts the algorithm will try to search for a better solution. If the number of attempts reaches the maximum it should stop." }, { "code": null, "e": 8151, "s": 8029, "text": "max_iter-It indicates the maximum number of new points the algorithm can find or the maximum number of iteration it does." }, { "code": null, "e": 8226, "s": 8151, "text": "init_state-The parameter “init_state” is the inital position of the array." }, { "code": null, "e": 8266, "s": 8226, "text": "The last chunk of code looks like this:" }, { "code": null, "e": 8833, "s": 8266, "text": "# Define decay scheduleT = mlrose.ExpDecay()# Define initial stateinitial_position = np.array([4, 6, 1, 5, 2, 0, 3, 7])# Solve problem using simulated annealingbest_position, best_objective = mlrose.simulated_annealing(problem=problem, schedule = T,max_attempts = 500, max_iters = 5000,init_state = initial_position)print('The best position found is: ', best_position)print('The number of queens that are not attacking each other is: ', best_objective)Output:The best position found is: [4 6 1 5 2 0 3 7]The number of queens that are not attacking each other is: 8.0" }, { "code": null, "e": 8896, "s": 8833, "text": "We solved the 8 queen problem succesfully as seen on Image 2.2" }, { "code": null, "e": 9107, "s": 8896, "text": "I hope you enjoyed the article and play with the eight queen problem. I leave you the code on google colab and github. It’s possible to run this code and with a few tweaks even solve the 9,10...n queen problem." }, { "code": null, "e": 11374, "s": 9107, "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 24 18:23:36 2020\n\n@author: saguilark\n\"\"\"\n### Install library\n!pip install mlrose\n### Import necessary libraries\nimport mlrose\nimport numpy as np\n\n\n\n###Defining the objective function\ndef queens_max(position):\n\n # We start the count\n no_attack_on_j = 0\n queen_not_attacking=0\n # Compare for each pair of queens\n for i in range(len(position) - 1): \n no_attack_on_j=0\n for j in range(i + 1, len(position)):\n\n ### Check if there is any diagonal or horizontal attack.\n ###Iterative process for each column\n if (position[j] != position[i]) and (position[j] != position[i] + (j - i)) and (position[j] != position[i] - (j - i)):\n\n \"\"\"If there isn't any attack on the evaluated column.\n The count is increased by one. \n This counter is only used as a reference .\"\"\"\n no_attack_on_j += 1\n\n \"\"\"If there is no attack on all the columns.\n The general counter is increased by one.\n This counter indicates the number of queens that are correctly\n positioned.\"\"\"\n if(no_attack_on_j==len(position)-1-i):\n queen_not_attacking+=1\n \"\"\"The return number is the number of queens not attacking each\n other if this number is 7 we add one cause it means the last\n queen is also free of attack.\"\"\"\n if(queen_not_attacking==7):\n queen_not_attacking+=1\n return queen_not_attacking\n\n# Assign the objective function to \"CustomFitness\" method.\nobjective = mlrose.CustomFitness(queens_max) \n\n#Description of the problem\nproblem = mlrose.DiscreteOpt(length = 8, fitness_fn = objective, maximize = True, max_val = 8)\n\n\n# Define decay schedule\nT = mlrose.ExpDecay()\n# Define initial state\ninitial_position = np.array([4, 6, 1, 5, 2, 0, 3, 7])\n# Solve problem using simulated annealing\nbest_position, best_objective = mlrose.simulated_annealing(problem=problem, schedule = T,\nmax_attempts = 500, max_iters = 5000,\ninit_state = initial_position)\nprint('The best position found is: ', best_position)\nprint('The number of queens that are not attacking each other is: ', best_objective)\n" }, { "code": null, "e": 12134, "s": 11374, "text": "Requirement already satisfied: mlrose in /usr/local/lib/python3.6/dist-packages (1.3.0)\nRequirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from mlrose) (1.4.1)\nRequirement already satisfied: sklearn in /usr/local/lib/python3.6/dist-packages (from mlrose) (0.0)\nRequirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from mlrose) (1.18.5)\nRequirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from sklearn->mlrose) (0.22.2.post1)\nRequirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->sklearn->mlrose) (0.16.0)\nThe best position found is: [2 7 3 6 0 5 1 4]\nThe number of queens that are not attacking each other is: 8.0\n" }, { "code": null, "e": 12148, "s": 12134, "text": "Bibliography:" }, { "code": null, "e": 12284, "s": 12148, "text": "Machine Learning, Randomized Optimization and SEarch¶. (n.d.). Retrieved August 13, 2020, from https://mlrose.readthedocs.io/en/stable/" }, { "code": null, "e": 12377, "s": 12284, "text": "Brain Training. (n.d.). Retrieved August 13, 2020, from http://www.brainmetrix.com/8-queens/" }, { "code": null, "e": 12480, "s": 12377, "text": "Eight Queens. (n.d.). Retrieved September 10, 2020, from http://www.datagenetics.com/blog/august42012/" } ]
Material Design Lite - Badges
An MDL badge component is an onscreen notification which can be a number or an icon. It is generally used to emphasize the number of items. MDL provides a range of CSS classes to apply various predefined visual and behavioral enhancements to the badges. The following table lists down the available classes and their effects. mdl-badge Identifies element as an MDL badge component. Required for span or link element. mdl-badge--no-background Applies open-circle effect to badge and is optional. mdl-badge--overlap Makes the badge overlap with its container and is optional. data-badge="value" Assigns a string value to badge used as attribute; required on span or link. The following example will help you understand the use of the mdl-badge class to add notifications to span and link elements. The MDL classes given below will be used in this example. mdl-badge − Identifies element as an MDL badge component. mdl-badge − Identifies element as an MDL badge component. data-badge − Assigns a string value to badge. Icons can be assigned to it using HTML symbols. data-badge − Assigns a string value to badge. Icons can be assigned to it using HTML symbols. <html> <head> <script src = "https://storage.googleapis.com/code.getmdl.io/1.0.6/material.min.js"> </script> <link rel = "stylesheet" href = "https://storage.googleapis.com/code.getmdl.io/1.0.6/material.indigo-pink.min.css"> <link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons"> <style> body { padding: 20px; background: #fafafa; position: relative; } </style> </head> <body> <span class = "material-icons mdl-badge" data-badge = "1">account_box</span> <span class = "material-icons mdl-badge" data-badge = "★">account_box</span> <span class = "mdl-badge" data-badge = "4">Unread Messages</span> <span class = "mdl-badge" data-badge = "⚑">Rating</span> <a href = "#" class = "mdl-badge" data-badge = "5">Inbox</a> </body> </html> Verify the result. Print Add Notes Bookmark this page
[ { "code": null, "e": 2026, "s": 1886, "text": "An MDL badge component is an onscreen notification which can be a number or an icon. It is generally used to emphasize the number of items." }, { "code": null, "e": 2212, "s": 2026, "text": "MDL provides a range of CSS classes to apply various predefined visual and behavioral\nenhancements to the badges. The following table lists down the available classes and their\neffects." }, { "code": null, "e": 2222, "s": 2212, "text": "mdl-badge" }, { "code": null, "e": 2303, "s": 2222, "text": "Identifies element as an MDL badge component. Required for span or link element." }, { "code": null, "e": 2328, "s": 2303, "text": "mdl-badge--no-background" }, { "code": null, "e": 2381, "s": 2328, "text": "Applies open-circle effect to badge and is optional." }, { "code": null, "e": 2400, "s": 2381, "text": "mdl-badge--overlap" }, { "code": null, "e": 2460, "s": 2400, "text": "Makes the badge overlap with its container and is optional." }, { "code": null, "e": 2479, "s": 2460, "text": "data-badge=\"value\"" }, { "code": null, "e": 2556, "s": 2479, "text": "Assigns a string value to badge\tused as attribute; required on span or link." }, { "code": null, "e": 2682, "s": 2556, "text": "The following example will help you understand the use of the mdl-badge class to add notifications to span and link elements." }, { "code": null, "e": 2740, "s": 2682, "text": "The MDL classes given below will be used in this example." }, { "code": null, "e": 2798, "s": 2740, "text": "mdl-badge − Identifies element as an MDL badge component." }, { "code": null, "e": 2856, "s": 2798, "text": "mdl-badge − Identifies element as an MDL badge component." }, { "code": null, "e": 2950, "s": 2856, "text": "data-badge − Assigns a string value to badge. Icons can be assigned to it using HTML symbols." }, { "code": null, "e": 3044, "s": 2950, "text": "data-badge − Assigns a string value to badge. Icons can be assigned to it using HTML symbols." }, { "code": null, "e": 3979, "s": 3044, "text": "<html>\n <head>\n <script src = \"https://storage.googleapis.com/code.getmdl.io/1.0.6/material.min.js\">\n </script>\n \n <link rel = \"stylesheet\" \n href = \"https://storage.googleapis.com/code.getmdl.io/1.0.6/material.indigo-pink.min.css\">\n <link rel = \"stylesheet\" \n href = \"https://fonts.googleapis.com/icon?family=Material+Icons\">\n <style>\n body {\n padding: 20px;\n background: #fafafa;\n position: relative;\n }\n </style>\n </head>\n \n <body>\n <span class = \"material-icons mdl-badge\" data-badge = \"1\">account_box</span> \n <span class = \"material-icons mdl-badge\" data-badge = \"★\">account_box</span>\t\n <span class = \"mdl-badge\" data-badge = \"4\">Unread Messages</span>\n <span class = \"mdl-badge\" data-badge = \"⚑\">Rating</span>\n <a href = \"#\" class = \"mdl-badge\" data-badge = \"5\">Inbox</a>\n </body>\n</html>" }, { "code": null, "e": 3998, "s": 3979, "text": "Verify the result." }, { "code": null, "e": 4005, "s": 3998, "text": " Print" }, { "code": null, "e": 4016, "s": 4005, "text": " Add Notes" } ]
fputs() function in PHP
Write to an open file using the fpus() function in PHP. It is an alias of fwrite(). The fputs() function returns the number of bytes written on success. It returns FALSE on failure. The fputs() function halts at the end of the file or when it reaches the specified length whichever comes first. fputs(file_pointer, string, length) file_pointer − A file pointer created using fopen(). Required. file_pointer − A file pointer created using fopen(). Required. string − A string to be written. Required. string − A string to be written. Required. length − Maximum bytes to write. Optional. length − Maximum bytes to write. Optional. The fputs() function returns the number of bytes written on success. It returns FALSE on failure. <?php $file_pointer = fopen("new.txt","w"); echo fputs($file,"This is demo text!"); fclose($file_pointer); ?> The following is the output. It returns the number of bytes written. 18 Let us see another example which writes a specified number of bytes to the file. The content is also read and displayed. <?php $file_pointer = fopen("new.txt","w"); echo fputs($file,"This is demo text!",4); fclose($file_pointer); fopen("new.txt", "r"); echo fread($file_pointer, filesize("new.txt")); fclose($file_pointer); ?> 4
[ { "code": null, "e": 1244, "s": 1062, "text": "Write to an open file using the fpus() function in PHP. It is an alias of fwrite(). The fputs() function returns the number of bytes written on success. It returns FALSE on failure." }, { "code": null, "e": 1357, "s": 1244, "text": "The fputs() function halts at the end of the file or when it reaches the specified length whichever comes first." }, { "code": null, "e": 1393, "s": 1357, "text": "fputs(file_pointer, string, length)" }, { "code": null, "e": 1456, "s": 1393, "text": "file_pointer − A file pointer created using fopen(). Required." }, { "code": null, "e": 1519, "s": 1456, "text": "file_pointer − A file pointer created using fopen(). Required." }, { "code": null, "e": 1562, "s": 1519, "text": "string − A string to be written. Required." }, { "code": null, "e": 1605, "s": 1562, "text": "string − A string to be written. Required." }, { "code": null, "e": 1648, "s": 1605, "text": "length − Maximum bytes to write. Optional." }, { "code": null, "e": 1691, "s": 1648, "text": "length − Maximum bytes to write. Optional." }, { "code": null, "e": 1789, "s": 1691, "text": "The fputs() function returns the number of bytes written on success. It returns FALSE on failure." }, { "code": null, "e": 1908, "s": 1789, "text": "<?php\n $file_pointer = fopen(\"new.txt\",\"w\");\n echo fputs($file,\"This is demo text!\");\n fclose($file_pointer);\n?>" }, { "code": null, "e": 1977, "s": 1908, "text": "The following is the output. It returns the number of bytes written." }, { "code": null, "e": 1980, "s": 1977, "text": "18" }, { "code": null, "e": 2101, "s": 1980, "text": "Let us see another example which writes a specified number of bytes to the file. The content is also read and displayed." }, { "code": null, "e": 2325, "s": 2101, "text": "<?php\n $file_pointer = fopen(\"new.txt\",\"w\");\n echo fputs($file,\"This is demo text!\",4);\n fclose($file_pointer);\n fopen(\"new.txt\", \"r\");\n echo fread($file_pointer, filesize(\"new.txt\"));\n fclose($file_pointer);\n?>" }, { "code": null, "e": 2327, "s": 2325, "text": "4" } ]
Fine-grained Sentiment Analysis in Python (Part 1) | by Prashanth Rao | Towards Data Science
“Learning to choose is hard. Learning to choose well is harder. And learning to choose well in a world of unlimited possibilities is harder still, perhaps too hard.” — Barry Schwartz When starting a new NLP sentiment analysis project, it can be quite an overwhelming task to narrow down on a select methodology for a given application. Do we use a rule-based model, or do we train a model on our own data? Should we train a neural network, or will a simple linear model meet our requirements? Should we spend the time and effort in implementing our own text classification framework, or can we just use one off-the-shelf? How hard is it to interpret the results and understand why certain predictions were made? This series aims at answering some of the above questions, with a focus on fine-grained sentiment analysis. Through the remaining sections, we’ll compare and discuss classification results using several well-known NLP libraries in Python. The methods described below fall under three broad categories: Rule-based methods: TextBlob: Simple rule-based API for sentiment analysis VADER: Parsimonious rule-based model for sentiment analysis of social media text. Feature-based methods: Logistic Regression: Generalized linear model in Scikit-learn. Support Vector Machine (SVM): Linear model in Scikit-learn with a stochastic gradient descent (SGD) optimizer for gradient loss. Embedding-based methods: FastText: An NLP library that uses highly efficient CPU-based representations of word embeddings for classification tasks. Flair: A PyTorch-based framework for NLP tasks such as sequence tagging and classification. Each approach is implemented in an object-oriented manner in Python, to ensure that we can easily swap out models for experiments and extend the framework with better, more powerful classifiers in the future. In most cases today, sentiment classifiers are used for binary classification (just positive or negative sentiment), and for good reason: fine-grained sentiment classification is a significantly more challenging task! The typical breakdown of fine-grained sentiment uses five discrete classes, as shown below. As one might imagine, models very easily err on either side of the strong/weak sentiment intensities thanks to the wonderful subtleties of human language. Binary class labels may be sufficient for studying large-scale positive/negative sentiment trends in text data such as Tweets, product reviews or customer feedback, but they do have their limitations. When performing information extraction with comparative expressions, for example: “This OnePlus model X is so much better than Samsung model X.” — a fine-grained analysis can provide more precise results to an automated system that prioritizes addressing customer complaints. In addition, dual-polarity sentences such as “The location was truly disgusting ... but the people there were glorious.” can confuse binary sentiment classifiers, leading to incorrect class predictions. The above points provide sufficient motivation to tackle this problem! The Stanford Sentiment Treebank (SST-5, or SST-fine-grained) dataset is a suitable benchmark to test our application, since it was designed to help evaluate a model’s ability to understand representations of sentence structure, rather than just looking at individual words in isolation. SST-5 consists of 11,855 sentences extracted from movie reviews with fine-grained sentiment labels [1–5], as well as 215,154 phrases that compose each sentence in the dataset. The raw data with phrase-based fine-grained sentiment labels is in the form of a tree structure, designed to help train a Recursive Neural Tensor Network (RNTN) from their 2015 paper. The component phrases were constructed by parsing each sentence using the Stanford parser (section 3 in the paper) and creating a recursive tree structure as shown in the below image. A deep neural network was then trained on the tree structure of each sentence to classify the sentiment of each phrase to obtain a cumulative sentiment of the entire sentence. The original RNTN implemented in the Stanford paper [Socher et al.] obtained an accuracy of 45.7% on the full-sentence sentiment classification. More recently, a Bi-attentive Classification Network (BCN) augmented with ELMo embeddings has been used to achieve a significantly higher accuracy of 54.7% on the SST-5 dataset. The current (as of 2019) state-of-the-art accuracy on the SST-5 dataset is 64.4%, by a method that uses sentence-level embeddings originally designed to solve a paraphrasing task — it ended up doing surprisingly well on fine-grained sentiment analysis as well. Although neural language models have been getting increasingly powerful since 2018, it might take far bigger deep learning models (with far more parameters) augmented with knowledge-based methods (such as graphs) to achieve sufficient semantic context for accuracies of 70–80% in fine-grained sentiment analysis. To evaluate our NLP methods and how each one differs from the other, we will use just the complete samples in the training dataset (ignoring the component phrases since we are not using a recursive tree-based classifier like the Stanford paper). The tree structure of phrases is converted to raw text and its associated class label using the pytreebank library. The code for this tree-to-tabular transformation is provided in this project’s GitHub repo. The full-sentence text and their class labels (for the train, dev and test sets) are written to individual text files using a tab-delimiter between the sentence and class labels. We can then explore the tabular dataset in more detail using Pandas. To begin, read in the training set as a DataFrame while specifying the tab-delimiter to distinguish the class label from the text. Note that the class labels in the column “truth” are cast to the data type category in Pandas rather than leaving it as a string. import pandas as pd# Read train datadf = pd.read_csv('../data/sst/sst_train.txt', sep='\t', header=None, names=['truth', 'text'])df['truth'] = df['truth'].str.replace('__label__', '')df['truth'] = df['truth'].astype(int).astype('category')df.head() Using the command df.shape[0] tells us we have 8,544 training samples. One important aspect to note before analyzing a sentiment classification dataset is the class distribution in the training data. import matplotlib.pyplot as pltax = df[‘truth’].value_counts(sort=False).plot(kind=’barh’)ax.set_xlabel(“Number of Samples in training Set”)ax.set_ylabel(“Label”) It is clear that most of the training samples belong to classes 2 and 4 (the weakly negative/positive classes). A sizeable number of samples belong to the neutral class. Barely 12% of the samples are from the strongly negative class 1, which is something to keep in mind as we evaluate our classifier accuracy. What about the test set? A quick look tells us that we have 2,210 test samples, with a very similar distribution to the training data — again, there are far fewer samples belonging to the strongly negative/positive classes (1 or 5) compared to the other classes. This is desirable, since the test set distribution on which our classifier makes predictions is not too different from that of the training set. An interesting point mentioned in the original paper is that many of the really short text examples belong to the neutral class (i.e. class 3). This can be easily visualized in Pandas. We can create a new column that stores the string length of each text sample, and then sort the DataFrame rows in ascending order of their text lengths. df['len'] = df['text'].str.len() # Store string length of each sampledf = df.sort_values(['len'], ascending=True)df.head(20) Samples with clearly polar words, such as “good” and “loved” would offer greater context to a sentiment classifier— however, for neutral sounding words (such as “Hopkins”, or “Brimful”), the classifier would have to not only work with extremely small context, i.e. single word samples, but also be able to deal with ambiguous or unseen words that did not appear in the training vocabulary. As mentioned in the paper, the SST dataset was labelled by human annotators via Amazon Mechanical Turk. Annotators were shown randomly selected phrases for which they chose labels from a continuous slider bar. A discrete sentiment label belonging to one of five classes was reconstructed based on an average of multiple annotators’ chosen labels. Random sampling was used during annotation to ensure that labelling wasn’t influenced by the phrase that preceded it. The above example makes it clear why this is such a challenging dataset on which to make sentiment predictions. For example, annotators tended to categorize the phrase “nerdy folks” as somewhat negative, since the word “nerdy” has a somewhat negative connotation in terms of our society’s current perception of nerds. However, from a purely linguistic perspective, this sample could just as well be classified as neutral. It is thus important to remember that text classification labels are always subject to human perceptions and biases. In a real-world application, it absolutely makes sense to look at certain edge cases on a subjective basis. No benchmark dataset — and by extension, classification model — is ever perfect. With these points in mind, we can proceed onward to designing our sentiment classification framework! A general workflow for model training and evaluation is shown below. Model Training: Each classifier (except for the rule-based ones) is trained on the 8,544 samples from the SST-5 training set using a supervised learning algorithm. Separate training scripts are available in the project’s GitHub repo. Prediction: As per our object-oriented design philosophy, we avoid repeating code blocks that perform the same tasks across the various classification methods. A Base class is defined in Python that contains the commonly used methods: one for reading in the SST-5 data into a Pandas DataFrame (read_data), and another to calculate the model’s classification accuracy and F1-score (accuracy). Storing the dataset in a Pandas DataFrame this way makes it very convenient to apply custom transformations and user-defined functions while avoiding excessive use of for-loops. Next, each individual classifier added to our framework must inherit the Base class defined above. To make the framework consistent, a score method and a predict method are included with each new sentiment classifier, as shown below. The score method outputs a unique sentiment class for a text sample, and the predict method applies the score method to every sample in the test dataset to output a new column, 'pred' in the test DataFrame. It is then trivial to compute the model’s accuracy and F1-scores by using the accuracy method defined in the Base class. Evaluation: To evaluate the model’s accuracy, a confusion matrix of the model is plotted using scikit-learn and matplotlib (plotter.py on GitHub). The confusion matrix tabulates the number of correct predictions versus the number of incorrect predictions for each class, so it becomes easier to see which classes are the least accurately predicted for a given classifier. Note that the confusion matrix for our 5-class case is a normalized anti-diagonal matrix — ideally, the classifier would get almost 100% of its predictions correct so all elements outside the anti-diagonal would be as close to zero as possible. In this section, we’ll go through some key points regarding the training, sentiment scoring and model evaluation for each method. TextBlob is a popular Python library for processing textual data. It is built on top of NLTK, another popular Natural Language Processing toolbox for Python. TextBlob uses a sentiment lexicon (consisting of predefined words) to assign scores for each word, which are then averaged out using a weighted average to give an overall sentence sentiment score. Three scores: “polarity”, “subjectivity” and “intensity” are calculated for each word. # A sentiment lexicon can be used to discern objective facts from subjective opinions in text. # Each word in the lexicon has scores for: # 1) polarity: negative vs. positive (-1.0 => +1.0) # 2) subjectivity: objective vs. subjective (+0.0 => +1.0) # 3) intensity: modifies next word? (x0.5 => x2.0) Some intuitive rules are hardcoded inside TextBlob to detect modifiers (such as adverbs in English: “very good”) that increase or decrease the overall polarity score of the sentence. A more detailed description of these rules is available in this blog post. Sentiment Scoring: To convert the polarity score returned by TextBlob (a continuous-valued float in the range [-1, 1]) to a fine-grained class label (an integer), we can make use of binning. This is easily done in Pandas using the pd.cut function — it allows us to go from a continuous variable to a categorical variable by using equal sized bins in the float interval of all TextBlob scores in the results. Evaluation: Since we are dealing with imbalanced classes during both training and testing, we look at the macro F1 score (which is the harmonic mean of the macro-averaged precision and recall) as well as classification accuracy. As can be seen , the accuracy of the TextBlob classification method is very low, as is the F1 score. The confusion matrix plot shows more detail about which classes were most incorrectly predicted by the classifier. To read the above confusion matrix plot, look at the cells along the anti-diagonal. Cell [1, 1] shows the percentage of samples belonging to class 1 that the classifier predicted correctly, cell [2, 2] for correct class 2 predictions, and so on. Cells away from the anti-diagonal show the percentage of wrong predictions made for each respective class — for example, looking at the cell [4, 5], we can see that 47% of all samples that actually belong to class 5 are (incorrectly) predicted as class 4 by TextBlob. It is clear that our TextBlob classifier predicts most samples as neutral or mildly positive, i.e. of class 3 or 4, which explains why the model accuracy is so low. Very few predictions are strongly negative or positive — this makes sense because TextBlob uses a weighted average sentiment score over all the words in each sample. This can very easily diffuse out the effect of sentences with widely varying polarities between words, such as “This movie is about lying , cheating , but loving the friends you betray.” “Valence Aware Dictionary and sEntiment Reasoner” is another popular rule-based library for sentiment analysis. Like TextBlob, it uses a sentiment lexicon that contains intensity measures for each word based on human-annotated labels. A key difference however, is that VADER was designed with a focus on social media texts. This means that it puts a lot of emphasis on rules that capture the essence of text typically seen on social media — for example, short sentences with emojis, repetitive vocabulary and copious use of punctuation (such as exclamation marks). Below are some examples of the sentiment intensity scores output by VADER. In the above text samples, minor variations are made to the same sentence. Note that VADER breaks down sentiment intensity scores into a positive, negative and neutral component, which are then normalized and squashed to be within the range [-1, 1] as a “compound” score. As we add more exclamation marks, capitalization and emojis/emoticons, the intensity gets more and more extreme (towards +/- 1). Sentiment scoring: For returning discrete class values on the SST-5 dataset, we apply a similar technique as done for TextBlob — the continuous “compound” polarity score (float) is converted to a discrete value using binning through the pandas pd.cut function. This returns one of five classes for each test sample, stored as a new column in the resulting DataFrame. Evaluation: The binning method used above is a rather crude way to equally divide the continuous (float) value from VADER into one of the five discrete classes we require. However, we do see an overall classification accuracy and macro F1 score improvement compared to TextBlob. The confusion matrix for VADER shows a lot more classes predicted correctly (along the anti-diagonal) — however, the spread of incorrect predictions about the diagonal is also greater, giving us a more “confused” model. The greater spread (outside the anti-diagonal) for VADER can be attributed to the fact that it only ever assigns very low or very high compound scores to text that has a lot of capitalization, punctuation, repetition and emojis. Since SST-5 does not really have such annotated text (it is quite different from social media text), most of the VADER predictions for this dataset lie within the range -0.5 to +0.5 (raw scores). This results in a much more narrow distribution when converting to discrete class labels and hence, many predictions can err on either side of the true label. Although the result with VADER is still quite low in accuracy, it is clear that its rule-based approach does capture a good amount of fine-gradation in sentiment when compared to TextBlob — fewer cases that are truly negative get classified as positive, and vice versa. Moving onward from rule-based approaches, the next method attempted is a logistic regression — among the most commonly used supervised learning algorithms for classification. Logistic regression is a linear model trained on labelled data — the term linear is important because it means the algorithm only uses linear combinations (i.e. sums and not products) of inputs and parameters to produce a class prediction. Sebastian Raschka gives a very concise explanation of how the logistic regression equates to a very simple, one-layer neural network in his blog post. The input features and their weights are fed into an activation function (a sigmoid for binary classification, or a softmax for multi-class). The output of the classifier is just the index of the sigmoid/softmax vector with the highest value as the class label. For multi-class logistic regression, a one-vs-rest method is typically used — in this method, we train C separate binary classification models, where C is the number of classes. Each classifier f_c, for c ∈ {1, ..., C} is trained to predict whether a sample is part of class c or not. Transforming words to features: To transform the text into features, the first step is to use scikit-learn’s CountVectorizer. This converts the entire corpus (i.e. all sentences) of our training data into a matrix of token counts. Tokens (words, punctuation symbols, etc.) are created using NLTK’s tokenizer and commonly-used stop words like “a”, “an”, “the” are removed because they do not add much value to the sentiment scoring. Next, the count matrix is converted to a TF-IDF (Term-frequency Inverse document frequency) representation. From the scikit-learn documentation: Tf means term-frequency while tf-idf means term-frequency times inverse document-frequency. This is a common term weighting scheme in information retrieval, that has also found good use in document classification. The goal of using tf-idf instead of the raw frequencies of occurrence of a token in a given document is to scale down the impact of tokens that occur very frequently in a given corpus and that are hence empirically less informative than features that occur in a small fraction of the training corpus. Sentiment scoring: Once we obtain the TF-IDF representation of the training corpus, the classifier is trained by fitting it to the existing features. A “newton-cg” solver is used for optimizing the loss in the logistic regression and L2 regularization is used by default. A sentiment label is returned for each test sample (using scikit-learn’s learner.predict method) as the index of the maximum class probability in the softmax output vector. Evaluation: Switching from a rule-based method to a feature-based one shows a significant improvement in the overall classification accuracy and F1 scores, as can be seen below. However, the confusion matrix shows why looking at an overall accuracy measure is not very useful in multi-class problems. The logistic regression model classifies a large percentage of true labels 1 and 5 (strongly negative/positive) as belonging to their neighbour classes (2 and 4). Also, hardly any examples are correctly classified as neutral (class 3). Because most of the training samples belonged to classes 2 and 4, it looks like the logistic classifier mostly learned the features that occur in these majority classes. Support Vector Machines (SVMs) are very similar to logistic regression in terms of how they optimize a loss function to generate a decision boundary between data points. The primary difference, however, is the use of “kernel functions”, i.e. functions that transform a complex, nonlinear decision space to one that has higher dimensionality, so that an appropriate hyperplane separating the data points can be found. The SVM classifier looks to maximize the distance of each data point from this hyperplane using “support vectors” that characterize each distance as a vector. A key feature of SVMs is the fact that it uses a hinge loss rather than a logistic loss. This makes it more robust to outliers in the data, since the hinge loss does not diverge as quickly as a logistic loss. Training and sentiment scoring: The linear SVM in scikit-learn is set up using a similar pipeline as done for the logistic regression described in earlier. Once we obtain the TF-IDF representation of the training corpus, we train the SVM model by fitting it to the training data features. A hinge loss function with a stochastic gradient descent (SGD) optimizer is used, and L2 regularization is applied during training. The sentiment label is returned (using scikit-learn’s learner.predict method) as the index of the maximum class probability in the softmax output vector. Evaluation: Because quite a few features are likely to be outliers in a realistic dataset, the SVM should in practice produce results that are slightly better than the logistic regression. Looking at the improvement in accuracy and F1 scores, this appears to be true. The choice of optimizer combined with the SVM’s ability to model a more complex hyperplane separating the samples into their own classes results in a slightly improved confusion matrix when compared with the logistic regression. The SVM model predicts the strongly negative/positive classes (1 and 5) more accurately than the logistic regression. However, it still fails to predict enough samples as belonging to class 3— a large percentage of the SVM predictions are once again biased towards the dominant classes 2 and 4. This tells us that there is scope for improvement in the way features are defined. A count vectorizer combined with a TF-IDF transformation does not really learn anything about how words are related to one another — they simply look at the number of word co-occurrences in the each sample to make a conclusion. Enter word embeddings. FastText, a highly efficient, scalable, CPU-based library for text representation and classification, was released by the Facebook AI Research (FAIR) team in 2016. A key feature of FastText is the fact that its underlying neural network learns representations, or embeddings that consider similarities between words. While Word2Vec (a word embedding technique released much earlier, in 2013) did something similar, there are some key points that stand out with regard to FastText. FastText considers subwords using a collection of n-grams: for example, “train” is broken down into “tra”, “rai” and “ain”. In this manner, the representation of a word is more resistant to misspellings and minor spelling variations. Unknown words are handled much better in FastText because it is able to break down long words into subwords that might also appear in other long words, giving it better context. Python module: Although the source code for FastText is in C++, an official Python module was released by FAIR in June 2019 (after several months of confusion within the community). This makes it very convenient to train and test our model completely within Python, without the use of any external binaries. However, to find the optimum hyperparameters, the command line interface for FastText is recommended. Training FastText model: To train the FastText model, use the fasttext command line interface (Unix only) — this contains a very useful utility for hyperparameter auto-tuning. As per the documentation, this utility optimizes all hyper-parameters for the maximum F1 score, so we don’t need to do a manual search for the best hyper-parameters for our specific dataset. This is run using the following command on the terminal, and takes about 5 minutes on CPU. The above command tells FastText to train the model on the training set and validate on the dev set while optimizing the hyper-parameters to achieve the maximum F1-score. The flag -autotune-modelsize 10M tells FastText to optimize the model’s quantization parameters (explained below) such that the final trained model is under 10 MB in size, and the -verbose option is enabled to see which combination of hyper-parameters gives the best results. 💡 TIP: Quantize the FastText model: Quantization reduces the number of bits required to store a model’s weights by using 16 or 8-bit integers, rather than standard 32-bit floating points. Doing so vastly reduces model size (by several orders of magnitude). FastText makes quantization very convenient in the latest release of its command line interface or its Python module as follows (the extension of the quantized model is .ftz, not .bin as the parent model). The cutoff option is set as per the value obtained during hyper-parameter optimization, which ensures that the final model size stays below 10 MB. # Quantize model to reduce space usage model.quantize(input=train, qnorm=True, retrain=True, cutoff=110539) model.save_model(os.path.join(model_path, "sst5.ftz")) The below snippet shows how to train the model from within Python using the optimum hyper-parameters (this step is optional — only the command-line training tool can be used, if preferred). For more details on the meaning of each hyper-parameter and how FastText works under the hood, this article gives a good description. Sentiment scoring: Sentiment predictions are made by loading in the trained, quantized (.ftz ) FastText model. The model has a predict method that outputs the most likely labels based on the probabilities extracted from the softmax output layer. For making a class prediction, we simply choose the most likely class label from this list of probabilities, directly extracting it as an integer. Evaluation: It can be seen that the FastText model accuracy and F1 scores do not vastly improve on the SVM for this dataset. The F1 score for FastText, however, is slightly higher than that for the SVM. The confusion matrix of both models side-by-side highlights this in more detail. The key difference between the FastText and SVM results is the percentage of correct predictions for the neutral class, 3. The SVM predicts more items correctly in the majority classes (2 and 4) than FastText, which highlight the weakness of feature-based approaches in text classification problems with imbalanced classes. Word embeddings and subword representations, as used by FastText, inherently give it additional context. This is especially true when it comes to classifying unknown words, which are quite common in the neutral class (especially the very short samples with one or two words, mostly unseen). However, our FastText model was trained using word trigrams, so for longer sentences that change polarities midway, the model is bound to “forget” the context several words previously. A sequential model such as an RNN or an LSTM would be able to much better capture longer-term context and model this transitive sentiment. In 2018, Zalando Research published a state-of-the-art deep learning sequence tagging NLP library called Flair. This quickly became a popular framework for classification tasks as well because of the fact that it allowed combining different kinds of word embeddings together to give the model even greater contextual awareness. At the heart of Flair is a contextualized representation called string embeddings. To obtain them, sentences from a large corpus are broken down into character sequences to pre-train a bidirectional language model that “learns” embeddings at the character-level. This way, the model learns to disambiguate case-sensitive characters (for example, proper nouns from similar sounding common nouns) and other syntactic patterns in natural language, which makes it very powerful for tasks like named entity recognition and part-of-speech tagging. Training a Flair Model for Classification: What makes Flair extremely convenient yet powerful is its ability to “stack” word embeddings (such as ELMo or BERT) with “Flair” (i.e. string) embeddings. The below example shows how to instantiate a stacked embedding of BERT (base, cased) or ELMo (original) embeddings with Flair embeddings. The stacked representation is converted to a document embedding, i.e. one that gives a single embedding for an entire text sample (no matter how many sentences). This allows us to condense a complex, arbitrary length representation to a fixed-size tensor representation that we can fit in GPU memory for training. The power of stacking embeddings (either BERT or ELMo) this way comes from the fact that character-level string embeddings capture latent syntactic-semantic information without using the notion of a word (they explicitly focus on subword representations) — while the stacked word embeddings from an external pre-trained neural network model give added word-level context. This enhances the model’s ability to identify a wide range of syntactic features in the given text, allowing it to surpass the performance of classical word embedding models. Notes on training: The Flair model requires a GPU for training, and due to its LSTM architecture does not parallelize as efficiently as compared to transformer architectures — so training time even on this relatively small SST-5 dataset is of the order of several hours. For this project, 25 epochs of training were run, and the validation loss was still decreasing when training was stopped, meaning that the model was underfitting considerably. As a result, using Flair on a real-world, large dataset for classification tasks can come with a significant cost penalty. Sentiment scoring: Just as before, a scoring technique is implemented with the existing framework in Pandas. The trained model is first loaded, and the text converted to a Sentence object (which is a tokenized representation of each sentence in a sample). The Flair model’s predict method is called to predict a class label using the maximum index from the softmax output layer, which is then extracted as an integer and stored sample-wise in a Pandas DataFrame. Since model inference can take quite a while even on a GPU, a tqdm progress bar is implemented to show how many test samples the model finished predicting. Evaluation: Two separate stacked representations are used to train two separate models — one using BERT (base, cased) and the other using ELMo (original). Inference is run using each model to give the following results. There is a sizeable improvement in accuracy and F1 scores over both the FastText and SVM models! Looking at the confusion matrices for each case yields insights into which classes were better predicted than others. The above plots highlight why stacking with BERT embeddings scored so much lower than stacking with ELMo embeddings. The BERT case almost makes no correct predictions for class 1 — however it does get a lot more predictions in class 4 correct. The ELMo model seems to stack much better with the Flair embeddings and generates a larger fraction of correct predictions for the minority classes (1 and 5). What went wrong with the Flair + BERT model during training? It could be that re-projecting and decreasing the number of hidden dimensions (during stacking) resulted in a loss of knowledge from the pre-trained BERT model, explaining why this model did not learn well enough on strongly negative samples. It is not exactly clear why stacking ELMo embeddings results in much better learning compared to stacking with BERT. In both cases, however, the Flair models took a large amount of time (several hours) to train, which can be a huge bottleneck in the real-world —yet, they do highlight the power of using contextual embeddings over classical word embeddings for fine-grained classification. In this post, six different NLP classifiers in Python were used to make class predictions on the SST-5 fine-grained sentiment dataset. Using progressively more and more complex models, we were able to push up the accuracy and macro-average F1 scores to around 48%, which is not too bad! In a future post, we’ll see how to further improve on these scores using a transformer model powered by transfer learning. Plotting normalized confusion matrices give some useful insights as to why the accuracies for the embedding-based methods are higher than the simpler feature-based methods like logistic regression and SVM. It is clear that overall accuracy is a very poor metric in multi-class problems with a class imbalance, such as this one — which is why macro F1-scores are needed to truly gauge which classifiers perform better. A key aspect of machine learning models (especially deep learning models) is that they are notoriously hard to interpret. To address this issue, we’ll look at explaining our results and answering the question: “Why did X classifier predict this specific class for this specific sample?”. The LIME Python library is used for this task, which will be described in the next post. If you made it through to the end of this article, thanks for reading! This was Part 1 of a series on fine-grained sentiment analysis in Python. Part 2 covers how to build an explainer module using LIME and explain class predictions on two representative test samples. Part 3 covers how to further improve the accuracy and F1 scores by building our own transformer model and using transfer learning. NOTE: All the training and evaluation code for this analysis are available in the project’s Github repo, so feel free to reproduce the results and make your own findings!
[ { "code": null, "e": 354, "s": 171, "text": "“Learning to choose is hard. Learning to choose well is harder. And learning to choose well in a world of unlimited possibilities is harder still, perhaps too hard.” — Barry Schwartz" }, { "code": null, "e": 883, "s": 354, "text": "When starting a new NLP sentiment analysis project, it can be quite an overwhelming task to narrow down on a select methodology for a given application. Do we use a rule-based model, or do we train a model on our own data? Should we train a neural network, or will a simple linear model meet our requirements? Should we spend the time and effort in implementing our own text classification framework, or can we just use one off-the-shelf? How hard is it to interpret the results and understand why certain predictions were made?" }, { "code": null, "e": 1185, "s": 883, "text": "This series aims at answering some of the above questions, with a focus on fine-grained sentiment analysis. Through the remaining sections, we’ll compare and discuss classification results using several well-known NLP libraries in Python. The methods described below fall under three broad categories:" }, { "code": null, "e": 1205, "s": 1185, "text": "Rule-based methods:" }, { "code": null, "e": 1260, "s": 1205, "text": "TextBlob: Simple rule-based API for sentiment analysis" }, { "code": null, "e": 1342, "s": 1260, "text": "VADER: Parsimonious rule-based model for sentiment analysis of social media text." }, { "code": null, "e": 1365, "s": 1342, "text": "Feature-based methods:" }, { "code": null, "e": 1428, "s": 1365, "text": "Logistic Regression: Generalized linear model in Scikit-learn." }, { "code": null, "e": 1557, "s": 1428, "text": "Support Vector Machine (SVM): Linear model in Scikit-learn with a stochastic gradient descent (SGD) optimizer for gradient loss." }, { "code": null, "e": 1582, "s": 1557, "text": "Embedding-based methods:" }, { "code": null, "e": 1705, "s": 1582, "text": "FastText: An NLP library that uses highly efficient CPU-based representations of word embeddings for classification tasks." }, { "code": null, "e": 1797, "s": 1705, "text": "Flair: A PyTorch-based framework for NLP tasks such as sequence tagging and classification." }, { "code": null, "e": 2006, "s": 1797, "text": "Each approach is implemented in an object-oriented manner in Python, to ensure that we can easily swap out models for experiments and extend the framework with better, more powerful classifiers in the future." }, { "code": null, "e": 2471, "s": 2006, "text": "In most cases today, sentiment classifiers are used for binary classification (just positive or negative sentiment), and for good reason: fine-grained sentiment classification is a significantly more challenging task! The typical breakdown of fine-grained sentiment uses five discrete classes, as shown below. As one might imagine, models very easily err on either side of the strong/weak sentiment intensities thanks to the wonderful subtleties of human language." }, { "code": null, "e": 3151, "s": 2471, "text": "Binary class labels may be sufficient for studying large-scale positive/negative sentiment trends in text data such as Tweets, product reviews or customer feedback, but they do have their limitations. When performing information extraction with comparative expressions, for example: “This OnePlus model X is so much better than Samsung model X.” — a fine-grained analysis can provide more precise results to an automated system that prioritizes addressing customer complaints. In addition, dual-polarity sentences such as “The location was truly disgusting ... but the people there were glorious.” can confuse binary sentiment classifiers, leading to incorrect class predictions." }, { "code": null, "e": 3222, "s": 3151, "text": "The above points provide sufficient motivation to tackle this problem!" }, { "code": null, "e": 3685, "s": 3222, "text": "The Stanford Sentiment Treebank (SST-5, or SST-fine-grained) dataset is a suitable benchmark to test our application, since it was designed to help evaluate a model’s ability to understand representations of sentence structure, rather than just looking at individual words in isolation. SST-5 consists of 11,855 sentences extracted from movie reviews with fine-grained sentiment labels [1–5], as well as 215,154 phrases that compose each sentence in the dataset." }, { "code": null, "e": 4229, "s": 3685, "text": "The raw data with phrase-based fine-grained sentiment labels is in the form of a tree structure, designed to help train a Recursive Neural Tensor Network (RNTN) from their 2015 paper. The component phrases were constructed by parsing each sentence using the Stanford parser (section 3 in the paper) and creating a recursive tree structure as shown in the below image. A deep neural network was then trained on the tree structure of each sentence to classify the sentiment of each phrase to obtain a cumulative sentiment of the entire sentence." }, { "code": null, "e": 4813, "s": 4229, "text": "The original RNTN implemented in the Stanford paper [Socher et al.] obtained an accuracy of 45.7% on the full-sentence sentiment classification. More recently, a Bi-attentive Classification Network (BCN) augmented with ELMo embeddings has been used to achieve a significantly higher accuracy of 54.7% on the SST-5 dataset. The current (as of 2019) state-of-the-art accuracy on the SST-5 dataset is 64.4%, by a method that uses sentence-level embeddings originally designed to solve a paraphrasing task — it ended up doing surprisingly well on fine-grained sentiment analysis as well." }, { "code": null, "e": 5126, "s": 4813, "text": "Although neural language models have been getting increasingly powerful since 2018, it might take far bigger deep learning models (with far more parameters) augmented with knowledge-based methods (such as graphs) to achieve sufficient semantic context for accuracies of 70–80% in fine-grained sentiment analysis." }, { "code": null, "e": 5580, "s": 5126, "text": "To evaluate our NLP methods and how each one differs from the other, we will use just the complete samples in the training dataset (ignoring the component phrases since we are not using a recursive tree-based classifier like the Stanford paper). The tree structure of phrases is converted to raw text and its associated class label using the pytreebank library. The code for this tree-to-tabular transformation is provided in this project’s GitHub repo." }, { "code": null, "e": 5759, "s": 5580, "text": "The full-sentence text and their class labels (for the train, dev and test sets) are written to individual text files using a tab-delimiter between the sentence and class labels." }, { "code": null, "e": 6089, "s": 5759, "text": "We can then explore the tabular dataset in more detail using Pandas. To begin, read in the training set as a DataFrame while specifying the tab-delimiter to distinguish the class label from the text. Note that the class labels in the column “truth” are cast to the data type category in Pandas rather than leaving it as a string." }, { "code": null, "e": 6338, "s": 6089, "text": "import pandas as pd# Read train datadf = pd.read_csv('../data/sst/sst_train.txt', sep='\\t', header=None, names=['truth', 'text'])df['truth'] = df['truth'].str.replace('__label__', '')df['truth'] = df['truth'].astype(int).astype('category')df.head()" }, { "code": null, "e": 6409, "s": 6338, "text": "Using the command df.shape[0] tells us we have 8,544 training samples." }, { "code": null, "e": 6538, "s": 6409, "text": "One important aspect to note before analyzing a sentiment classification dataset is the class distribution in the training data." }, { "code": null, "e": 6701, "s": 6538, "text": "import matplotlib.pyplot as pltax = df[‘truth’].value_counts(sort=False).plot(kind=’barh’)ax.set_xlabel(“Number of Samples in training Set”)ax.set_ylabel(“Label”)" }, { "code": null, "e": 7012, "s": 6701, "text": "It is clear that most of the training samples belong to classes 2 and 4 (the weakly negative/positive classes). A sizeable number of samples belong to the neutral class. Barely 12% of the samples are from the strongly negative class 1, which is something to keep in mind as we evaluate our classifier accuracy." }, { "code": null, "e": 7420, "s": 7012, "text": "What about the test set? A quick look tells us that we have 2,210 test samples, with a very similar distribution to the training data — again, there are far fewer samples belonging to the strongly negative/positive classes (1 or 5) compared to the other classes. This is desirable, since the test set distribution on which our classifier makes predictions is not too different from that of the training set." }, { "code": null, "e": 7758, "s": 7420, "text": "An interesting point mentioned in the original paper is that many of the really short text examples belong to the neutral class (i.e. class 3). This can be easily visualized in Pandas. We can create a new column that stores the string length of each text sample, and then sort the DataFrame rows in ascending order of their text lengths." }, { "code": null, "e": 7884, "s": 7758, "text": "df['len'] = df['text'].str.len() # Store string length of each sampledf = df.sort_values(['len'], ascending=True)df.head(20)" }, { "code": null, "e": 8274, "s": 7884, "text": "Samples with clearly polar words, such as “good” and “loved” would offer greater context to a sentiment classifier— however, for neutral sounding words (such as “Hopkins”, or “Brimful”), the classifier would have to not only work with extremely small context, i.e. single word samples, but also be able to deal with ambiguous or unseen words that did not appear in the training vocabulary." }, { "code": null, "e": 8739, "s": 8274, "text": "As mentioned in the paper, the SST dataset was labelled by human annotators via Amazon Mechanical Turk. Annotators were shown randomly selected phrases for which they chose labels from a continuous slider bar. A discrete sentiment label belonging to one of five classes was reconstructed based on an average of multiple annotators’ chosen labels. Random sampling was used during annotation to ensure that labelling wasn’t influenced by the phrase that preceded it." }, { "code": null, "e": 9161, "s": 8739, "text": "The above example makes it clear why this is such a challenging dataset on which to make sentiment predictions. For example, annotators tended to categorize the phrase “nerdy folks” as somewhat negative, since the word “nerdy” has a somewhat negative connotation in terms of our society’s current perception of nerds. However, from a purely linguistic perspective, this sample could just as well be classified as neutral." }, { "code": null, "e": 9467, "s": 9161, "text": "It is thus important to remember that text classification labels are always subject to human perceptions and biases. In a real-world application, it absolutely makes sense to look at certain edge cases on a subjective basis. No benchmark dataset — and by extension, classification model — is ever perfect." }, { "code": null, "e": 9569, "s": 9467, "text": "With these points in mind, we can proceed onward to designing our sentiment classification framework!" }, { "code": null, "e": 9638, "s": 9569, "text": "A general workflow for model training and evaluation is shown below." }, { "code": null, "e": 9872, "s": 9638, "text": "Model Training: Each classifier (except for the rule-based ones) is trained on the 8,544 samples from the SST-5 training set using a supervised learning algorithm. Separate training scripts are available in the project’s GitHub repo." }, { "code": null, "e": 10442, "s": 9872, "text": "Prediction: As per our object-oriented design philosophy, we avoid repeating code blocks that perform the same tasks across the various classification methods. A Base class is defined in Python that contains the commonly used methods: one for reading in the SST-5 data into a Pandas DataFrame (read_data), and another to calculate the model’s classification accuracy and F1-score (accuracy). Storing the dataset in a Pandas DataFrame this way makes it very convenient to apply custom transformations and user-defined functions while avoiding excessive use of for-loops." }, { "code": null, "e": 11004, "s": 10442, "text": "Next, each individual classifier added to our framework must inherit the Base class defined above. To make the framework consistent, a score method and a predict method are included with each new sentiment classifier, as shown below. The score method outputs a unique sentiment class for a text sample, and the predict method applies the score method to every sample in the test dataset to output a new column, 'pred' in the test DataFrame. It is then trivial to compute the model’s accuracy and F1-scores by using the accuracy method defined in the Base class." }, { "code": null, "e": 11621, "s": 11004, "text": "Evaluation: To evaluate the model’s accuracy, a confusion matrix of the model is plotted using scikit-learn and matplotlib (plotter.py on GitHub). The confusion matrix tabulates the number of correct predictions versus the number of incorrect predictions for each class, so it becomes easier to see which classes are the least accurately predicted for a given classifier. Note that the confusion matrix for our 5-class case is a normalized anti-diagonal matrix — ideally, the classifier would get almost 100% of its predictions correct so all elements outside the anti-diagonal would be as close to zero as possible." }, { "code": null, "e": 11751, "s": 11621, "text": "In this section, we’ll go through some key points regarding the training, sentiment scoring and model evaluation for each method." }, { "code": null, "e": 12193, "s": 11751, "text": "TextBlob is a popular Python library for processing textual data. It is built on top of NLTK, another popular Natural Language Processing toolbox for Python. TextBlob uses a sentiment lexicon (consisting of predefined words) to assign scores for each word, which are then averaged out using a weighted average to give an overall sentence sentiment score. Three scores: “polarity”, “subjectivity” and “intensity” are calculated for each word." }, { "code": null, "e": 12493, "s": 12193, "text": "# A sentiment lexicon can be used to discern objective facts from subjective opinions in text. # Each word in the lexicon has scores for: # 1) polarity: negative vs. positive (-1.0 => +1.0) # 2) subjectivity: objective vs. subjective (+0.0 => +1.0) # 3) intensity: modifies next word? (x0.5 => x2.0)" }, { "code": null, "e": 12751, "s": 12493, "text": "Some intuitive rules are hardcoded inside TextBlob to detect modifiers (such as adverbs in English: “very good”) that increase or decrease the overall polarity score of the sentence. A more detailed description of these rules is available in this blog post." }, { "code": null, "e": 13159, "s": 12751, "text": "Sentiment Scoring: To convert the polarity score returned by TextBlob (a continuous-valued float in the range [-1, 1]) to a fine-grained class label (an integer), we can make use of binning. This is easily done in Pandas using the pd.cut function — it allows us to go from a continuous variable to a categorical variable by using equal sized bins in the float interval of all TextBlob scores in the results." }, { "code": null, "e": 13489, "s": 13159, "text": "Evaluation: Since we are dealing with imbalanced classes during both training and testing, we look at the macro F1 score (which is the harmonic mean of the macro-averaged precision and recall) as well as classification accuracy. As can be seen , the accuracy of the TextBlob classification method is very low, as is the F1 score." }, { "code": null, "e": 13604, "s": 13489, "text": "The confusion matrix plot shows more detail about which classes were most incorrectly predicted by the classifier." }, { "code": null, "e": 14118, "s": 13604, "text": "To read the above confusion matrix plot, look at the cells along the anti-diagonal. Cell [1, 1] shows the percentage of samples belonging to class 1 that the classifier predicted correctly, cell [2, 2] for correct class 2 predictions, and so on. Cells away from the anti-diagonal show the percentage of wrong predictions made for each respective class — for example, looking at the cell [4, 5], we can see that 47% of all samples that actually belong to class 5 are (incorrectly) predicted as class 4 by TextBlob." }, { "code": null, "e": 14636, "s": 14118, "text": "It is clear that our TextBlob classifier predicts most samples as neutral or mildly positive, i.e. of class 3 or 4, which explains why the model accuracy is so low. Very few predictions are strongly negative or positive — this makes sense because TextBlob uses a weighted average sentiment score over all the words in each sample. This can very easily diffuse out the effect of sentences with widely varying polarities between words, such as “This movie is about lying , cheating , but loving the friends you betray.”" }, { "code": null, "e": 15276, "s": 14636, "text": "“Valence Aware Dictionary and sEntiment Reasoner” is another popular rule-based library for sentiment analysis. Like TextBlob, it uses a sentiment lexicon that contains intensity measures for each word based on human-annotated labels. A key difference however, is that VADER was designed with a focus on social media texts. This means that it puts a lot of emphasis on rules that capture the essence of text typically seen on social media — for example, short sentences with emojis, repetitive vocabulary and copious use of punctuation (such as exclamation marks). Below are some examples of the sentiment intensity scores output by VADER." }, { "code": null, "e": 15677, "s": 15276, "text": "In the above text samples, minor variations are made to the same sentence. Note that VADER breaks down sentiment intensity scores into a positive, negative and neutral component, which are then normalized and squashed to be within the range [-1, 1] as a “compound” score. As we add more exclamation marks, capitalization and emojis/emoticons, the intensity gets more and more extreme (towards +/- 1)." }, { "code": null, "e": 16044, "s": 15677, "text": "Sentiment scoring: For returning discrete class values on the SST-5 dataset, we apply a similar technique as done for TextBlob — the continuous “compound” polarity score (float) is converted to a discrete value using binning through the pandas pd.cut function. This returns one of five classes for each test sample, stored as a new column in the resulting DataFrame." }, { "code": null, "e": 16323, "s": 16044, "text": "Evaluation: The binning method used above is a rather crude way to equally divide the continuous (float) value from VADER into one of the five discrete classes we require. However, we do see an overall classification accuracy and macro F1 score improvement compared to TextBlob." }, { "code": null, "e": 16543, "s": 16323, "text": "The confusion matrix for VADER shows a lot more classes predicted correctly (along the anti-diagonal) — however, the spread of incorrect predictions about the diagonal is also greater, giving us a more “confused” model." }, { "code": null, "e": 17127, "s": 16543, "text": "The greater spread (outside the anti-diagonal) for VADER can be attributed to the fact that it only ever assigns very low or very high compound scores to text that has a lot of capitalization, punctuation, repetition and emojis. Since SST-5 does not really have such annotated text (it is quite different from social media text), most of the VADER predictions for this dataset lie within the range -0.5 to +0.5 (raw scores). This results in a much more narrow distribution when converting to discrete class labels and hence, many predictions can err on either side of the true label." }, { "code": null, "e": 17397, "s": 17127, "text": "Although the result with VADER is still quite low in accuracy, it is clear that its rule-based approach does capture a good amount of fine-gradation in sentiment when compared to TextBlob — fewer cases that are truly negative get classified as positive, and vice versa." }, { "code": null, "e": 17812, "s": 17397, "text": "Moving onward from rule-based approaches, the next method attempted is a logistic regression — among the most commonly used supervised learning algorithms for classification. Logistic regression is a linear model trained on labelled data — the term linear is important because it means the algorithm only uses linear combinations (i.e. sums and not products) of inputs and parameters to produce a class prediction." }, { "code": null, "e": 18225, "s": 17812, "text": "Sebastian Raschka gives a very concise explanation of how the logistic regression equates to a very simple, one-layer neural network in his blog post. The input features and their weights are fed into an activation function (a sigmoid for binary classification, or a softmax for multi-class). The output of the classifier is just the index of the sigmoid/softmax vector with the highest value as the class label." }, { "code": null, "e": 18510, "s": 18225, "text": "For multi-class logistic regression, a one-vs-rest method is typically used — in this method, we train C separate binary classification models, where C is the number of classes. Each classifier f_c, for c ∈ {1, ..., C} is trained to predict whether a sample is part of class c or not." }, { "code": null, "e": 19087, "s": 18510, "text": "Transforming words to features: To transform the text into features, the first step is to use scikit-learn’s CountVectorizer. This converts the entire corpus (i.e. all sentences) of our training data into a matrix of token counts. Tokens (words, punctuation symbols, etc.) are created using NLTK’s tokenizer and commonly-used stop words like “a”, “an”, “the” are removed because they do not add much value to the sentiment scoring. Next, the count matrix is converted to a TF-IDF (Term-frequency Inverse document frequency) representation. From the scikit-learn documentation:" }, { "code": null, "e": 19602, "s": 19087, "text": "Tf means term-frequency while tf-idf means term-frequency times inverse document-frequency. This is a common term weighting scheme in information retrieval, that has also found good use in document classification. The goal of using tf-idf instead of the raw frequencies of occurrence of a token in a given document is to scale down the impact of tokens that occur very frequently in a given corpus and that are hence empirically less informative than features that occur in a small fraction of the training corpus." }, { "code": null, "e": 20047, "s": 19602, "text": "Sentiment scoring: Once we obtain the TF-IDF representation of the training corpus, the classifier is trained by fitting it to the existing features. A “newton-cg” solver is used for optimizing the loss in the logistic regression and L2 regularization is used by default. A sentiment label is returned for each test sample (using scikit-learn’s learner.predict method) as the index of the maximum class probability in the softmax output vector." }, { "code": null, "e": 20225, "s": 20047, "text": "Evaluation: Switching from a rule-based method to a feature-based one shows a significant improvement in the overall classification accuracy and F1 scores, as can be seen below." }, { "code": null, "e": 20348, "s": 20225, "text": "However, the confusion matrix shows why looking at an overall accuracy measure is not very useful in multi-class problems." }, { "code": null, "e": 20754, "s": 20348, "text": "The logistic regression model classifies a large percentage of true labels 1 and 5 (strongly negative/positive) as belonging to their neighbour classes (2 and 4). Also, hardly any examples are correctly classified as neutral (class 3). Because most of the training samples belonged to classes 2 and 4, it looks like the logistic classifier mostly learned the features that occur in these majority classes." }, { "code": null, "e": 21330, "s": 20754, "text": "Support Vector Machines (SVMs) are very similar to logistic regression in terms of how they optimize a loss function to generate a decision boundary between data points. The primary difference, however, is the use of “kernel functions”, i.e. functions that transform a complex, nonlinear decision space to one that has higher dimensionality, so that an appropriate hyperplane separating the data points can be found. The SVM classifier looks to maximize the distance of each data point from this hyperplane using “support vectors” that characterize each distance as a vector." }, { "code": null, "e": 21539, "s": 21330, "text": "A key feature of SVMs is the fact that it uses a hinge loss rather than a logistic loss. This makes it more robust to outliers in the data, since the hinge loss does not diverge as quickly as a logistic loss." }, { "code": null, "e": 22114, "s": 21539, "text": "Training and sentiment scoring: The linear SVM in scikit-learn is set up using a similar pipeline as done for the logistic regression described in earlier. Once we obtain the TF-IDF representation of the training corpus, we train the SVM model by fitting it to the training data features. A hinge loss function with a stochastic gradient descent (SGD) optimizer is used, and L2 regularization is applied during training. The sentiment label is returned (using scikit-learn’s learner.predict method) as the index of the maximum class probability in the softmax output vector." }, { "code": null, "e": 22382, "s": 22114, "text": "Evaluation: Because quite a few features are likely to be outliers in a realistic dataset, the SVM should in practice produce results that are slightly better than the logistic regression. Looking at the improvement in accuracy and F1 scores, this appears to be true." }, { "code": null, "e": 22611, "s": 22382, "text": "The choice of optimizer combined with the SVM’s ability to model a more complex hyperplane separating the samples into their own classes results in a slightly improved confusion matrix when compared with the logistic regression." }, { "code": null, "e": 23240, "s": 22611, "text": "The SVM model predicts the strongly negative/positive classes (1 and 5) more accurately than the logistic regression. However, it still fails to predict enough samples as belonging to class 3— a large percentage of the SVM predictions are once again biased towards the dominant classes 2 and 4. This tells us that there is scope for improvement in the way features are defined. A count vectorizer combined with a TF-IDF transformation does not really learn anything about how words are related to one another — they simply look at the number of word co-occurrences in the each sample to make a conclusion. Enter word embeddings." }, { "code": null, "e": 23721, "s": 23240, "text": "FastText, a highly efficient, scalable, CPU-based library for text representation and classification, was released by the Facebook AI Research (FAIR) team in 2016. A key feature of FastText is the fact that its underlying neural network learns representations, or embeddings that consider similarities between words. While Word2Vec (a word embedding technique released much earlier, in 2013) did something similar, there are some key points that stand out with regard to FastText." }, { "code": null, "e": 23955, "s": 23721, "text": "FastText considers subwords using a collection of n-grams: for example, “train” is broken down into “tra”, “rai” and “ain”. In this manner, the representation of a word is more resistant to misspellings and minor spelling variations." }, { "code": null, "e": 24133, "s": 23955, "text": "Unknown words are handled much better in FastText because it is able to break down long words into subwords that might also appear in other long words, giving it better context." }, { "code": null, "e": 24543, "s": 24133, "text": "Python module: Although the source code for FastText is in C++, an official Python module was released by FAIR in June 2019 (after several months of confusion within the community). This makes it very convenient to train and test our model completely within Python, without the use of any external binaries. However, to find the optimum hyperparameters, the command line interface for FastText is recommended." }, { "code": null, "e": 25001, "s": 24543, "text": "Training FastText model: To train the FastText model, use the fasttext command line interface (Unix only) — this contains a very useful utility for hyperparameter auto-tuning. As per the documentation, this utility optimizes all hyper-parameters for the maximum F1 score, so we don’t need to do a manual search for the best hyper-parameters for our specific dataset. This is run using the following command on the terminal, and takes about 5 minutes on CPU." }, { "code": null, "e": 25448, "s": 25001, "text": "The above command tells FastText to train the model on the training set and validate on the dev set while optimizing the hyper-parameters to achieve the maximum F1-score. The flag -autotune-modelsize 10M tells FastText to optimize the model’s quantization parameters (explained below) such that the final trained model is under 10 MB in size, and the -verbose option is enabled to see which combination of hyper-parameters gives the best results." }, { "code": null, "e": 26058, "s": 25448, "text": "💡 TIP: Quantize the FastText model: Quantization reduces the number of bits required to store a model’s weights by using 16 or 8-bit integers, rather than standard 32-bit floating points. Doing so vastly reduces model size (by several orders of magnitude). FastText makes quantization very convenient in the latest release of its command line interface or its Python module as follows (the extension of the quantized model is .ftz, not .bin as the parent model). The cutoff option is set as per the value obtained during hyper-parameter optimization, which ensures that the final model size stays below 10 MB." }, { "code": null, "e": 26273, "s": 26058, "text": "# Quantize model to reduce space usage model.quantize(input=train, qnorm=True, retrain=True, cutoff=110539) model.save_model(os.path.join(model_path, \"sst5.ftz\"))" }, { "code": null, "e": 26463, "s": 26273, "text": "The below snippet shows how to train the model from within Python using the optimum hyper-parameters (this step is optional — only the command-line training tool can be used, if preferred)." }, { "code": null, "e": 26597, "s": 26463, "text": "For more details on the meaning of each hyper-parameter and how FastText works under the hood, this article gives a good description." }, { "code": null, "e": 26990, "s": 26597, "text": "Sentiment scoring: Sentiment predictions are made by loading in the trained, quantized (.ftz ) FastText model. The model has a predict method that outputs the most likely labels based on the probabilities extracted from the softmax output layer. For making a class prediction, we simply choose the most likely class label from this list of probabilities, directly extracting it as an integer." }, { "code": null, "e": 27115, "s": 26990, "text": "Evaluation: It can be seen that the FastText model accuracy and F1 scores do not vastly improve on the SVM for this dataset." }, { "code": null, "e": 27193, "s": 27115, "text": "The F1 score for FastText, however, is slightly higher than that for the SVM." }, { "code": null, "e": 27274, "s": 27193, "text": "The confusion matrix of both models side-by-side highlights this in more detail." }, { "code": null, "e": 27889, "s": 27274, "text": "The key difference between the FastText and SVM results is the percentage of correct predictions for the neutral class, 3. The SVM predicts more items correctly in the majority classes (2 and 4) than FastText, which highlight the weakness of feature-based approaches in text classification problems with imbalanced classes. Word embeddings and subword representations, as used by FastText, inherently give it additional context. This is especially true when it comes to classifying unknown words, which are quite common in the neutral class (especially the very short samples with one or two words, mostly unseen)." }, { "code": null, "e": 28213, "s": 27889, "text": "However, our FastText model was trained using word trigrams, so for longer sentences that change polarities midway, the model is bound to “forget” the context several words previously. A sequential model such as an RNN or an LSTM would be able to much better capture longer-term context and model this transitive sentiment." }, { "code": null, "e": 28541, "s": 28213, "text": "In 2018, Zalando Research published a state-of-the-art deep learning sequence tagging NLP library called Flair. This quickly became a popular framework for classification tasks as well because of the fact that it allowed combining different kinds of word embeddings together to give the model even greater contextual awareness." }, { "code": null, "e": 29083, "s": 28541, "text": "At the heart of Flair is a contextualized representation called string embeddings. To obtain them, sentences from a large corpus are broken down into character sequences to pre-train a bidirectional language model that “learns” embeddings at the character-level. This way, the model learns to disambiguate case-sensitive characters (for example, proper nouns from similar sounding common nouns) and other syntactic patterns in natural language, which makes it very powerful for tasks like named entity recognition and part-of-speech tagging." }, { "code": null, "e": 29733, "s": 29083, "text": "Training a Flair Model for Classification: What makes Flair extremely convenient yet powerful is its ability to “stack” word embeddings (such as ELMo or BERT) with “Flair” (i.e. string) embeddings. The below example shows how to instantiate a stacked embedding of BERT (base, cased) or ELMo (original) embeddings with Flair embeddings. The stacked representation is converted to a document embedding, i.e. one that gives a single embedding for an entire text sample (no matter how many sentences). This allows us to condense a complex, arbitrary length representation to a fixed-size tensor representation that we can fit in GPU memory for training." }, { "code": null, "e": 30280, "s": 29733, "text": "The power of stacking embeddings (either BERT or ELMo) this way comes from the fact that character-level string embeddings capture latent syntactic-semantic information without using the notion of a word (they explicitly focus on subword representations) — while the stacked word embeddings from an external pre-trained neural network model give added word-level context. This enhances the model’s ability to identify a wide range of syntactic features in the given text, allowing it to surpass the performance of classical word embedding models." }, { "code": null, "e": 30850, "s": 30280, "text": "Notes on training: The Flair model requires a GPU for training, and due to its LSTM architecture does not parallelize as efficiently as compared to transformer architectures — so training time even on this relatively small SST-5 dataset is of the order of several hours. For this project, 25 epochs of training were run, and the validation loss was still decreasing when training was stopped, meaning that the model was underfitting considerably. As a result, using Flair on a real-world, large dataset for classification tasks can come with a significant cost penalty." }, { "code": null, "e": 31469, "s": 30850, "text": "Sentiment scoring: Just as before, a scoring technique is implemented with the existing framework in Pandas. The trained model is first loaded, and the text converted to a Sentence object (which is a tokenized representation of each sentence in a sample). The Flair model’s predict method is called to predict a class label using the maximum index from the softmax output layer, which is then extracted as an integer and stored sample-wise in a Pandas DataFrame. Since model inference can take quite a while even on a GPU, a tqdm progress bar is implemented to show how many test samples the model finished predicting." }, { "code": null, "e": 31689, "s": 31469, "text": "Evaluation: Two separate stacked representations are used to train two separate models — one using BERT (base, cased) and the other using ELMo (original). Inference is run using each model to give the following results." }, { "code": null, "e": 31904, "s": 31689, "text": "There is a sizeable improvement in accuracy and F1 scores over both the FastText and SVM models! Looking at the confusion matrices for each case yields insights into which classes were better predicted than others." }, { "code": null, "e": 32307, "s": 31904, "text": "The above plots highlight why stacking with BERT embeddings scored so much lower than stacking with ELMo embeddings. The BERT case almost makes no correct predictions for class 1 — however it does get a lot more predictions in class 4 correct. The ELMo model seems to stack much better with the Flair embeddings and generates a larger fraction of correct predictions for the minority classes (1 and 5)." }, { "code": null, "e": 33001, "s": 32307, "text": "What went wrong with the Flair + BERT model during training? It could be that re-projecting and decreasing the number of hidden dimensions (during stacking) resulted in a loss of knowledge from the pre-trained BERT model, explaining why this model did not learn well enough on strongly negative samples. It is not exactly clear why stacking ELMo embeddings results in much better learning compared to stacking with BERT. In both cases, however, the Flair models took a large amount of time (several hours) to train, which can be a huge bottleneck in the real-world —yet, they do highlight the power of using contextual embeddings over classical word embeddings for fine-grained classification." }, { "code": null, "e": 33411, "s": 33001, "text": "In this post, six different NLP classifiers in Python were used to make class predictions on the SST-5 fine-grained sentiment dataset. Using progressively more and more complex models, we were able to push up the accuracy and macro-average F1 scores to around 48%, which is not too bad! In a future post, we’ll see how to further improve on these scores using a transformer model powered by transfer learning." }, { "code": null, "e": 33829, "s": 33411, "text": "Plotting normalized confusion matrices give some useful insights as to why the accuracies for the embedding-based methods are higher than the simpler feature-based methods like logistic regression and SVM. It is clear that overall accuracy is a very poor metric in multi-class problems with a class imbalance, such as this one — which is why macro F1-scores are needed to truly gauge which classifiers perform better." }, { "code": null, "e": 34206, "s": 33829, "text": "A key aspect of machine learning models (especially deep learning models) is that they are notoriously hard to interpret. To address this issue, we’ll look at explaining our results and answering the question: “Why did X classifier predict this specific class for this specific sample?”. The LIME Python library is used for this task, which will be described in the next post." }, { "code": null, "e": 34277, "s": 34206, "text": "If you made it through to the end of this article, thanks for reading!" }, { "code": null, "e": 34351, "s": 34277, "text": "This was Part 1 of a series on fine-grained sentiment analysis in Python." }, { "code": null, "e": 34475, "s": 34351, "text": "Part 2 covers how to build an explainer module using LIME and explain class predictions on two representative test samples." }, { "code": null, "e": 34606, "s": 34475, "text": "Part 3 covers how to further improve the accuracy and F1 scores by building our own transformer model and using transfer learning." } ]
What's the difference between meta name and meta property? - GeeksforGeeks
09 Jun, 2020 Meta Data:The metadata means information about data. So basically Meta tag provides you the information on the HTML document. So basically this tag is an empty tag which means it only has an opening tag and no closing tag. The number of meta tags in an HTML document depends upon the HTML document and it doesn’t affect the physical appearance of the HTML document.The meta tag is always inside the tag. So basically you can use meta property attribute in the body tag but it should contain property element. Various Types of HTML attributes: Name AttributeThis attribute is basically used to explain the name of the property.Http-equivalent attributeThis attribute is basically used to get an HTTP response message head.AuthorBasically it is used to specify the name of the author of the document.DescriptionIt basically shows the description of a particular HTML PageContent AttributeThis attribute is used for particular properties value Name AttributeThis attribute is basically used to explain the name of the property. Http-equivalent attributeThis attribute is basically used to get an HTTP response message head. AuthorBasically it is used to specify the name of the author of the document. DescriptionIt basically shows the description of a particular HTML Page Content AttributeThis attribute is used for particular properties value Meta Property:Meta property is just similar to meta tag the difference arises only when we talk about different editions of HTML. The meta property comes from the RDFa. So basically meta property comes in use to basically link the elements in the body tag as long as they contain a property tag and basically the body tag is the main parent tag and then we use meta property to link another tag in the body tag. <meta property="og:title" content="Main Title"><meta property="og:description" content="About the description"> And it is totally allowed to use Rfda’s property attribute together with html5’s name attribute. You can use Microdata’s itemProp attribute with RFDA’s property only and only if HTML%’s name attribute is not provided. <meta itemprop="description" property="og:description" content="About the description" /> Difference Between Meta tag and Meta property:Basically meta name is the usual name which is very frequently used in HTML documents. So basically what is meta property?. The property attribute comes from the RDFa which is in HTML5. So basically you can use meta property together on the same meta tag for example <meta name="description" property="og:description" content="description about the content" /> Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Misc Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? REST API (Introduction) Design a web page using HTML and CSS How to position a div at the bottom of its container using CSS? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 24651, "s": 24623, "text": "\n09 Jun, 2020" }, { "code": null, "e": 25160, "s": 24651, "text": "Meta Data:The metadata means information about data. So basically Meta tag provides you the information on the HTML document. So basically this tag is an empty tag which means it only has an opening tag and no closing tag. The number of meta tags in an HTML document depends upon the HTML document and it doesn’t affect the physical appearance of the HTML document.The meta tag is always inside the tag. So basically you can use meta property attribute in the body tag but it should contain property element." }, { "code": null, "e": 25194, "s": 25160, "text": "Various Types of HTML attributes:" }, { "code": null, "e": 25592, "s": 25194, "text": "Name AttributeThis attribute is basically used to explain the name of the property.Http-equivalent attributeThis attribute is basically used to get an HTTP response message head.AuthorBasically it is used to specify the name of the author of the document.DescriptionIt basically shows the description of a particular HTML PageContent AttributeThis attribute is used for particular properties value" }, { "code": null, "e": 25676, "s": 25592, "text": "Name AttributeThis attribute is basically used to explain the name of the property." }, { "code": null, "e": 25772, "s": 25676, "text": "Http-equivalent attributeThis attribute is basically used to get an HTTP response message head." }, { "code": null, "e": 25850, "s": 25772, "text": "AuthorBasically it is used to specify the name of the author of the document." }, { "code": null, "e": 25922, "s": 25850, "text": "DescriptionIt basically shows the description of a particular HTML Page" }, { "code": null, "e": 25994, "s": 25922, "text": "Content AttributeThis attribute is used for particular properties value" }, { "code": null, "e": 26406, "s": 25994, "text": "Meta Property:Meta property is just similar to meta tag the difference arises only when we talk about different editions of HTML. The meta property comes from the RDFa. So basically meta property comes in use to basically link the elements in the body tag as long as they contain a property tag and basically the body tag is the main parent tag and then we use meta property to link another tag in the body tag." }, { "code": "<meta property=\"og:title\" content=\"Main Title\"><meta property=\"og:description\" content=\"About the description\">", "e": 26519, "s": 26406, "text": null }, { "code": null, "e": 26616, "s": 26519, "text": "And it is totally allowed to use Rfda’s property attribute together with html5’s name attribute." }, { "code": null, "e": 26737, "s": 26616, "text": "You can use Microdata’s itemProp attribute with RFDA’s property only and only if HTML%’s name attribute is not provided." }, { "code": "<meta itemprop=\"description\" property=\"og:description\" content=\"About the description\" />", "e": 26840, "s": 26737, "text": null }, { "code": null, "e": 27153, "s": 26840, "text": "Difference Between Meta tag and Meta property:Basically meta name is the usual name which is very frequently used in HTML documents. So basically what is meta property?. The property attribute comes from the RDFa which is in HTML5. So basically you can use meta property together on the same meta tag for example" }, { "code": "<meta name=\"description\" property=\"og:description\" content=\"description about the content\" />", "e": 27259, "s": 27153, "text": null }, { "code": null, "e": 27396, "s": 27259, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27406, "s": 27396, "text": "HTML-Misc" }, { "code": null, "e": 27413, "s": 27406, "text": "Picked" }, { "code": null, "e": 27418, "s": 27413, "text": "HTML" }, { "code": null, "e": 27435, "s": 27418, "text": "Web Technologies" }, { "code": null, "e": 27440, "s": 27435, "text": "HTML" }, { "code": null, "e": 27538, "s": 27440, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27547, "s": 27538, "text": "Comments" }, { "code": null, "e": 27560, "s": 27547, "text": "Old Comments" }, { "code": null, "e": 27597, "s": 27560, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27647, "s": 27597, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27671, "s": 27647, "text": "REST API (Introduction)" }, { "code": null, "e": 27708, "s": 27671, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27772, "s": 27708, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 27828, "s": 27772, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27861, "s": 27828, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27904, "s": 27861, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27965, "s": 27904, "text": "Difference between var, let and const keywords in JavaScript" } ]
Maximum rational number (or fraction) from an array in C++
In this problem, we are given a 2-D array that contains rational numbers (one in each row). Our task is to create a program to calculate the maximum rational number (or fraction) from an array in C++. Problem Description − The 2-D array is of the form [n][2]. Each row has two integer values that denote the value of a and b in the equation of rational number, a/b. We need to find the greatest number out of all these rational numbers. Let’s take an example to understand the problem, rat[][] = { {3, 2}, {5, 7}, {1, 9}, {11, 4} } 11 4 The maximum number out of 3/2 , 5/7 , 1/9 , 11/4 is 11/4. To solve the problem, we need to find the values of the numbers and then compare their values. But, this might give an error if the difference between the precision is greater like, if we use float we cannot differentiate between rational numbers, 34.12313431123, and 34.12313431124. So, we will use another method to compare values. This is using the LCM of all denominators and then changing the numerators accordingly. After this, the comparison of the numerators will return the maximum number. Program to show the implementation of our solution, Live Demo #include <bits/stdc++.h> using namespace std; const int n = 4; int findMaxRatNum(int ratNum[n][2]){ int numArray[n]; int LCM = 1; int mavVal = 0, index = 0; for (int i = 0; i < n; i++) LCM = (LCM * ratNum[i][1]) / __gcd(LCM, ratNum[i][1]); for (int i = 0; i < n; i++) { numArray[i] = (ratNum[i][0]) * (LCM / ratNum[i][1]); if (mavVal < numArray[i]) { mavVal = numArray[i]; index = i; } } return index; } int main(){ int ratNum[n][2] = {{3, 2},{5, 7},{1, 9},{11, 4}}; int i = findMaxRatNum(ratNum); cout<<"The maximum rational number from an array is "<<ratNum[i][0]<<"/"<<ratNum[i][1]; } The maximum rational number from an array is 11/4
[ { "code": null, "e": 1263, "s": 1062, "text": "In this problem, we are given a 2-D array that contains rational numbers\n(one in each row). Our task is to create a program to calculate the maximum\nrational number (or fraction) from an array in C++." }, { "code": null, "e": 1499, "s": 1263, "text": "Problem Description − The 2-D array is of the form [n][2]. Each row has two integer values that denote the value of a and b in the equation of rational number, a/b. We need to find the greatest number out of all these rational numbers." }, { "code": null, "e": 1548, "s": 1499, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1606, "s": 1548, "text": "rat[][] = {\n {3, 2},\n {5, 7},\n {1, 9},\n {11, 4}\n}" }, { "code": null, "e": 1611, "s": 1606, "text": "11 4" }, { "code": null, "e": 1637, "s": 1611, "text": "The maximum number out of" }, { "code": null, "e": 1669, "s": 1637, "text": "3/2 , 5/7 , 1/9 , 11/4 is 11/4." }, { "code": null, "e": 1953, "s": 1669, "text": "To solve the problem, we need to find the values of the numbers and then\ncompare their values. But, this might give an error if the difference between\nthe precision is greater like, if we use float we cannot differentiate between\nrational numbers, 34.12313431123, and 34.12313431124." }, { "code": null, "e": 2168, "s": 1953, "text": "So, we will use another method to compare values. This is using the LCM of\nall denominators and then changing the numerators accordingly. After this,\nthe comparison of the numerators will return the maximum number." }, { "code": null, "e": 2220, "s": 2168, "text": "Program to show the implementation of our solution," }, { "code": null, "e": 2231, "s": 2220, "text": " Live Demo" }, { "code": null, "e": 2891, "s": 2231, "text": "#include <bits/stdc++.h>\nusing namespace std;\nconst int n = 4;\nint findMaxRatNum(int ratNum[n][2]){\n int numArray[n];\n int LCM = 1;\n int mavVal = 0, index = 0;\n for (int i = 0; i < n; i++)\n LCM = (LCM * ratNum[i][1]) / __gcd(LCM, ratNum[i][1]);\n for (int i = 0; i < n; i++) {\n numArray[i] = (ratNum[i][0]) * (LCM / ratNum[i][1]);\n if (mavVal < numArray[i]) {\n mavVal = numArray[i];\n index = i;\n }\n }\n return index;\n}\nint main(){\n int ratNum[n][2] = {{3, 2},{5, 7},{1, 9},{11, 4}};\n int i = findMaxRatNum(ratNum);\n cout<<\"The maximum rational number from an array is \"<<ratNum[i][0]<<\"/\"<<ratNum[i][1];\n}" }, { "code": null, "e": 2941, "s": 2891, "text": "The maximum rational number from an array is 11/4" } ]
The Art of Hyperparameter Tuning in Deep Neural Nets by Example | by Rishit Dagli | Towards Data Science
Hello developers 👋, If you have worked on building Deep Neural Networks earlier you might know that building neural nets can involve setting a lot of different hyperparameters. In this article, I will share with you some tips and guidelines you can use to better organize your hyperparameter tuning process which should make it a lot more efficient for you to stumble upon a good setting for the hyperparameters. Very simply a hyperparameter is external to the model that is it cannot be learned within the estimator, and whose value you cannot calculate from the data. Many models have important parameters which cannot be directly estimated from the data. This type of model parameter is referred to as a tuning parameter because there is no analytical formula available to calculate an appropriate value. — Page 64, 65, Applied Predictive Modeling, 2013 The hyperparameters are often used in the processes to help estimate the model parameters and are often to be specified by you. In most cases to tune these hyperparameters, you would be using some heuristic approach based on your experience, maybe starter values for the hyperparameters or find the best values by trial and error for a given problem. As I was saying at the start of this article, one of the painful things about training Deep Neural Networks is the large number of hyperparameters you have to deal with. These could be your learning rate α, the discounting factor ρ, and epsilon ε if you are using the RMSprop optimizer (Hinton et al.) or the exponential decay rates β1 and β2 if you are using the Adam optimizer (Kingma et al.). You also need to choose the number of layers in the network or the number of hidden units for the layers, you might be using learning rate schedulers and would want to configure that and a lot more😩! We definitely need ways to better organize our hyperparameter tuning process. Usually, we can categorize hyperparameters into two groups: the hyperparameters used for training and those used for model design🖌️. A proper choice of hyperparameters related to model training would allow neural networks to learn faster and achieve enhanced performance making the tuning process, definitely something you would want to care about. The hyperparameters for model design are more related to the structure of neural networks a trivial example being the number of hidden layers and the width of these layers. The model training hyperparameters in most cases could well serve as a way to measure a model’s learning capacity🧠. During the training process, I usually give the most attention to the learning rate α, and the batch size because these determine the speed of convergence so you should consider tuning them first or give them more attention. However, I do strongly believe that for most models the learning rate α would be the most important hyperparameter to tune consequently deserving more attention. We will later in this article discuss ways to select the learning rate. Also do note that I mention “usually” over here, this could most certainly change according to the kind of applications you are building. Next up, I usually consider tuning the momentum term β in RMSprop and others since this helps us reduces the oscillation by strengthening the weight updates in the same direction, also allowing us to decrease the change in different directions. I often suggest using β = 0.9 which works as a very good default and is most often used too. After doing so I would try and tune the number of hidden units for each layer followed by the number of hidden layers which essentially help change the model structure followed by the learning rate decay which we will soon see. Note: The order suggested in this paragraph has seemed to work well for me and was originally suggested by Andrew Ng. Furthermore, a really helpful summary about the order of importance of hyperparameters from lecture notes of Ng was compiled by Tong Yu and Hong Zhu in their paper suggesting this order: learning rate Momentum β, for RMSprop, etc. Mini-batch size Number of hidden layers learning rate decay Regularization λ The things we talk about under this section would essentially be some things I find important and apply while the tuning of any hyperparameter. So, we will not be talking about things related to tuning for a specific hyperparameter but concepts that apply to all of them. Random Search and Grid Search (a pre-cursor of Random Search) are by far the most widely used methods because of their simplicity. Earlier it was very common to sample the points in a grid and then systematically perform an exhaustive search on the hyperparameter set specified by users. And this works well and is applicable for several hyperparameters with limited search space. In the diagram here as we mention Grid Search asks us to systematically sample the points and try out those values after which we could choose the one which best suits us. To perform hyperparameter tuning for deep neural nets it is often recommended to rather choose points at random. So in the image above, we choose the same number of points but do not follow a systemic approach to choosing those points like on the left side. And the reason you often do that is that it is difficult to know in advance which hyperparameters are going to be the most important for your problem. Let us say the hyperparameter 1 here matters a lot for your problem and hyperparameter 2 contributes very less you essentially get to try out just 5 values of hyperparameter 1 and you might find almost the same results after trying the values of hyperparameter 2 since it does not contribute a lot. On other hand, if you had used random sampling you would more richly explore the set of possible values. So, we could use random search in the early stage of the tuning process to rapidly narrow down the search space, before we start using a guided algorithm to obtain finer results that go from a coarse to fine sampling scheme. Here is a simple example with TensorFlow where I try to use Random Search on the Fashion MNIST Dataset for the learning rate and the number of units: Hyperband (Li et al.) is another algorithm I tend to use quite often, it is essentially a slight improvement of Random Search incorporating adaptive resource allocation and early-stopping to quickly converge on a high-performing model. Here we train a large number of models for a few epochs and carry forward only the top-performing half of models to the next round. Early stopping is particularly useful for deep learning scenarios where a deep neural network is trained over a number of epochs. The training script can report the target metric after each epoch, and if the run is significantly underperforming previous runs after the same number of intervals, it can be abandoned. Here is a simple example with TensorFlow where I try to use Hyperband on the Fashion MNIST Dataset for the learning rate and the number of units: I am particularly interested in talking more about choosing an appropriate learning rate α since for most learning applications it is the most important hyperparameter to tune consequently also deserving more attention. Having a constant learning rate is the most straightforward approach and is often set as the default schedule: optimizer = tf.keras.optimizers.Adam(learning_rate = 0.01) However, it turns out that with a constant LR, the network can often be trained to a sufficient, but unsatisfactory accuracy because the initial value could always prove to be larger, especially in the final few steps of gradient descent. The optimal learning rate would depend on the topology of your loss landscape, which is in turn dependent on both the model architecture and the dataset. So we can say that an optimal learning rate would give us a steep drop in the loss function. Decreasing the learning rate would decrease the loss function but it would do so at a very shallow rate. On other hand increasing the learning rate after the optimal one will cause the loss to bounce about the minima. Here is a figure to sum this up: You now understand why it is important to choose a learning rate effectively and with that let’s talk a bit about updating your learning rates while training or setting a schedule. A prevalent technique, known as learning rate annealing, is often used, it recommends starting with a relatively high learning rate and then gradually lowering the learning rate📉 during training. As an example, I could start with a learning rate of 10−2 when the accuracy is saturated or I reach a plateau we could lower the learning rate to let’s say 10−3 and maybe then to 10−5 if required. In training deep networks, it is usually helpful to anneal the learning rate over time. Good intuition to have in mind is that with a high learning rate, the system contains too much kinetic energy and the parameter vector bounces around chaotically, unable to settle down into deeper, but narrower parts of the loss function. — Stanford CS231n Course Notes by Fei-Fei Li, Ranjay Krishna, and Danfei Xu Going back to the example above, I suspect that my learning rate should be somewhere between 10−2 and 10−5 so if I simply update my learning rate uniformly across this range, we use 90% of the resource for the range 10−2 to 10−3 which does not make sense. You could rather update the LR on the log scale, this allows us to use an equal amount of resources for 10−2 to 10−3 and between 10−3 to 10−4. Now it should be super easy for you😎 to understand exponential decay which is a widely used LR schedule (Li et al.). An exponential schedule provides a more drastic decay at the beginning and a gentle decay when approaching convergence. Here is an example showing how we can perform exponential decay with TensorFlow: Also, note that the initial values are influential and must be carefully determined, in this case, though you might want to use a comparatively large value because it will decay during training. To better help us understand why I will later suggest some good default values for the momentum term, I would like to show a bit about why the momentum term is used in RMSprop and some others. The idea behind RMSprop is to accelerate the gradient descent like the precursors Adagrad (Duchi et al.) and Adadelta (Zeiler et al.) but gives superior performance when steps become smaller. RMSprop uses exponentially weighted averages of the squares instead of directly using ∂w and ∂b: Now you might have guessed until now the moving average term β should be a value between 0 and 1. In practice, most of the time 0.9 works well (also suggested by Geoffrey Hinton) and I would say is a really good default value. You would often consider trying out a value between 0.9 (averaging across the last 10 values) and 0.999 (averaging across the last 1000 values). Here is a really wonderful diagram to summarize the effect of β. Here the: red-colored line represents β = 0.9 green-colored line represents β = 0.98 As you can see, with smaller numbers of β, the new sequence turns out to be fluctuating a lot, because we’re averaging over a smaller number of examples and therefore are much closer to the noisy data. However with bigger values of beta, like β, we get a much smoother curve, but it’s a little bit shifted to the right because we average over a larger number of examples. So in all 0.9 provides a good balance but as I mentioned earlier you would often consider trying out a value between 0.9 and 0.999. Just as we talked about searching for a good learning rate α and how it does not make sense to do this in the linear scale rather we do this in the logarithmic scale in this article. Similarly, if you are searching for a good value of β it would again not make sense to perform the search uniformly at random between 0.9 and 0.999. So a simple trick might be to instead search for 1-β in the range 10−1 to 10−3 and we will search for it in the log scale. Here’s some sample code to generate these values in the log scale which we can then search across: r = -2 * np.random.rand() # gives us random values between -2, 0r = r - 1 # convert them to -3, -1beta = 1 - 10**r I will not be talking about some specific rules or suggestions about the number of hidden layers and you will soon understand why I do not do so (by example). The number of hidden layers d is a pretty critical parameter for determining the overall structure of neural networks, which has a direct influence on the final output. I have seen almost always that deep learning networks with more layers often obtain more complex features and relatively higher accuracy making this a regular approach to achieving better results. As an example, the ResNet model (He et al.) can be scaled up from ResNet-18 to ResNet-200 by simply using more layers, repeating the baseline structure according to their need for accuracy. Recently, Yanping Huang et al. in their paper achieved 84.3 % ImageNet top-1 accuracy by scaling up a baseline model four times larger! The number of neurons in each layer w must also be carefully considered after having talked about the number of layers. Too few neurons in the hidden layers may cause underfitting because the model lacks complexity. By contrast, too many neurons may result in overfitting and increase training time. A couple of suggestions by Jeff Heaton that have worked like a charm could be a good start for tuning the number of neurons. to make it easy to understand here I use winput as the number of neurons for the input layer and woutput as the number of neurons for the output layer. The number of hidden neurons should be between the size of the input layer and the size of the output layer. winput < w < woutput The number of hidden neurons should be 2/3 the size of the input layer, plus the size of the output layer. w = 2/3 winput + woutput The number of hidden neurons should be less than twice the size of the input layer. winput < 2 woutput And that is it for helping you choose the Model Design Hyperparameters🖌️, I would personally suggest you also take a look at getting some more idea about tuning the regularization λ and has a sizable impact on the model weights if you are interested in that you can take a look at this blog I wrote some time back addressing this in detail: towardsdatascience.com Yeah! By including all of these concepts I hope you can start better tuning your hyperparameters and building better models and start perfecting the “Art of Hyperparameter tuning”🚀. I hope you liked this article. If you liked this article, share it with everyone😄! Sharing is caring! Thank you! Many thanks to Alexandru Petrescu for helping me to make this better :)
[ { "code": null, "e": 585, "s": 172, "text": "Hello developers 👋, If you have worked on building Deep Neural Networks earlier you might know that building neural nets can involve setting a lot of different hyperparameters. In this article, I will share with you some tips and guidelines you can use to better organize your hyperparameter tuning process which should make it a lot more efficient for you to stumble upon a good setting for the hyperparameters." }, { "code": null, "e": 742, "s": 585, "text": "Very simply a hyperparameter is external to the model that is it cannot be learned within the estimator, and whose value you cannot calculate from the data." }, { "code": null, "e": 980, "s": 742, "text": "Many models have important parameters which cannot be directly estimated from the data. This type of model parameter is referred to as a tuning parameter because there is no analytical formula available to calculate an appropriate value." }, { "code": null, "e": 1029, "s": 980, "text": "— Page 64, 65, Applied Predictive Modeling, 2013" }, { "code": null, "e": 1380, "s": 1029, "text": "The hyperparameters are often used in the processes to help estimate the model parameters and are often to be specified by you. In most cases to tune these hyperparameters, you would be using some heuristic approach based on your experience, maybe starter values for the hyperparameters or find the best values by trial and error for a given problem." }, { "code": null, "e": 2054, "s": 1380, "text": "As I was saying at the start of this article, one of the painful things about training Deep Neural Networks is the large number of hyperparameters you have to deal with. These could be your learning rate α, the discounting factor ρ, and epsilon ε if you are using the RMSprop optimizer (Hinton et al.) or the exponential decay rates β1 and β2 if you are using the Adam optimizer (Kingma et al.). You also need to choose the number of layers in the network or the number of hidden units for the layers, you might be using learning rate schedulers and would want to configure that and a lot more😩! We definitely need ways to better organize our hyperparameter tuning process." }, { "code": null, "e": 2692, "s": 2054, "text": "Usually, we can categorize hyperparameters into two groups: the hyperparameters used for training and those used for model design🖌️. A proper choice of hyperparameters related to model training would allow neural networks to learn faster and achieve enhanced performance making the tuning process, definitely something you would want to care about. The hyperparameters for model design are more related to the structure of neural networks a trivial example being the number of hidden layers and the width of these layers. The model training hyperparameters in most cases could well serve as a way to measure a model’s learning capacity🧠." }, { "code": null, "e": 3289, "s": 2692, "text": "During the training process, I usually give the most attention to the learning rate α, and the batch size because these determine the speed of convergence so you should consider tuning them first or give them more attention. However, I do strongly believe that for most models the learning rate α would be the most important hyperparameter to tune consequently deserving more attention. We will later in this article discuss ways to select the learning rate. Also do note that I mention “usually” over here, this could most certainly change according to the kind of applications you are building." }, { "code": null, "e": 3627, "s": 3289, "text": "Next up, I usually consider tuning the momentum term β in RMSprop and others since this helps us reduces the oscillation by strengthening the weight updates in the same direction, also allowing us to decrease the change in different directions. I often suggest using β = 0.9 which works as a very good default and is most often used too." }, { "code": null, "e": 3973, "s": 3627, "text": "After doing so I would try and tune the number of hidden units for each layer followed by the number of hidden layers which essentially help change the model structure followed by the learning rate decay which we will soon see. Note: The order suggested in this paragraph has seemed to work well for me and was originally suggested by Andrew Ng." }, { "code": null, "e": 4160, "s": 3973, "text": "Furthermore, a really helpful summary about the order of importance of hyperparameters from lecture notes of Ng was compiled by Tong Yu and Hong Zhu in their paper suggesting this order:" }, { "code": null, "e": 4174, "s": 4160, "text": "learning rate" }, { "code": null, "e": 4204, "s": 4174, "text": "Momentum β, for RMSprop, etc." }, { "code": null, "e": 4220, "s": 4204, "text": "Mini-batch size" }, { "code": null, "e": 4244, "s": 4220, "text": "Number of hidden layers" }, { "code": null, "e": 4264, "s": 4244, "text": "learning rate decay" }, { "code": null, "e": 4281, "s": 4264, "text": "Regularization λ" }, { "code": null, "e": 4553, "s": 4281, "text": "The things we talk about under this section would essentially be some things I find important and apply while the tuning of any hyperparameter. So, we will not be talking about things related to tuning for a specific hyperparameter but concepts that apply to all of them." }, { "code": null, "e": 5106, "s": 4553, "text": "Random Search and Grid Search (a pre-cursor of Random Search) are by far the most widely used methods because of their simplicity. Earlier it was very common to sample the points in a grid and then systematically perform an exhaustive search on the hyperparameter set specified by users. And this works well and is applicable for several hyperparameters with limited search space. In the diagram here as we mention Grid Search asks us to systematically sample the points and try out those values after which we could choose the one which best suits us." }, { "code": null, "e": 5919, "s": 5106, "text": "To perform hyperparameter tuning for deep neural nets it is often recommended to rather choose points at random. So in the image above, we choose the same number of points but do not follow a systemic approach to choosing those points like on the left side. And the reason you often do that is that it is difficult to know in advance which hyperparameters are going to be the most important for your problem. Let us say the hyperparameter 1 here matters a lot for your problem and hyperparameter 2 contributes very less you essentially get to try out just 5 values of hyperparameter 1 and you might find almost the same results after trying the values of hyperparameter 2 since it does not contribute a lot. On other hand, if you had used random sampling you would more richly explore the set of possible values." }, { "code": null, "e": 6294, "s": 5919, "text": "So, we could use random search in the early stage of the tuning process to rapidly narrow down the search space, before we start using a guided algorithm to obtain finer results that go from a coarse to fine sampling scheme. Here is a simple example with TensorFlow where I try to use Random Search on the Fashion MNIST Dataset for the learning rate and the number of units:" }, { "code": null, "e": 6662, "s": 6294, "text": "Hyperband (Li et al.) is another algorithm I tend to use quite often, it is essentially a slight improvement of Random Search incorporating adaptive resource allocation and early-stopping to quickly converge on a high-performing model. Here we train a large number of models for a few epochs and carry forward only the top-performing half of models to the next round." }, { "code": null, "e": 6978, "s": 6662, "text": "Early stopping is particularly useful for deep learning scenarios where a deep neural network is trained over a number of epochs. The training script can report the target metric after each epoch, and if the run is significantly underperforming previous runs after the same number of intervals, it can be abandoned." }, { "code": null, "e": 7124, "s": 6978, "text": "Here is a simple example with TensorFlow where I try to use Hyperband on the Fashion MNIST Dataset for the learning rate and the number of units:" }, { "code": null, "e": 7455, "s": 7124, "text": "I am particularly interested in talking more about choosing an appropriate learning rate α since for most learning applications it is the most important hyperparameter to tune consequently also deserving more attention. Having a constant learning rate is the most straightforward approach and is often set as the default schedule:" }, { "code": null, "e": 7514, "s": 7455, "text": "optimizer = tf.keras.optimizers.Adam(learning_rate = 0.01)" }, { "code": null, "e": 8251, "s": 7514, "text": "However, it turns out that with a constant LR, the network can often be trained to a sufficient, but unsatisfactory accuracy because the initial value could always prove to be larger, especially in the final few steps of gradient descent. The optimal learning rate would depend on the topology of your loss landscape, which is in turn dependent on both the model architecture and the dataset. So we can say that an optimal learning rate would give us a steep drop in the loss function. Decreasing the learning rate would decrease the loss function but it would do so at a very shallow rate. On other hand increasing the learning rate after the optimal one will cause the loss to bounce about the minima. Here is a figure to sum this up:" }, { "code": null, "e": 8825, "s": 8251, "text": "You now understand why it is important to choose a learning rate effectively and with that let’s talk a bit about updating your learning rates while training or setting a schedule. A prevalent technique, known as learning rate annealing, is often used, it recommends starting with a relatively high learning rate and then gradually lowering the learning rate📉 during training. As an example, I could start with a learning rate of 10−2 when the accuracy is saturated or I reach a plateau we could lower the learning rate to let’s say 10−3 and maybe then to 10−5 if required." }, { "code": null, "e": 9152, "s": 8825, "text": "In training deep networks, it is usually helpful to anneal the learning rate over time. Good intuition to have in mind is that with a high learning rate, the system contains too much kinetic energy and the parameter vector bounces around chaotically, unable to settle down into deeper, but narrower parts of the loss function." }, { "code": null, "e": 9228, "s": 9152, "text": "— Stanford CS231n Course Notes by Fei-Fei Li, Ranjay Krishna, and Danfei Xu" }, { "code": null, "e": 9864, "s": 9228, "text": "Going back to the example above, I suspect that my learning rate should be somewhere between 10−2 and 10−5 so if I simply update my learning rate uniformly across this range, we use 90% of the resource for the range 10−2 to 10−3 which does not make sense. You could rather update the LR on the log scale, this allows us to use an equal amount of resources for 10−2 to 10−3 and between 10−3 to 10−4. Now it should be super easy for you😎 to understand exponential decay which is a widely used LR schedule (Li et al.). An exponential schedule provides a more drastic decay at the beginning and a gentle decay when approaching convergence." }, { "code": null, "e": 9945, "s": 9864, "text": "Here is an example showing how we can perform exponential decay with TensorFlow:" }, { "code": null, "e": 10140, "s": 9945, "text": "Also, note that the initial values are influential and must be carefully determined, in this case, though you might want to use a comparatively large value because it will decay during training." }, { "code": null, "e": 10622, "s": 10140, "text": "To better help us understand why I will later suggest some good default values for the momentum term, I would like to show a bit about why the momentum term is used in RMSprop and some others. The idea behind RMSprop is to accelerate the gradient descent like the precursors Adagrad (Duchi et al.) and Adadelta (Zeiler et al.) but gives superior performance when steps become smaller. RMSprop uses exponentially weighted averages of the squares instead of directly using ∂w and ∂b:" }, { "code": null, "e": 11069, "s": 10622, "text": "Now you might have guessed until now the moving average term β should be a value between 0 and 1. In practice, most of the time 0.9 works well (also suggested by Geoffrey Hinton) and I would say is a really good default value. You would often consider trying out a value between 0.9 (averaging across the last 10 values) and 0.999 (averaging across the last 1000 values). Here is a really wonderful diagram to summarize the effect of β. Here the:" }, { "code": null, "e": 11105, "s": 11069, "text": "red-colored line represents β = 0.9" }, { "code": null, "e": 11144, "s": 11105, "text": "green-colored line represents β = 0.98" }, { "code": null, "e": 11648, "s": 11144, "text": "As you can see, with smaller numbers of β, the new sequence turns out to be fluctuating a lot, because we’re averaging over a smaller number of examples and therefore are much closer to the noisy data. However with bigger values of beta, like β, we get a much smoother curve, but it’s a little bit shifted to the right because we average over a larger number of examples. So in all 0.9 provides a good balance but as I mentioned earlier you would often consider trying out a value between 0.9 and 0.999." }, { "code": null, "e": 12202, "s": 11648, "text": "Just as we talked about searching for a good learning rate α and how it does not make sense to do this in the linear scale rather we do this in the logarithmic scale in this article. Similarly, if you are searching for a good value of β it would again not make sense to perform the search uniformly at random between 0.9 and 0.999. So a simple trick might be to instead search for 1-β in the range 10−1 to 10−3 and we will search for it in the log scale. Here’s some sample code to generate these values in the log scale which we can then search across:" }, { "code": null, "e": 12333, "s": 12202, "text": "r = -2 * np.random.rand() # gives us random values between -2, 0r = r - 1 # convert them to -3, -1beta = 1 - 10**r" }, { "code": null, "e": 12492, "s": 12333, "text": "I will not be talking about some specific rules or suggestions about the number of hidden layers and you will soon understand why I do not do so (by example)." }, { "code": null, "e": 12858, "s": 12492, "text": "The number of hidden layers d is a pretty critical parameter for determining the overall structure of neural networks, which has a direct influence on the final output. I have seen almost always that deep learning networks with more layers often obtain more complex features and relatively higher accuracy making this a regular approach to achieving better results." }, { "code": null, "e": 13184, "s": 12858, "text": "As an example, the ResNet model (He et al.) can be scaled up from ResNet-18 to ResNet-200 by simply using more layers, repeating the baseline structure according to their need for accuracy. Recently, Yanping Huang et al. in their paper achieved 84.3 % ImageNet top-1 accuracy by scaling up a baseline model four times larger!" }, { "code": null, "e": 13484, "s": 13184, "text": "The number of neurons in each layer w must also be carefully considered after having talked about the number of layers. Too few neurons in the hidden layers may cause underfitting because the model lacks complexity. By contrast, too many neurons may result in overfitting and increase training time." }, { "code": null, "e": 13761, "s": 13484, "text": "A couple of suggestions by Jeff Heaton that have worked like a charm could be a good start for tuning the number of neurons. to make it easy to understand here I use winput as the number of neurons for the input layer and woutput as the number of neurons for the output layer." }, { "code": null, "e": 13891, "s": 13761, "text": "The number of hidden neurons should be between the size of the input layer and the size of the output layer. winput < w < woutput" }, { "code": null, "e": 14023, "s": 13891, "text": "The number of hidden neurons should be 2/3 the size of the input layer, plus the size of the output layer. w = 2/3 winput + woutput" }, { "code": null, "e": 14126, "s": 14023, "text": "The number of hidden neurons should be less than twice the size of the input layer. winput < 2 woutput" }, { "code": null, "e": 14467, "s": 14126, "text": "And that is it for helping you choose the Model Design Hyperparameters🖌️, I would personally suggest you also take a look at getting some more idea about tuning the regularization λ and has a sizable impact on the model weights if you are interested in that you can take a look at this blog I wrote some time back addressing this in detail:" }, { "code": null, "e": 14490, "s": 14467, "text": "towardsdatascience.com" }, { "code": null, "e": 14703, "s": 14490, "text": "Yeah! By including all of these concepts I hope you can start better tuning your hyperparameters and building better models and start perfecting the “Art of Hyperparameter tuning”🚀. I hope you liked this article." }, { "code": null, "e": 14785, "s": 14703, "text": "If you liked this article, share it with everyone😄! Sharing is caring! Thank you!" } ]
string.gsub() function in Lua programming
There are scenarios when we want to change a pattern that we found in a string with our pattern, and in Lua for that we have a famous library function, named the string.gsub() function. The string.gsub() function has three arguments, the first is the subject string, in which we are trying to replace a substring to another substring, the second argument is the pattern that we want to replace in the given string, and the third argument is the string from which we want to replace the pattern. string.gsub(x,a,b) In the above syntax, the x identifier is used to denote the string in which we are trying to replace a pattern, the a identifier is the pattern that we want to replace, and the b identifier is the pattern with which we want to replace the substring that we found. Now, let’s consider a basic example of the string.gsub() in Lua. Consider the example shown below − Live Demo s = string.gsub("Lua is good", "good", "great") print(s)--> Lua is great Lua is great Let’s consider one more simple example, so that you understand it completely. Consider the example shown below − Live Demo s = string.gsub("hello lii", "l", "x") print(s) hexxo xii It should be noted that if we provide a pattern that is not present in the string, then nothing will change, the string will remain the same. Consider the example shown below − Live Demo s = string.gsub("Lua is good", "ok", "great") print(s) Lua is good There’s also a fourth argument that we can pass in the string.gsub() function and that fourth argument will be used to limit the number of substitutions to be made. Consider the example shown below − Live Demo s = string.gsub("lua is lua and lua", "lua", "he",2) print(s) he is he and lua
[ { "code": null, "e": 1248, "s": 1062, "text": "There are scenarios when we want to change a pattern that we found in a string with our pattern, and in Lua for that we have a famous library function, named the string.gsub() function." }, { "code": null, "e": 1557, "s": 1248, "text": "The string.gsub() function has three arguments, the first is the subject string, in which we are trying to replace a substring to another substring, the second argument is the pattern that we want to replace in the given string, and the third argument is the string from which we want to replace the pattern." }, { "code": null, "e": 1576, "s": 1557, "text": "string.gsub(x,a,b)" }, { "code": null, "e": 1840, "s": 1576, "text": "In the above syntax, the x identifier is used to denote the string in which we are trying to replace a pattern, the a identifier is the pattern that we want to replace, and the b identifier is the pattern with which we want to replace the substring that we found." }, { "code": null, "e": 1905, "s": 1840, "text": "Now, let’s consider a basic example of the string.gsub() in Lua." }, { "code": null, "e": 1940, "s": 1905, "text": "Consider the example shown below −" }, { "code": null, "e": 1951, "s": 1940, "text": " Live Demo" }, { "code": null, "e": 2024, "s": 1951, "text": "s = string.gsub(\"Lua is good\", \"good\", \"great\")\nprint(s)--> Lua is great" }, { "code": null, "e": 2037, "s": 2024, "text": "Lua is great" }, { "code": null, "e": 2115, "s": 2037, "text": "Let’s consider one more simple example, so that you understand it completely." }, { "code": null, "e": 2150, "s": 2115, "text": "Consider the example shown below −" }, { "code": null, "e": 2161, "s": 2150, "text": " Live Demo" }, { "code": null, "e": 2209, "s": 2161, "text": "s = string.gsub(\"hello lii\", \"l\", \"x\")\nprint(s)" }, { "code": null, "e": 2219, "s": 2209, "text": "hexxo xii" }, { "code": null, "e": 2361, "s": 2219, "text": "It should be noted that if we provide a pattern that is not present in the string, then nothing will change, the string will remain the same." }, { "code": null, "e": 2396, "s": 2361, "text": "Consider the example shown below −" }, { "code": null, "e": 2407, "s": 2396, "text": " Live Demo" }, { "code": null, "e": 2462, "s": 2407, "text": "s = string.gsub(\"Lua is good\", \"ok\", \"great\")\nprint(s)" }, { "code": null, "e": 2474, "s": 2462, "text": "Lua is good" }, { "code": null, "e": 2639, "s": 2474, "text": "There’s also a fourth argument that we can pass in the string.gsub() function and that fourth argument will be used to limit the number of substitutions to be made." }, { "code": null, "e": 2674, "s": 2639, "text": "Consider the example shown below −" }, { "code": null, "e": 2685, "s": 2674, "text": " Live Demo" }, { "code": null, "e": 2747, "s": 2685, "text": "s = string.gsub(\"lua is lua and lua\", \"lua\", \"he\",2)\nprint(s)" }, { "code": null, "e": 2764, "s": 2747, "text": "he is he and lua" } ]
Messaging Via Azure Service bus | SendMessage and ScheduleMessage - GeeksforGeeks
27 Feb, 2020 In this section, we are going to discuss in brief about the data transfer methods to transfer data across Azure topics via service bus pooling. We can either send a normal message or a schedule based message. We will walk through each of these two basic type of messaging. Azure Service Bus: Microsoft Azure Service Bus is a fully managed enterprise integration messaging service on cloud used to connect any applications, devices, and services running in the cloud to any other applications or services. This platform acts as a messaging backbone for applications over cloud and across any devices. How does it work ? Data is transferred between different applications and services using messages. A message is in binary format and can contain JSON, XML, or just text. These messages are placed on to the service bus the application is connected with, so that all or specific users connected on, with this application, over the socket service connection open can receive the data transferred over the service bus. Types of messaging: Data Messages transferred over the Azure service bus can be made of two major types, whether the data need to be sent on a specific schedule or is that required to be sent on immediate basis. Here we will discuss in detail about both these process of messaging. Each of these has its own specific methods for invoking the messaging process. Send Message Immediate: The send() function call sends a message to the Azure Service Bus to which the current sender is connected to. This method makes a non-asynchronous call. You also have an asynchronous version to improve performance.Prototype:send( IMessage message )Sample Code:public static async sendMessage(content: Message): Promise<string> { const serviceConnection = AzureServiceBus.createConnection(); const client = serviceConnection.createQueueClient("" + process.env.AZURE_SERVICEBUS_QUEUE); const sender = client.createSender(); let response = ""; try { const scheduledEnqueueTimeUtc = moment().utc().add(1, "m").toDate(); await sender.send( {body: JSON.stringify(content), label: "MyTopic"}); await client.close(); } catch (error) { } finally { await serviceConnection.close(); } return resp;} Prototype: send( IMessage message ) Sample Code: public static async sendMessage(content: Message): Promise<string> { const serviceConnection = AzureServiceBus.createConnection(); const client = serviceConnection.createQueueClient("" + process.env.AZURE_SERVICEBUS_QUEUE); const sender = client.createSender(); let response = ""; try { const scheduledEnqueueTimeUtc = moment().utc().add(1, "m").toDate(); await sender.send( {body: JSON.stringify(content), label: "MyTopic"}); await client.close(); } catch (error) { } finally { await serviceConnection.close(); } return resp;} Schedule Message: This method sends a timer-based message to the Azure Service Bus the invoking sender is connected with. It enqueues the message into the bus to scheduled time message, the message is delivered to the receiver end. This is currently asynchronous process for better performance.Prototype:scheduleMessage( IMessage message, Instant scheduledEnqueueTimeUtc )Sample Code:public static async sendScheduleMessage( content: Message): Promise<string> { const serviceConnection = AzureServiceBus.createConnection(); const client = serviceConnection.createQueueClient( "" + process.env.AZURE_SERVICEBUS_QUEUE); const sender = client.createSender(); let response = ""; try { const scheduledEnqueueTimeUtc = moment().utc().add(1, "m").toDate(); const sequenceId = await sender.scheduleMessage( scheduledEnqueueTimeUtc, {body: JSON.stringify(content), label: "MyTopic"}); response = sequenceId.toString(); await client.close(); } catch (error) { } finally { await serviceConnection.close(); } return resp;}This will raise an issue that the sequenceId value will go “undefined”. The Azure portal has provided with a fix that the message needs to be encoded and then placed into the service bus in order to get the correct sequenceId back. Prototype: scheduleMessage( IMessage message, Instant scheduledEnqueueTimeUtc ) Sample Code: public static async sendScheduleMessage( content: Message): Promise<string> { const serviceConnection = AzureServiceBus.createConnection(); const client = serviceConnection.createQueueClient( "" + process.env.AZURE_SERVICEBUS_QUEUE); const sender = client.createSender(); let response = ""; try { const scheduledEnqueueTimeUtc = moment().utc().add(1, "m").toDate(); const sequenceId = await sender.scheduleMessage( scheduledEnqueueTimeUtc, {body: JSON.stringify(content), label: "MyTopic"}); response = sequenceId.toString(); await client.close(); } catch (error) { } finally { await serviceConnection.close(); } return resp;} This will raise an issue that the sequenceId value will go “undefined”. The Azure portal has provided with a fix that the message needs to be encoded and then placed into the service bus in order to get the correct sequenceId back. Bug Fix: import { DefaultDataTransformer } from "@azure/amqp-common";...... const dt = new DefaultDataTransformer(); const sequenceId = await sender.scheduleMessage( scheduledEnqueueTimeUtc, {body: dt.encode(JSON.stringify(content)), label: "MyTopic"}); response = sequenceId.toString(); Now you will receive the proper sequenceId, which you can use to cancel the message if required in the future using the following code piece. CancelMessage: This method deleted the message placed in the service bus early using the scheduleMessage call. We need to send the sequenceNumber returned during the call as the only parameter for this method invocation. If the message is already delivered then we receive an error MessageNotFound which needs to be handled in the catch. Prototype: cancelScheduledMessage( long sequenceNumber ) Thus we have covered how we can communicate data by using the above two methods and placing the data requests either via a scheduled basis or non scheduled manner. Cloud-Computing Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Front End Developer Skills That You Need in 2022 How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page? Node.js fs.readFileSync() Method How to redirect to another page in ReactJS ? How to Insert Form Data into Database using PHP ? How to pass data from child component to its parent in ReactJS ?
[ { "code": null, "e": 24733, "s": 24705, "text": "\n27 Feb, 2020" }, { "code": null, "e": 25006, "s": 24733, "text": "In this section, we are going to discuss in brief about the data transfer methods to transfer data across Azure topics via service bus pooling. We can either send a normal message or a schedule based message. We will walk through each of these two basic type of messaging." }, { "code": null, "e": 25333, "s": 25006, "text": "Azure Service Bus: Microsoft Azure Service Bus is a fully managed enterprise integration messaging service on cloud used to connect any applications, devices, and services running in the cloud to any other applications or services. This platform acts as a messaging backbone for applications over cloud and across any devices." }, { "code": null, "e": 25748, "s": 25333, "text": "How does it work ? Data is transferred between different applications and services using messages. A message is in binary format and can contain JSON, XML, or just text. These messages are placed on to the service bus the application is connected with, so that all or specific users connected on, with this application, over the socket service connection open can receive the data transferred over the service bus." }, { "code": null, "e": 26109, "s": 25748, "text": "Types of messaging: Data Messages transferred over the Azure service bus can be made of two major types, whether the data need to be sent on a specific schedule or is that required to be sent on immediate basis. Here we will discuss in detail about both these process of messaging. Each of these has its own specific methods for invoking the messaging process." }, { "code": null, "e": 27083, "s": 26109, "text": "Send Message Immediate: The send() function call sends a message to the Azure Service Bus to which the current sender is connected to. This method makes a non-asynchronous call. You also have an asynchronous version to improve performance.Prototype:send( IMessage message )Sample Code:public static async sendMessage(content: Message): Promise<string> { const serviceConnection = AzureServiceBus.createConnection(); const client = serviceConnection.createQueueClient(\"\" + process.env.AZURE_SERVICEBUS_QUEUE); const sender = client.createSender(); let response = \"\"; try { const scheduledEnqueueTimeUtc = moment().utc().add(1, \"m\").toDate(); await sender.send( {body: JSON.stringify(content), label: \"MyTopic\"}); await client.close(); } catch (error) { } finally { await serviceConnection.close(); } return resp;}" }, { "code": null, "e": 27094, "s": 27083, "text": "Prototype:" }, { "code": null, "e": 27119, "s": 27094, "text": "send( IMessage message )" }, { "code": null, "e": 27132, "s": 27119, "text": "Sample Code:" }, { "code": "public static async sendMessage(content: Message): Promise<string> { const serviceConnection = AzureServiceBus.createConnection(); const client = serviceConnection.createQueueClient(\"\" + process.env.AZURE_SERVICEBUS_QUEUE); const sender = client.createSender(); let response = \"\"; try { const scheduledEnqueueTimeUtc = moment().utc().add(1, \"m\").toDate(); await sender.send( {body: JSON.stringify(content), label: \"MyTopic\"}); await client.close(); } catch (error) { } finally { await serviceConnection.close(); } return resp;}", "e": 27821, "s": 27132, "text": null }, { "code": null, "e": 29252, "s": 27821, "text": "Schedule Message: This method sends a timer-based message to the Azure Service Bus the invoking sender is connected with. It enqueues the message into the bus to scheduled time message, the message is delivered to the receiver end. This is currently asynchronous process for better performance.Prototype:scheduleMessage( IMessage message, Instant scheduledEnqueueTimeUtc )Sample Code:public static async sendScheduleMessage( content: Message): Promise<string> { const serviceConnection = AzureServiceBus.createConnection(); const client = serviceConnection.createQueueClient( \"\" + process.env.AZURE_SERVICEBUS_QUEUE); const sender = client.createSender(); let response = \"\"; try { const scheduledEnqueueTimeUtc = moment().utc().add(1, \"m\").toDate(); const sequenceId = await sender.scheduleMessage( scheduledEnqueueTimeUtc, {body: JSON.stringify(content), label: \"MyTopic\"}); response = sequenceId.toString(); await client.close(); } catch (error) { } finally { await serviceConnection.close(); } return resp;}This will raise an issue that the sequenceId value will go “undefined”. The Azure portal has provided with a fix that the message needs to be encoded and then placed into the service bus in order to get the correct sequenceId back." }, { "code": null, "e": 29263, "s": 29252, "text": "Prototype:" }, { "code": null, "e": 29332, "s": 29263, "text": "scheduleMessage( IMessage message, Instant scheduledEnqueueTimeUtc )" }, { "code": null, "e": 29345, "s": 29332, "text": "Sample Code:" }, { "code": "public static async sendScheduleMessage( content: Message): Promise<string> { const serviceConnection = AzureServiceBus.createConnection(); const client = serviceConnection.createQueueClient( \"\" + process.env.AZURE_SERVICEBUS_QUEUE); const sender = client.createSender(); let response = \"\"; try { const scheduledEnqueueTimeUtc = moment().utc().add(1, \"m\").toDate(); const sequenceId = await sender.scheduleMessage( scheduledEnqueueTimeUtc, {body: JSON.stringify(content), label: \"MyTopic\"}); response = sequenceId.toString(); await client.close(); } catch (error) { } finally { await serviceConnection.close(); } return resp;}", "e": 30161, "s": 29345, "text": null }, { "code": null, "e": 30393, "s": 30161, "text": "This will raise an issue that the sequenceId value will go “undefined”. The Azure portal has provided with a fix that the message needs to be encoded and then placed into the service bus in order to get the correct sequenceId back." }, { "code": null, "e": 30402, "s": 30393, "text": "Bug Fix:" }, { "code": "import { DefaultDataTransformer } from \"@azure/amqp-common\";...... const dt = new DefaultDataTransformer(); const sequenceId = await sender.scheduleMessage( scheduledEnqueueTimeUtc, {body: dt.encode(JSON.stringify(content)), label: \"MyTopic\"}); response = sequenceId.toString();", "e": 30716, "s": 30402, "text": null }, { "code": null, "e": 30858, "s": 30716, "text": "Now you will receive the proper sequenceId, which you can use to cancel the message if required in the future using the following code piece." }, { "code": null, "e": 31196, "s": 30858, "text": "CancelMessage: This method deleted the message placed in the service bus early using the scheduleMessage call. We need to send the sequenceNumber returned during the call as the only parameter for this method invocation. If the message is already delivered then we receive an error MessageNotFound which needs to be handled in the catch." }, { "code": null, "e": 31207, "s": 31196, "text": "Prototype:" }, { "code": null, "e": 31253, "s": 31207, "text": "cancelScheduledMessage( long sequenceNumber )" }, { "code": null, "e": 31417, "s": 31253, "text": "Thus we have covered how we can communicate data by using the above two methods and placing the data requests either via a scheduled basis or non scheduled manner." }, { "code": null, "e": 31433, "s": 31417, "text": "Cloud-Computing" }, { "code": null, "e": 31450, "s": 31433, "text": "Web Technologies" }, { "code": null, "e": 31548, "s": 31450, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31557, "s": 31548, "text": "Comments" }, { "code": null, "e": 31570, "s": 31557, "text": "Old Comments" }, { "code": null, "e": 31626, "s": 31570, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 31669, "s": 31626, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31730, "s": 31669, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31775, "s": 31730, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31847, "s": 31775, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 31905, "s": 31847, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 31938, "s": 31905, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 31983, "s": 31938, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 32033, "s": 31983, "text": "How to Insert Form Data into Database using PHP ?" } ]
Alphanumeric Order by in MySQL for strings mixed with numbers
Let’s say you have a VARCHAR column in a table with values are strings and the numbers are on the right side. For example − John1023 Carol9871 David9098 Now, consider you want to order by on the basis of these right-side numbers in the entire column. For this, use ORDER BY RIGHT. Let us first create a table − mysql> create table DemoTable757 ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, ClientId varchar(100) ); Query OK, 0 rows affected (0.53 sec) Insert some records in the table using insert command − mysql> insert into DemoTable757(ClientId) values('John1023'); Query OK, 1 row affected (0.41 sec) mysql> insert into DemoTable757(ClientId) values('Carol9871'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable757(ClientId) values('David9098'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable757(ClientId) values('Adam9989'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable757(ClientId) values('Bob9789'); Query OK, 1 row affected (0.20 sec) Display all records from the table using select statement − mysql> select *from DemoTable757; This will produce the following output - +----+-----------+ | Id | ClientId | +----+-----------+ | 1 | John1023 | | 2 | Carol9871 | | 3 | David9098 | | 4 | Adam9989 | | 5 | Bob9789 | +----+-----------+ 5 rows in set (0.00 sec) Following is the query for alphanumeric order by in MySQL − mysql> select Id,ClientId from DemoTable757 order by right(ClientId,4); This will produce the following output - +----+-----------+ | Id | ClientId | +----+-----------+ | 1 | John1023 | | 3 | David9098 | | 5 | Bob9789 | | 2 | Carol9871 | | 4 | Adam9989 | +----+-----------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1186, "s": 1062, "text": "Let’s say you have a VARCHAR column in a table with values are strings and the numbers are on the right side. For example −" }, { "code": null, "e": 1215, "s": 1186, "text": "John1023\nCarol9871\nDavid9098" }, { "code": null, "e": 1343, "s": 1215, "text": "Now, consider you want to order by on the basis of these right-side numbers in the entire column. For this, use ORDER BY RIGHT." }, { "code": null, "e": 1373, "s": 1343, "text": "Let us first create a table −" }, { "code": null, "e": 1520, "s": 1373, "text": "mysql> create table DemoTable757 (\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n ClientId varchar(100)\n);\nQuery OK, 0 rows affected (0.53 sec)" }, { "code": null, "e": 1576, "s": 1520, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2067, "s": 1576, "text": "mysql> insert into DemoTable757(ClientId) values('John1023');\nQuery OK, 1 row affected (0.41 sec)\nmysql> insert into DemoTable757(ClientId) values('Carol9871');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable757(ClientId) values('David9098');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable757(ClientId) values('Adam9989');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable757(ClientId) values('Bob9789');\nQuery OK, 1 row affected (0.20 sec)" }, { "code": null, "e": 2127, "s": 2067, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2161, "s": 2127, "text": "mysql> select *from DemoTable757;" }, { "code": null, "e": 2202, "s": 2161, "text": "This will produce the following output -" }, { "code": null, "e": 2398, "s": 2202, "text": "+----+-----------+\n| Id | ClientId |\n+----+-----------+\n| 1 | John1023 |\n| 2 | Carol9871 |\n| 3 | David9098 |\n| 4 | Adam9989 |\n| 5 | Bob9789 |\n+----+-----------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2458, "s": 2398, "text": "Following is the query for alphanumeric order by in MySQL −" }, { "code": null, "e": 2530, "s": 2458, "text": "mysql> select Id,ClientId from DemoTable757 order by right(ClientId,4);" }, { "code": null, "e": 2571, "s": 2530, "text": "This will produce the following output -" }, { "code": null, "e": 2767, "s": 2571, "text": "+----+-----------+\n| Id | ClientId |\n+----+-----------+\n| 1 | John1023 |\n| 3 | David9098 |\n| 5 | Bob9789 |\n| 2 | Carol9871 |\n| 4 | Adam9989 |\n+----+-----------+\n5 rows in set (0.00 sec)" } ]
AngularJS | angular.uppercase() Function - GeeksforGeeks
16 Apr, 2019 The angular.uppercase() Function in AngularJS is used to convert the string into uppercase. It can be used when user wants to show the text in uppercase instead of lowercase.Syntax: angular.uppercase(string) Example: In this example the string is converted into uppercase. <html ng-app="app"><head><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script> <title>angular.uppercase()</title> </head> <body style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>angular.uppercase()</h2> <div ng-controller="geek"> <br> <b>Before: </b>{{ string1 }} <br><br> <button id="myButton" ng-mousedown="upper()">Click it! </button> <br><br> <b>After: </b>{{ string2 }} </div> <script> var app = angular.module('app', []); app.controller('geek', function($scope) { $scope.obj1 = "geeksforgeeks is the computer science portal for geeks." $scope.obj2; $scope.string1 = $scope.obj1; $scope.upper = function() { $scope.string2 = angular.uppercase($scope.obj1); } }); </script> </body></html> Output:Before Click:After Click: AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Angular File Upload Angular | keyup event Auth Guards in Angular 9/10/11 What is AOT and JIT Compiler in Angular ? Angular PrimeNG Dropdown Component Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 27880, "s": 27852, "text": "\n16 Apr, 2019" }, { "code": null, "e": 28062, "s": 27880, "text": "The angular.uppercase() Function in AngularJS is used to convert the string into uppercase. It can be used when user wants to show the text in uppercase instead of lowercase.Syntax:" }, { "code": null, "e": 28088, "s": 28062, "text": "angular.uppercase(string)" }, { "code": null, "e": 28153, "s": 28088, "text": "Example: In this example the string is converted into uppercase." }, { "code": "<html ng-app=\"app\"><head><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js\"></script> <title>angular.uppercase()</title> </head> <body style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>angular.uppercase()</h2> <div ng-controller=\"geek\"> <br> <b>Before: </b>{{ string1 }} <br><br> <button id=\"myButton\" ng-mousedown=\"upper()\">Click it! </button> <br><br> <b>After: </b>{{ string2 }} </div> <script> var app = angular.module('app', []); app.controller('geek', function($scope) { $scope.obj1 = \"geeksforgeeks is the computer science portal for geeks.\" $scope.obj2; $scope.string1 = $scope.obj1; $scope.upper = function() { $scope.string2 = angular.uppercase($scope.obj1); } }); </script> </body></html>", "e": 29034, "s": 28153, "text": null }, { "code": null, "e": 29067, "s": 29034, "text": "Output:Before Click:After Click:" }, { "code": null, "e": 29077, "s": 29067, "text": "AngularJS" }, { "code": null, "e": 29094, "s": 29077, "text": "Web Technologies" }, { "code": null, "e": 29192, "s": 29094, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29201, "s": 29192, "text": "Comments" }, { "code": null, "e": 29214, "s": 29201, "text": "Old Comments" }, { "code": null, "e": 29234, "s": 29214, "text": "Angular File Upload" }, { "code": null, "e": 29256, "s": 29234, "text": "Angular | keyup event" }, { "code": null, "e": 29287, "s": 29256, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 29329, "s": 29287, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 29364, "s": 29329, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 29420, "s": 29364, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 29453, "s": 29420, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29515, "s": 29453, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29558, "s": 29515, "text": "How to fetch data from an API in ReactJS ?" } ]
CSS3 - Web Fonts
Web fonts are used to allows the fonts in CSS, which are not installed on local system. TrueType Fonts (TTF) TrueType is an outline font standard developed by Apple and Microsoft in the late 1980s, It became most common fonts for both windows and MAC operating systems. OpenType Fonts (OTF) OpenType is a format for scalable computer fonts and developed by Microsoft The Web Open Font Format (WOFF) WOFF is used for develop web page and developed in the year of 2009. Now it is using by W3C recommendation. SVG Fonts/Shapes SVG allow SVG fonts within SVG documentation. We can also apply CSS to SVG with font face property. Embedded OpenType Fonts (EOT) EOT is used to develop the web pages and it has embedded in webpages so no need to allow 3rd party fonts Following code shows the sample code of font face − <html> <head> <style> @font-face { font-family: myFirstFont; src: url(/css/font/SansationLight.woff); } div { font-family: myFirstFont; } </Style> </head> <body> <div>This is the example of font face with CSS3.</div> <p><b>Original Text :</b>This is the example of font face with CSS3.</p> </body> </html> It will produce the following result − Original Text :This is the example of font face with CSS3. The following list contained all the fonts description which are placed in the @font-face rule − font-family Used to defines the name of font src Used to defines the URL font-stretch Used to find, how font should be stretched font-style Used to defines the fonts style font-weight Used to defines the font weight(boldness) 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2714, "s": 2626, "text": "Web fonts are used to allows the fonts in CSS, which are not installed on local system." }, { "code": null, "e": 2735, "s": 2714, "text": "TrueType Fonts (TTF)" }, { "code": null, "e": 2896, "s": 2735, "text": "TrueType is an outline font standard developed by Apple and Microsoft in the late 1980s, It became most common fonts for both windows and MAC operating systems." }, { "code": null, "e": 2917, "s": 2896, "text": "OpenType Fonts (OTF)" }, { "code": null, "e": 2993, "s": 2917, "text": "OpenType is a format for scalable computer fonts and developed by Microsoft" }, { "code": null, "e": 3025, "s": 2993, "text": "The Web Open Font Format (WOFF)" }, { "code": null, "e": 3133, "s": 3025, "text": "WOFF is used for develop web page and developed in the year of 2009. Now it is using by W3C recommendation." }, { "code": null, "e": 3150, "s": 3133, "text": "SVG Fonts/Shapes" }, { "code": null, "e": 3250, "s": 3150, "text": "SVG allow SVG fonts within SVG documentation. We can also apply CSS to SVG with font face property." }, { "code": null, "e": 3280, "s": 3250, "text": "Embedded OpenType Fonts (EOT)" }, { "code": null, "e": 3385, "s": 3280, "text": "EOT is used to develop the web pages and it has embedded in webpages so no need to allow 3rd party fonts" }, { "code": null, "e": 3437, "s": 3385, "text": "Following code shows the sample code of font face −" }, { "code": null, "e": 3855, "s": 3437, "text": "<html>\n <head>\n <style>\n @font-face {\n font-family: myFirstFont;\n src: url(/css/font/SansationLight.woff);\n }\n div {\n font-family: myFirstFont;\n }\n </Style>\n </head>\n \n <body>\n <div>This is the example of font face with CSS3.</div>\n <p><b>Original Text :</b>This is the example of font face with CSS3.</p>\n </body>\n</html>" }, { "code": null, "e": 3894, "s": 3855, "text": "It will produce the following result −" }, { "code": null, "e": 3953, "s": 3894, "text": "Original Text :This is the example of font face with CSS3." }, { "code": null, "e": 4050, "s": 3953, "text": "The following list contained all the fonts description which are placed in the @font-face rule −" }, { "code": null, "e": 4062, "s": 4050, "text": "font-family" }, { "code": null, "e": 4095, "s": 4062, "text": "Used to defines the name of font" }, { "code": null, "e": 4099, "s": 4095, "text": "src" }, { "code": null, "e": 4123, "s": 4099, "text": "Used to defines the URL" }, { "code": null, "e": 4136, "s": 4123, "text": "font-stretch" }, { "code": null, "e": 4179, "s": 4136, "text": "Used to find, how font should be stretched" }, { "code": null, "e": 4190, "s": 4179, "text": "font-style" }, { "code": null, "e": 4222, "s": 4190, "text": "Used to defines the fonts style" }, { "code": null, "e": 4234, "s": 4222, "text": "font-weight" }, { "code": null, "e": 4276, "s": 4234, "text": "Used to defines the font weight(boldness)" }, { "code": null, "e": 4311, "s": 4276, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4325, "s": 4311, "text": " Anadi Sharma" }, { "code": null, "e": 4360, "s": 4325, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4377, "s": 4360, "text": " Frahaan Hussain" }, { "code": null, "e": 4412, "s": 4377, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4443, "s": 4412, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4478, "s": 4443, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4509, "s": 4478, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4544, "s": 4509, "text": "\n 51 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4575, "s": 4544, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4608, "s": 4575, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 4639, "s": 4608, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4646, "s": 4639, "text": " Print" }, { "code": null, "e": 4657, "s": 4646, "text": " Add Notes" } ]
Program for array rotation - GeeksforGeeks
09 Nov, 2021 Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements. Rotation of the above array by 2 will make array METHOD 1 (Using temp array) Input arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2, n =7 1) Store the first d elements in a temp array temp[] = [1, 2] 2) Shift rest of the arr[] arr[] = [3, 4, 5, 6, 7, 6, 7] 3) Store back the d elements arr[] = [3, 4, 5, 6, 7, 1, 2] Time complexity : O(n) Auxiliary Space : O(d) METHOD 2 (Rotate one by one) leftRotate(arr[], d, n) start For i = 0 to i < d Left rotate all elements of arr[] by one end To rotate by one, store arr[0] in a temporary variable temp, move arr[1] to arr[0], arr[2] to arr[1] ...and finally temp to arr[n-1]Let us take the same example arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2 Rotate arr[] by one 2 times We get [2, 3, 4, 5, 6, 7, 1] after first rotation and [ 3, 4, 5, 6, 7, 1, 2] after second rotation.Below is the implementation of the above approach : C++ C Java Python3 C# PHP Javascript // C++ program to rotate an array by// d elements#include <bits/stdc++.h>using namespace std; /*Function to left Rotate arr[] of size n by 1*/void leftRotatebyOne(int arr[], int n){ int temp = arr[0], i; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n-1] = temp;} /*Function to left rotate arr[] of size n by d*/void leftRotate(int arr[], int d, int n){ for (int i = 0; i < d; i++) leftRotatebyOne(arr, n);} /* utility function to print an array */void printArray(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} /* Driver program to test above functions */int main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); // Function calling leftRotate(arr, 2, n); printArray(arr, n); return 0;} // C program to rotate an array by// d elements#include <stdio.h> /* Function to left Rotate arr[] of size n by 1*/void leftRotatebyOne(int arr[], int n); /*Function to left rotate arr[] of size n by d*/void leftRotate(int arr[], int d, int n){ int i; for (i = 0; i < d; i++) leftRotatebyOne(arr, n);} void leftRotatebyOne(int arr[], int n){ int temp = arr[0], i; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n-1] = temp;} /* utility function to print an array */void printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) printf("%d ", arr[i]);} /* Driver program to test above functions */int main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; leftRotate(arr, 2, 7); printArray(arr, 7); return 0;} // Java program to rotate an array by// d elements class RotateArray { /*Function to left rotate arr[] of size n by d*/ void leftRotate(int arr[], int d, int n) { for (int i = 0; i < d; i++) leftRotatebyOne(arr, n); } void leftRotatebyOne(int arr[], int n) { int i, temp; temp = arr[0]; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n-1] = temp; } /* utility function to print an array */ void printArray(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); } // Driver program to test above functions public static void main(String[] args) { RotateArray rotate = new RotateArray(); int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; rotate.leftRotate(arr, 2, 7); rotate.printArray(arr, 7); }} // This code has been contributed by Mayank Jaiswal # Python3 program to rotate an array by# d elements# Function to left rotate arr[] of size n by d*/def leftRotate(arr, d, n): for i in range(d): leftRotatebyOne(arr, n) # Function to left Rotate arr[] of size n by 1*/def leftRotatebyOne(arr, n): temp = arr[0] for i in range(n-1): arr[i] = arr[i + 1] arr[n-1] = temp # utility function to print an array */def printArray(arr, size): for i in range(size): print ("% d"% arr[i], end =" ") # Driver program to test above functions */arr = [1, 2, 3, 4, 5, 6, 7]leftRotate(arr, 2, 7)printArray(arr, 7) # This code is contributed by Shreyanshi Arun // C# program for array rotationusing System; class GFG { /* Function to left rotate arr[] of size n by d*/ static void leftRotate(int[] arr, int d, int n) { for (int i = 0; i < d; i++) leftRotatebyOne(arr, n); } static void leftRotatebyOne(int[] arr, int n) { int i, temp = arr[0]; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n-1] = temp; } /* utility function to print an array */ static void printArray(int[] arr, int size) { for (int i = 0; i < size; i++) Console.Write(arr[i] + " "); } // Driver code public static void Main() { int[] arr = { 1, 2, 3, 4, 5, 6, 7 }; leftRotate(arr, 2, 7); printArray(arr, 7); }} // This code is contributed by Sam007 <?php// PHP program to rotate an array// by d elements /*Function to left Rotate arr[] of size n by 1*/function leftRotatebyOne(&$arr, $n){ $temp = $arr[0]; for ($i = 0; $i < $n - 1; $i++) $arr[$i] = $arr[$i + 1]; $arr[$n-1] = $temp;} /*Function to left rotate arr[] of size n by d*/function leftRotate(&$arr, $d, $n){ for ($i = 0; $i < $d; $i++) leftRotatebyOne($arr, $n);} /* utility function to print an array */function printArray(&$arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i] . " ";} // Driver Code$arr = array( 1, 2, 3, 4, 5, 6, 7 );$n = sizeof($arr); // Function callingleftRotate($arr, 2, $n);printArray($arr, $n); // This code is contributed// by ChitraNayal?> <script> // JavaScript program to rotate an array by// d elements /* Function to left rotate arr of size n by d */ function leftRotate(arr , d , n) { for (i = 0; i < d; i++) leftRotatebyOne(arr, n); } function leftRotatebyOne(arr , n) { var i, temp; temp = arr[0]; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n - 1] = temp; } /* utility function to print an array */ function printArray(arr , n) { for (i = 0; i < n; i++) document.write(arr[i] + " "); } // Driver program to test above functions var arr = [ 1, 2, 3, 4, 5, 6, 7 ]; leftRotate(arr, 2, 7); printArray(arr, 7); // This code is contributed by todaysgaurav </script> Output : 3 4 5 6 7 1 2 Time complexity : O(n * d) Auxiliary Space : O(1)METHOD 3 (A Juggling Algorithm) This is an extension of method 2. Instead of moving one by one, divide the array in different sets where number of sets is equal to GCD of n and d and move the elements within sets. If GCD is 1 as is for the above example array (n = 7 and d =2), then elements will be moved within one set only, we just start with temp = arr[0] and keep moving arr[I+d] to arr[I] and finally store temp at the right place.Here is an example for n =12 and d = 3. GCD is 3 and Let arr[] be {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} a) Elements are first moved in first set – (See below diagram for this movement) arr[] after this step --> {4 2 3 7 5 6 10 8 9 1 11 12} b) Then in second set. arr[] after this step --> {4 5 3 7 8 6 10 11 9 1 2 12} c) Finally in third set. arr[] after this step --> {4 5 6 7 8 9 10 11 12 1 2 3} Below is the implementation of the above approach : C++ C Java Python3 C# Javascript // C++ program to rotate an array by// d elements#include <bits/stdc++.h>using namespace std; /*Function to get gcd of a and b*/int gcd(int a, int b){ if (b == 0) return a; else return gcd(b, a % b);} /*Function to left rotate arr[] of siz n by d*/void leftRotate(int arr[], int d, int n){ /* To handle if d >= n */ d = d % n; int g_c_d = gcd(d, n); for (int i = 0; i < g_c_d; i++) { /* move i-th values of blocks */ int temp = arr[i]; int j = i; while (1) { int k = j + d; if (k >= n) k = k - n; if (k == i) break; arr[j] = arr[k]; j = k; } arr[j] = temp; }} // Function to print an arrayvoid printArray(int arr[], int size){ for (int i = 0; i < size; i++) cout << arr[i] << " ";} /* Driver program to test above functions */int main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); // Function calling leftRotate(arr, 2, n); printArray(arr, n); return 0;} // C program to rotate an array by// d elements#include <stdio.h> /* function to print an array */void printArray(int arr[], int size); /*Function to get gcd of a and b*/int gcd(int a, int b); /*Function to left rotate arr[] of siz n by d*/void leftRotate(int arr[], int d, int n){ int i, j, k, temp; /* To handle if d >= n */ d = d % n; int g_c_d = gcd(d, n); for (i = 0; i < g_c_d; i++) { /* move i-th values of blocks */ temp = arr[i]; j = i; while (1) { k = j + d; if (k >= n) k = k - n; if (k == i) break; arr[j] = arr[k]; j = k; } arr[j] = temp; }} /*UTILITY FUNCTIONS*//* function to print an array */void printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) printf("%d ", arr[i]);} /*Function to get gcd of a and b*/int gcd(int a, int b){ if (b == 0) return a; else return gcd(b, a % b);} /* Driver program to test above functions */int main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; leftRotate(arr, 2, 7); printArray(arr, 7); getchar(); return 0;} // Java program to rotate an array by// d elementsclass RotateArray { /*Function to left rotate arr[] of siz n by d*/ void leftRotate(int arr[], int d, int n) { /* To handle if d >= n */ d = d % n; int i, j, k, temp; int g_c_d = gcd(d, n); for (i = 0; i < g_c_d; i++) { /* move i-th values of blocks */ temp = arr[i]; j = i; while (true) { k = j + d; if (k >= n) k = k - n; if (k == i) break; arr[j] = arr[k]; j = k; } arr[j] = temp; } } /*UTILITY FUNCTIONS*/ /* function to print an array */ void printArray(int arr[], int size) { int i; for (i = 0; i < size; i++) System.out.print(arr[i] + " "); } /*Function to get gcd of a and b*/ int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } // Driver program to test above functions public static void main(String[] args) { RotateArray rotate = new RotateArray(); int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; rotate.leftRotate(arr, 2, 7); rotate.printArray(arr, 7); }} // This code has been contributed by Mayank Jaiswal # Python3 program to rotate an array by# d elements# Function to left rotate arr[] of size n by ddef leftRotate(arr, d, n): d = d % n g_c_d = gcd(d, n) for i in range(g_c_d): # move i-th values of blocks temp = arr[i] j = i while 1: k = j + d if k >= n: k = k - n if k == i: break arr[j] = arr[k] j = k arr[j] = temp # UTILITY FUNCTIONS# function to print an arraydef printArray(arr, size): for i in range(size): print ("% d" % arr[i], end =" ") # Function to get gcd of a and bdef gcd(a, b): if b == 0: return a; else: return gcd(b, a % b) # Driver program to test above functionsarr = [1, 2, 3, 4, 5, 6, 7]n = len(arr)d = 2leftRotate(arr, d, n)printArray(arr, n) # This code is contributed by Shreyanshi Arun // C# program for array rotationusing System; class GFG { /* Function to left rotate arr[] of size n by d*/ static void leftRotate(int[] arr, int d, int n) { int i, j, k, temp; /* To handle if d >= n */ d = d % n; int g_c_d = gcd(d, n); for (i = 0; i < g_c_d; i++) { /* move i-th values of blocks */ temp = arr[i]; j = i; while (true) { k = j + d; if (k >= n) k = k - n; if (k == i) break; arr[j] = arr[k]; j = k; } arr[j] = temp; } } /*UTILITY FUNCTIONS*/ /* Function to print an array */ static void printArray(int[] arr, int size) { for (int i = 0; i < size; i++) Console.Write(arr[i] + " "); } /* Function to get gcd of a and b*/ static int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } // Driver code public static void Main() { int[] arr = { 1, 2, 3, 4, 5, 6, 7 }; leftRotate(arr, 2, 7); printArray(arr, 7); }} // This code is contributed by Sam007 <script> // JavaScript program to rotate an array by// d elements /*Function to get gcd of a and b*/function gcd( a, b){ if (b == 0) return a; else return gcd(b, a % b);} /*Function to left rotate arr[] of siz n by d*/function leftRotate(arr, d, n){ /* To handle if d >= n */ d = d % n; let g_c_d = gcd(d, n); for (let i = 0; i < g_c_d; i++) { /* move i-th values of blocks */ let temp = arr[i]; let j = i; while (1) { let k = j + d; if (k >= n) k = k - n; if (k == i) break; arr[j] = arr[k]; j = k; } arr[j] = temp; }} // Function to print an arrayfunction printArray(arr, size){ for (let i = 0; i < size; i++) document.write(arr[i] +" ");} /* Driver program to test above functions */let arr = [ 1, 2, 3, 4, 5, 6, 7 ];let n = arr.length;// Function callingleftRotate(arr, 2, n);printArray(arr, n); </script> Output : 3 4 5 6 7 1 2 Time complexity : O(n) Auxiliary Space : O(1) Please see following posts for other methods of array rotation: Block swap algorithm for array rotation Reversal algorithm for array rotationPlease write comments if you find any bug in above programs/algorithms. shantanoo SukhjashanSingh tufan_gupta2000 ukasp VenkteshJain saryan573 anuragkurle subash m mohammed169 todaysgaurav rohan07 bunnyram19 singghakshay Amazon MakeMyTrip MAQ Software rotation SAP Labs Wipro Arrays Greedy Amazon MakeMyTrip MAQ Software Wipro SAP Labs Arrays Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Multidimensional Arrays in Java Linear Search Python | Using 2D arrays/lists the right way Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3 Write a program to print all permutations of a given string
[ { "code": null, "e": 37367, "s": 37339, "text": "\n09 Nov, 2021" }, { "code": null, "e": 37449, "s": 37367, "text": "Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements. " }, { "code": null, "e": 37499, "s": 37449, "text": "Rotation of the above array by 2 will make array " }, { "code": null, "e": 37530, "s": 37501, "text": "METHOD 1 (Using temp array) " }, { "code": null, "e": 37766, "s": 37530, "text": "Input arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2, n =7\n1) Store the first d elements in a temp array\n temp[] = [1, 2]\n2) Shift rest of the arr[]\n arr[] = [3, 4, 5, 6, 7, 6, 7]\n3) Store back the d elements\n arr[] = [3, 4, 5, 6, 7, 1, 2]" }, { "code": null, "e": 37812, "s": 37766, "text": "Time complexity : O(n) Auxiliary Space : O(d)" }, { "code": null, "e": 37843, "s": 37812, "text": "METHOD 2 (Rotate one by one) " }, { "code": null, "e": 37943, "s": 37843, "text": "leftRotate(arr[], d, n)\nstart\n For i = 0 to i < d\n Left rotate all elements of arr[] by one\nend" }, { "code": null, "e": 38322, "s": 37943, "text": "To rotate by one, store arr[0] in a temporary variable temp, move arr[1] to arr[0], arr[2] to arr[1] ...and finally temp to arr[n-1]Let us take the same example arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2 Rotate arr[] by one 2 times We get [2, 3, 4, 5, 6, 7, 1] after first rotation and [ 3, 4, 5, 6, 7, 1, 2] after second rotation.Below is the implementation of the above approach : " }, { "code": null, "e": 38326, "s": 38322, "text": "C++" }, { "code": null, "e": 38328, "s": 38326, "text": "C" }, { "code": null, "e": 38333, "s": 38328, "text": "Java" }, { "code": null, "e": 38341, "s": 38333, "text": "Python3" }, { "code": null, "e": 38344, "s": 38341, "text": "C#" }, { "code": null, "e": 38348, "s": 38344, "text": "PHP" }, { "code": null, "e": 38359, "s": 38348, "text": "Javascript" }, { "code": "// C++ program to rotate an array by// d elements#include <bits/stdc++.h>using namespace std; /*Function to left Rotate arr[] of size n by 1*/void leftRotatebyOne(int arr[], int n){ int temp = arr[0], i; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n-1] = temp;} /*Function to left rotate arr[] of size n by d*/void leftRotate(int arr[], int d, int n){ for (int i = 0; i < d; i++) leftRotatebyOne(arr, n);} /* utility function to print an array */void printArray(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \";} /* Driver program to test above functions */int main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); // Function calling leftRotate(arr, 2, n); printArray(arr, n); return 0;}", "e": 39164, "s": 38359, "text": null }, { "code": "// C program to rotate an array by// d elements#include <stdio.h> /* Function to left Rotate arr[] of size n by 1*/void leftRotatebyOne(int arr[], int n); /*Function to left rotate arr[] of size n by d*/void leftRotate(int arr[], int d, int n){ int i; for (i = 0; i < d; i++) leftRotatebyOne(arr, n);} void leftRotatebyOne(int arr[], int n){ int temp = arr[0], i; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n-1] = temp;} /* utility function to print an array */void printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) printf(\"%d \", arr[i]);} /* Driver program to test above functions */int main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; leftRotate(arr, 2, 7); printArray(arr, 7); return 0;}", "e": 39926, "s": 39164, "text": null }, { "code": "// Java program to rotate an array by// d elements class RotateArray { /*Function to left rotate arr[] of size n by d*/ void leftRotate(int arr[], int d, int n) { for (int i = 0; i < d; i++) leftRotatebyOne(arr, n); } void leftRotatebyOne(int arr[], int n) { int i, temp; temp = arr[0]; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n-1] = temp; } /* utility function to print an array */ void printArray(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); } // Driver program to test above functions public static void main(String[] args) { RotateArray rotate = new RotateArray(); int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; rotate.leftRotate(arr, 2, 7); rotate.printArray(arr, 7); }} // This code has been contributed by Mayank Jaiswal", "e": 40843, "s": 39926, "text": null }, { "code": "# Python3 program to rotate an array by# d elements# Function to left rotate arr[] of size n by d*/def leftRotate(arr, d, n): for i in range(d): leftRotatebyOne(arr, n) # Function to left Rotate arr[] of size n by 1*/def leftRotatebyOne(arr, n): temp = arr[0] for i in range(n-1): arr[i] = arr[i + 1] arr[n-1] = temp # utility function to print an array */def printArray(arr, size): for i in range(size): print (\"% d\"% arr[i], end =\" \") # Driver program to test above functions */arr = [1, 2, 3, 4, 5, 6, 7]leftRotate(arr, 2, 7)printArray(arr, 7) # This code is contributed by Shreyanshi Arun", "e": 41483, "s": 40843, "text": null }, { "code": "// C# program for array rotationusing System; class GFG { /* Function to left rotate arr[] of size n by d*/ static void leftRotate(int[] arr, int d, int n) { for (int i = 0; i < d; i++) leftRotatebyOne(arr, n); } static void leftRotatebyOne(int[] arr, int n) { int i, temp = arr[0]; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n-1] = temp; } /* utility function to print an array */ static void printArray(int[] arr, int size) { for (int i = 0; i < size; i++) Console.Write(arr[i] + \" \"); } // Driver code public static void Main() { int[] arr = { 1, 2, 3, 4, 5, 6, 7 }; leftRotate(arr, 2, 7); printArray(arr, 7); }} // This code is contributed by Sam007", "e": 42314, "s": 41483, "text": null }, { "code": "<?php// PHP program to rotate an array// by d elements /*Function to left Rotate arr[] of size n by 1*/function leftRotatebyOne(&$arr, $n){ $temp = $arr[0]; for ($i = 0; $i < $n - 1; $i++) $arr[$i] = $arr[$i + 1]; $arr[$n-1] = $temp;} /*Function to left rotate arr[] of size n by d*/function leftRotate(&$arr, $d, $n){ for ($i = 0; $i < $d; $i++) leftRotatebyOne($arr, $n);} /* utility function to print an array */function printArray(&$arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i] . \" \";} // Driver Code$arr = array( 1, 2, 3, 4, 5, 6, 7 );$n = sizeof($arr); // Function callingleftRotate($arr, 2, $n);printArray($arr, $n); // This code is contributed// by ChitraNayal?>", "e": 43032, "s": 42314, "text": null }, { "code": "<script> // JavaScript program to rotate an array by// d elements /* Function to left rotate arr of size n by d */ function leftRotate(arr , d , n) { for (i = 0; i < d; i++) leftRotatebyOne(arr, n); } function leftRotatebyOne(arr , n) { var i, temp; temp = arr[0]; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n - 1] = temp; } /* utility function to print an array */ function printArray(arr , n) { for (i = 0; i < n; i++) document.write(arr[i] + \" \"); } // Driver program to test above functions var arr = [ 1, 2, 3, 4, 5, 6, 7 ]; leftRotate(arr, 2, 7); printArray(arr, 7); // This code is contributed by todaysgaurav </script>", "e": 43802, "s": 43032, "text": null }, { "code": null, "e": 43813, "s": 43802, "text": "Output : " }, { "code": null, "e": 43828, "s": 43813, "text": "3 4 5 6 7 1 2 " }, { "code": null, "e": 44369, "s": 43828, "text": "Time complexity : O(n * d) Auxiliary Space : O(1)METHOD 3 (A Juggling Algorithm) This is an extension of method 2. Instead of moving one by one, divide the array in different sets where number of sets is equal to GCD of n and d and move the elements within sets. If GCD is 1 as is for the above example array (n = 7 and d =2), then elements will be moved within one set only, we just start with temp = arr[0] and keep moving arr[I+d] to arr[I] and finally store temp at the right place.Here is an example for n =12 and d = 3. GCD is 3 and " }, { "code": null, "e": 44508, "s": 44369, "text": "Let arr[] be {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}\n\na) Elements are first moved in first set – (See below \n diagram for this movement)" }, { "code": null, "e": 44759, "s": 44508, "text": " arr[] after this step --> {4 2 3 7 5 6 10 8 9 1 11 12}\n\nb) Then in second set.\n arr[] after this step --> {4 5 3 7 8 6 10 11 9 1 2 12}\n\nc) Finally in third set.\n arr[] after this step --> {4 5 6 7 8 9 10 11 12 1 2 3}" }, { "code": null, "e": 44812, "s": 44759, "text": "Below is the implementation of the above approach : " }, { "code": null, "e": 44816, "s": 44812, "text": "C++" }, { "code": null, "e": 44818, "s": 44816, "text": "C" }, { "code": null, "e": 44823, "s": 44818, "text": "Java" }, { "code": null, "e": 44831, "s": 44823, "text": "Python3" }, { "code": null, "e": 44834, "s": 44831, "text": "C#" }, { "code": null, "e": 44845, "s": 44834, "text": "Javascript" }, { "code": "// C++ program to rotate an array by// d elements#include <bits/stdc++.h>using namespace std; /*Function to get gcd of a and b*/int gcd(int a, int b){ if (b == 0) return a; else return gcd(b, a % b);} /*Function to left rotate arr[] of siz n by d*/void leftRotate(int arr[], int d, int n){ /* To handle if d >= n */ d = d % n; int g_c_d = gcd(d, n); for (int i = 0; i < g_c_d; i++) { /* move i-th values of blocks */ int temp = arr[i]; int j = i; while (1) { int k = j + d; if (k >= n) k = k - n; if (k == i) break; arr[j] = arr[k]; j = k; } arr[j] = temp; }} // Function to print an arrayvoid printArray(int arr[], int size){ for (int i = 0; i < size; i++) cout << arr[i] << \" \";} /* Driver program to test above functions */int main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); // Function calling leftRotate(arr, 2, n); printArray(arr, n); return 0;}", "e": 45928, "s": 44845, "text": null }, { "code": "// C program to rotate an array by// d elements#include <stdio.h> /* function to print an array */void printArray(int arr[], int size); /*Function to get gcd of a and b*/int gcd(int a, int b); /*Function to left rotate arr[] of siz n by d*/void leftRotate(int arr[], int d, int n){ int i, j, k, temp; /* To handle if d >= n */ d = d % n; int g_c_d = gcd(d, n); for (i = 0; i < g_c_d; i++) { /* move i-th values of blocks */ temp = arr[i]; j = i; while (1) { k = j + d; if (k >= n) k = k - n; if (k == i) break; arr[j] = arr[k]; j = k; } arr[j] = temp; }} /*UTILITY FUNCTIONS*//* function to print an array */void printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) printf(\"%d \", arr[i]);} /*Function to get gcd of a and b*/int gcd(int a, int b){ if (b == 0) return a; else return gcd(b, a % b);} /* Driver program to test above functions */int main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; leftRotate(arr, 2, 7); printArray(arr, 7); getchar(); return 0;}", "e": 47084, "s": 45928, "text": null }, { "code": "// Java program to rotate an array by// d elementsclass RotateArray { /*Function to left rotate arr[] of siz n by d*/ void leftRotate(int arr[], int d, int n) { /* To handle if d >= n */ d = d % n; int i, j, k, temp; int g_c_d = gcd(d, n); for (i = 0; i < g_c_d; i++) { /* move i-th values of blocks */ temp = arr[i]; j = i; while (true) { k = j + d; if (k >= n) k = k - n; if (k == i) break; arr[j] = arr[k]; j = k; } arr[j] = temp; } } /*UTILITY FUNCTIONS*/ /* function to print an array */ void printArray(int arr[], int size) { int i; for (i = 0; i < size; i++) System.out.print(arr[i] + \" \"); } /*Function to get gcd of a and b*/ int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } // Driver program to test above functions public static void main(String[] args) { RotateArray rotate = new RotateArray(); int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; rotate.leftRotate(arr, 2, 7); rotate.printArray(arr, 7); }} // This code has been contributed by Mayank Jaiswal", "e": 48431, "s": 47084, "text": null }, { "code": "# Python3 program to rotate an array by# d elements# Function to left rotate arr[] of size n by ddef leftRotate(arr, d, n): d = d % n g_c_d = gcd(d, n) for i in range(g_c_d): # move i-th values of blocks temp = arr[i] j = i while 1: k = j + d if k >= n: k = k - n if k == i: break arr[j] = arr[k] j = k arr[j] = temp # UTILITY FUNCTIONS# function to print an arraydef printArray(arr, size): for i in range(size): print (\"% d\" % arr[i], end =\" \") # Function to get gcd of a and bdef gcd(a, b): if b == 0: return a; else: return gcd(b, a % b) # Driver program to test above functionsarr = [1, 2, 3, 4, 5, 6, 7]n = len(arr)d = 2leftRotate(arr, d, n)printArray(arr, n) # This code is contributed by Shreyanshi Arun", "e": 49310, "s": 48431, "text": null }, { "code": "// C# program for array rotationusing System; class GFG { /* Function to left rotate arr[] of size n by d*/ static void leftRotate(int[] arr, int d, int n) { int i, j, k, temp; /* To handle if d >= n */ d = d % n; int g_c_d = gcd(d, n); for (i = 0; i < g_c_d; i++) { /* move i-th values of blocks */ temp = arr[i]; j = i; while (true) { k = j + d; if (k >= n) k = k - n; if (k == i) break; arr[j] = arr[k]; j = k; } arr[j] = temp; } } /*UTILITY FUNCTIONS*/ /* Function to print an array */ static void printArray(int[] arr, int size) { for (int i = 0; i < size; i++) Console.Write(arr[i] + \" \"); } /* Function to get gcd of a and b*/ static int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } // Driver code public static void Main() { int[] arr = { 1, 2, 3, 4, 5, 6, 7 }; leftRotate(arr, 2, 7); printArray(arr, 7); }} // This code is contributed by Sam007", "e": 50569, "s": 49310, "text": null }, { "code": "<script> // JavaScript program to rotate an array by// d elements /*Function to get gcd of a and b*/function gcd( a, b){ if (b == 0) return a; else return gcd(b, a % b);} /*Function to left rotate arr[] of siz n by d*/function leftRotate(arr, d, n){ /* To handle if d >= n */ d = d % n; let g_c_d = gcd(d, n); for (let i = 0; i < g_c_d; i++) { /* move i-th values of blocks */ let temp = arr[i]; let j = i; while (1) { let k = j + d; if (k >= n) k = k - n; if (k == i) break; arr[j] = arr[k]; j = k; } arr[j] = temp; }} // Function to print an arrayfunction printArray(arr, size){ for (let i = 0; i < size; i++) document.write(arr[i] +\" \");} /* Driver program to test above functions */let arr = [ 1, 2, 3, 4, 5, 6, 7 ];let n = arr.length;// Function callingleftRotate(arr, 2, n);printArray(arr, n); </script>", "e": 51554, "s": 50569, "text": null }, { "code": null, "e": 51564, "s": 51554, "text": "Output : " }, { "code": null, "e": 51579, "s": 51564, "text": "3 4 5 6 7 1 2 " }, { "code": null, "e": 51626, "s": 51579, "text": "Time complexity : O(n) Auxiliary Space : O(1) " }, { "code": null, "e": 51840, "s": 51626, "text": "Please see following posts for other methods of array rotation: Block swap algorithm for array rotation Reversal algorithm for array rotationPlease write comments if you find any bug in above programs/algorithms. " }, { "code": null, "e": 51850, "s": 51840, "text": "shantanoo" }, { "code": null, "e": 51866, "s": 51850, "text": "SukhjashanSingh" }, { "code": null, "e": 51882, "s": 51866, "text": "tufan_gupta2000" }, { "code": null, "e": 51888, "s": 51882, "text": "ukasp" }, { "code": null, "e": 51901, "s": 51888, "text": "VenkteshJain" }, { "code": null, "e": 51911, "s": 51901, "text": "saryan573" }, { "code": null, "e": 51923, "s": 51911, "text": "anuragkurle" }, { "code": null, "e": 51932, "s": 51923, "text": "subash m" }, { "code": null, "e": 51944, "s": 51932, "text": "mohammed169" }, { "code": null, "e": 51957, "s": 51944, "text": "todaysgaurav" }, { "code": null, "e": 51965, "s": 51957, "text": "rohan07" }, { "code": null, "e": 51976, "s": 51965, "text": "bunnyram19" }, { "code": null, "e": 51989, "s": 51976, "text": "singghakshay" }, { "code": null, "e": 51996, "s": 51989, "text": "Amazon" }, { "code": null, "e": 52007, "s": 51996, "text": "MakeMyTrip" }, { "code": null, "e": 52020, "s": 52007, "text": "MAQ Software" }, { "code": null, "e": 52029, "s": 52020, "text": "rotation" }, { "code": null, "e": 52038, "s": 52029, "text": "SAP Labs" }, { "code": null, "e": 52044, "s": 52038, "text": "Wipro" }, { "code": null, "e": 52051, "s": 52044, "text": "Arrays" }, { "code": null, "e": 52058, "s": 52051, "text": "Greedy" }, { "code": null, "e": 52065, "s": 52058, "text": "Amazon" }, { "code": null, "e": 52076, "s": 52065, "text": "MakeMyTrip" }, { "code": null, "e": 52089, "s": 52076, "text": "MAQ Software" }, { "code": null, "e": 52095, "s": 52089, "text": "Wipro" }, { "code": null, "e": 52104, "s": 52095, "text": "SAP Labs" }, { "code": null, "e": 52111, "s": 52104, "text": "Arrays" }, { "code": null, "e": 52118, "s": 52111, "text": "Greedy" }, { "code": null, "e": 52216, "s": 52118, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 52225, "s": 52216, "text": "Comments" }, { "code": null, "e": 52238, "s": 52225, "text": "Old Comments" }, { "code": null, "e": 52282, "s": 52238, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 52314, "s": 52282, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 52346, "s": 52314, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 52360, "s": 52346, "text": "Linear Search" }, { "code": null, "e": 52405, "s": 52360, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 52456, "s": 52405, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 52507, "s": 52456, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 52565, "s": 52507, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 52596, "s": 52565, "text": "Huffman Coding | Greedy Algo-3" } ]
Dress Segmentation with Autoencoder in Keras | by Marco Cerliani | Towards Data Science
The fashion industry is a very profitable field for Artificial Intelligence. There are a lot of areas where Data Scientists can develop interesting use cases and provide benefits. I have already demonstrated my interest in this sector here, where I developed a solution for recommendation and tagging dresses from Zalando online store. In this post, I try to go further developing a system that receives as input raw images (taken from the web or made with a smartphone) and try to extract dresses shown in it. Keeping in mind that challenges of Segmentation are infamous for the extreme noise present in the original images; we try to develop a strong solution with clever tricks (during preprocessing) that deal with this aspect. In the end, you can also try to merge this solution with the previous one cited. This permits you to develop a system for real-time recommendation and tagging for dresses, through photographs you take while out and about. Recently also a Kaggle competition was launched on Visual analysis and Segmentation of clothing. It is a very interesting challenge but this is not for us... My object is to extract dresses from photographs so this dataset is not adequate due to its redundancy and fine-grained attributes. We need images that contain mostly dresses, so the best choice was to build the data ourselves. I collected from the web images containing people wearing woman dresses of various types and in different scenarios. The next step required to create masks: this is necessary for every task of object segmentation if we want to train a model that will be able to focus only on the points of real interest. Below I report a sample of data at our disposal. I collected the original images from the internet and then I enjoy myself to cut them further, separating people from dresses. We operate this discrimination because we want to mark separation among background, skin, and dress. Backgrounds and skins are the most relevant sources of noise in this kind of problem, so we try to suppress them. With these cuttings we are able to recreate our masks as shown below, this is made simple binarizing the image. The skin is obtained as the difference among persons and dress. As the final step, we merge all in a single image of three dimensions. This picture decodes the relevant features of our original image which we are interested in. Our purpose is to maintain separation among background, skin end dress: this result is perfect for our scope! We iterated this process for every image in our dataset in order to have for every original image an associated mask of three dimensions. We have all at our disposal to create our model. The workflow we have in mind is very simple: We fit a model which receives as input a raw image and outputs a three-dimensional mask, i.e. it is able to recreate from the original images the desired separation among skin/background and dress. In this way, when a new raw image comes in, we can separate it in three different parts: background, skin and dress. We take into consideration only the channel of our interest (dress), use it to create a mask from the input image and cut it to recreate the original dress. All this magic is possible due to the power of UNet. This deep convolutional Autoencoder is often used in the task of segmentation like this. It is easy to replicate in Keras and we train it to recreate pixel for pixel each channel of our desired mask. Before starting training we decided to standardize all our original images with their RGB mean. We notice that during prediction when we encounter an image with high noise (in term of ambiguous background or skin) our model start to struggle. This inconvenience can be exceeded by simply increasing the number of training images. But we also develop a clever shortcut to avoid these mistakes. We make use of the GrubCut Algorithm provided by OpenCV. This algorithm was implemented to separate the foreground from the background making use of the Gaussian Mixture Model. This makes for us because it helps to point the person in the foreground denoising all around. Here the simple function we implement to make it possible. We assume that the person of our interest stands in the middle of the image. def cut(img): img = cv.resize(img,(224,224)) mask = np.zeros(img.shape[:2],np.uint8) bgdModel = np.zeros((1,65),np.float64) fgdModel = np.zeros((1,65),np.float64) height, width = img.shape[:2] rect = (50,10,width-100,height-20) cv.grabCut(img,mask,rect,bgdModel,fgdModel,5, cv.GC_INIT_WITH_RECT) mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8') img2 = img*mask2[:,:,np.newaxis] img2[mask2 == 0] = (255, 255, 255) final = np.ones(img.shape,np.uint8)*0 + img2 return mask, final Now we apply UNet and are ready to see some results on new images! Our preprocess step, combined with UNet powers, are able to achieve great performance. In this post, we develop an end-to-end solution for Dress Segmentation. To achieve this purpose we make use of a powerful Autoencoder combined with clever preprocess techniques. We plan this solution in order to use it in a realistic scenario with real photographs, with the possibility to build on it a visual recommendation system. CHECK MY GITHUB REPO Keep in touch: Linkedin
[ { "code": null, "e": 507, "s": 171, "text": "The fashion industry is a very profitable field for Artificial Intelligence. There are a lot of areas where Data Scientists can develop interesting use cases and provide benefits. I have already demonstrated my interest in this sector here, where I developed a solution for recommendation and tagging dresses from Zalando online store." }, { "code": null, "e": 903, "s": 507, "text": "In this post, I try to go further developing a system that receives as input raw images (taken from the web or made with a smartphone) and try to extract dresses shown in it. Keeping in mind that challenges of Segmentation are infamous for the extreme noise present in the original images; we try to develop a strong solution with clever tricks (during preprocessing) that deal with this aspect." }, { "code": null, "e": 1125, "s": 903, "text": "In the end, you can also try to merge this solution with the previous one cited. This permits you to develop a system for real-time recommendation and tagging for dresses, through photographs you take while out and about." }, { "code": null, "e": 1511, "s": 1125, "text": "Recently also a Kaggle competition was launched on Visual analysis and Segmentation of clothing. It is a very interesting challenge but this is not for us... My object is to extract dresses from photographs so this dataset is not adequate due to its redundancy and fine-grained attributes. We need images that contain mostly dresses, so the best choice was to build the data ourselves." }, { "code": null, "e": 1816, "s": 1511, "text": "I collected from the web images containing people wearing woman dresses of various types and in different scenarios. The next step required to create masks: this is necessary for every task of object segmentation if we want to train a model that will be able to focus only on the points of real interest." }, { "code": null, "e": 1992, "s": 1816, "text": "Below I report a sample of data at our disposal. I collected the original images from the internet and then I enjoy myself to cut them further, separating people from dresses." }, { "code": null, "e": 2207, "s": 1992, "text": "We operate this discrimination because we want to mark separation among background, skin, and dress. Backgrounds and skins are the most relevant sources of noise in this kind of problem, so we try to suppress them." }, { "code": null, "e": 2383, "s": 2207, "text": "With these cuttings we are able to recreate our masks as shown below, this is made simple binarizing the image. The skin is obtained as the difference among persons and dress." }, { "code": null, "e": 2657, "s": 2383, "text": "As the final step, we merge all in a single image of three dimensions. This picture decodes the relevant features of our original image which we are interested in. Our purpose is to maintain separation among background, skin end dress: this result is perfect for our scope!" }, { "code": null, "e": 2795, "s": 2657, "text": "We iterated this process for every image in our dataset in order to have for every original image an associated mask of three dimensions." }, { "code": null, "e": 2889, "s": 2795, "text": "We have all at our disposal to create our model. The workflow we have in mind is very simple:" }, { "code": null, "e": 3361, "s": 2889, "text": "We fit a model which receives as input a raw image and outputs a three-dimensional mask, i.e. it is able to recreate from the original images the desired separation among skin/background and dress. In this way, when a new raw image comes in, we can separate it in three different parts: background, skin and dress. We take into consideration only the channel of our interest (dress), use it to create a mask from the input image and cut it to recreate the original dress." }, { "code": null, "e": 3614, "s": 3361, "text": "All this magic is possible due to the power of UNet. This deep convolutional Autoencoder is often used in the task of segmentation like this. It is easy to replicate in Keras and we train it to recreate pixel for pixel each channel of our desired mask." }, { "code": null, "e": 3710, "s": 3614, "text": "Before starting training we decided to standardize all our original images with their RGB mean." }, { "code": null, "e": 4007, "s": 3710, "text": "We notice that during prediction when we encounter an image with high noise (in term of ambiguous background or skin) our model start to struggle. This inconvenience can be exceeded by simply increasing the number of training images. But we also develop a clever shortcut to avoid these mistakes." }, { "code": null, "e": 4279, "s": 4007, "text": "We make use of the GrubCut Algorithm provided by OpenCV. This algorithm was implemented to separate the foreground from the background making use of the Gaussian Mixture Model. This makes for us because it helps to point the person in the foreground denoising all around." }, { "code": null, "e": 4415, "s": 4279, "text": "Here the simple function we implement to make it possible. We assume that the person of our interest stands in the middle of the image." }, { "code": null, "e": 4962, "s": 4415, "text": "def cut(img): img = cv.resize(img,(224,224)) mask = np.zeros(img.shape[:2],np.uint8) bgdModel = np.zeros((1,65),np.float64) fgdModel = np.zeros((1,65),np.float64) height, width = img.shape[:2] rect = (50,10,width-100,height-20) cv.grabCut(img,mask,rect,bgdModel,fgdModel,5, cv.GC_INIT_WITH_RECT) mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8') img2 = img*mask2[:,:,np.newaxis] img2[mask2 == 0] = (255, 255, 255) final = np.ones(img.shape,np.uint8)*0 + img2 return mask, final" }, { "code": null, "e": 5029, "s": 4962, "text": "Now we apply UNet and are ready to see some results on new images!" }, { "code": null, "e": 5116, "s": 5029, "text": "Our preprocess step, combined with UNet powers, are able to achieve great performance." }, { "code": null, "e": 5450, "s": 5116, "text": "In this post, we develop an end-to-end solution for Dress Segmentation. To achieve this purpose we make use of a powerful Autoencoder combined with clever preprocess techniques. We plan this solution in order to use it in a realistic scenario with real photographs, with the possibility to build on it a visual recommendation system." }, { "code": null, "e": 5471, "s": 5450, "text": "CHECK MY GITHUB REPO" } ]
Cumulative percentage of a column in Pandas - Python - GeeksforGeeks
15 Mar, 2021 Cumulative Percentage is calculated by the mathematical formula of dividing the cumulative sum of the column by the mathematical sum of all the values and then multiplying the result by 100. This is also applicable in Pandas Data frames.Here, the pre-defined cumsum() and sum() functions are used to compute the cumulative sum and sum of all the values of a column.Syntax: df[cum_percent] = 100 * (df[‘column_name’].cumsum()/df[‘column_name’].sum()) Example 1: Python3 import pandas as pdimport numpy as np # Create a DataFramedf1 = { 'Name':['abc','bcd','cde','def','efg','fgh','ghi'], 'Math_score':[52,87,49,74,28,59,48]} df1 = pd.DataFrame(df1, columns=['Name','Math_score']) # Computing Cumulative Percentagedf1['cum_percent'] = 100*(df1.Math_score.cumsum() / df1.Math_score.sum()) df1 Output: Example 2: Python3 import pandas as pdimport numpy as np # Create a DataFramedf1 = { 'Name':['abc','bcd','cde','def','efg','fgh','ghi'], 'Math_score':[52,87,49,74,28,59,48], 'Eng_score':[34,67,25,89,92,45,86]} df1 = pd.DataFrame(df1,columns=['Name','Math_score','Eng_score']) # Computing cumulative Percentagedf1['Eng_cum_percent'] = (df1.Eng_score.cumsum() / df1.Eng_score.sum()) * 100 df1 Output: arorakashish0911 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 ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Python | os.path.join() method Defaultdict in Python Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n15 Mar, 2021" }, { "code": null, "e": 24666, "s": 24292, "text": "Cumulative Percentage is calculated by the mathematical formula of dividing the cumulative sum of the column by the mathematical sum of all the values and then multiplying the result by 100. This is also applicable in Pandas Data frames.Here, the pre-defined cumsum() and sum() functions are used to compute the cumulative sum and sum of all the values of a column.Syntax: " }, { "code": null, "e": 24745, "s": 24666, "text": "df[cum_percent] = 100 * (df[‘column_name’].cumsum()/df[‘column_name’].sum()) " }, { "code": null, "e": 24756, "s": 24745, "text": "Example 1:" }, { "code": null, "e": 24764, "s": 24756, "text": "Python3" }, { "code": "import pandas as pdimport numpy as np # Create a DataFramedf1 = { 'Name':['abc','bcd','cde','def','efg','fgh','ghi'], 'Math_score':[52,87,49,74,28,59,48]} df1 = pd.DataFrame(df1, columns=['Name','Math_score']) # Computing Cumulative Percentagedf1['cum_percent'] = 100*(df1.Math_score.cumsum() / df1.Math_score.sum()) df1", "e": 25093, "s": 24764, "text": null }, { "code": null, "e": 25107, "s": 25097, "text": "Output: " }, { "code": null, "e": 25127, "s": 25115, "text": "Example 2: " }, { "code": null, "e": 25137, "s": 25129, "text": "Python3" }, { "code": "import pandas as pdimport numpy as np # Create a DataFramedf1 = { 'Name':['abc','bcd','cde','def','efg','fgh','ghi'], 'Math_score':[52,87,49,74,28,59,48], 'Eng_score':[34,67,25,89,92,45,86]} df1 = pd.DataFrame(df1,columns=['Name','Math_score','Eng_score']) # Computing cumulative Percentagedf1['Eng_cum_percent'] = (df1.Eng_score.cumsum() / df1.Eng_score.sum()) * 100 df1", "e": 25518, "s": 25137, "text": null }, { "code": null, "e": 25532, "s": 25522, "text": "Output: " }, { "code": null, "e": 25553, "s": 25536, "text": "arorakashish0911" }, { "code": null, "e": 25577, "s": 25553, "text": "Python pandas-dataFrame" }, { "code": null, "e": 25591, "s": 25577, "text": "Python-pandas" }, { "code": null, "e": 25598, "s": 25591, "text": "Python" }, { "code": null, "e": 25696, "s": 25598, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25728, "s": 25696, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25770, "s": 25728, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25826, "s": 25770, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25868, "s": 25826, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25923, "s": 25868, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 25954, "s": 25923, "text": "Python | os.path.join() method" }, { "code": null, "e": 25976, "s": 25954, "text": "Defaultdict in Python" }, { "code": null, "e": 26015, "s": 25976, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26044, "s": 26015, "text": "Create a directory in Python" } ]
Principal Component Analysis with NumPy | by Wendy Navarrete | Towards Data Science
It is a technique commonly used for linear dimensionality reduction. The idea behind PCA is to find lower dimensional representations of data that retain as much information as possible. Let’s start following next steps. %matplotlib inlineimport pandas as pdimport matplotlib.pyplot as pltimport numpy as npimport seaborn as sns This is the classic database to be found in the pattern recognition literature. The data set contains 3 classes of 50 instances each, where each class refers to a type of iris plant. Retrieved from UCI Machine Learning Repository. iris = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data", header=None)iris.columns = ["sepal_length","sepal_width", 'petal_length','petal_width','species']iris.dropna(how='all', inplace=True)iris.head() # Plotting data using seabornplt.style.use("ggplot")plt.rcParams["figure.figsize"] = (12,8)sns.scatterplot(x = iris.sepal_length, y=iris.sepal_width, hue = iris.species, style=iris.species) Before applying PCA, the variables will be standardized to have a mean of 0 and a standard deviation of 1. This is important because all variables go through the origin point (where the value of all axes is 0) and share the same variance. def standardize_data(arr): ''' This function standardize an array, its substracts mean value, and then divide the standard deviation. param 1: array return: standardized array ''' rows, columns = arr.shape standardizedArray = np.zeros(shape=(rows, columns)) tempArray = np.zeros(rows) for column in range(columns): mean = np.mean(X[:,column]) std = np.std(X[:,column]) tempArray = np.empty(0) for element in X[:,column]: tempArray = np.append(tempArray, ((element - mean) / std)) standardizedArray[:,column] = tempArray return standardizedArray # Standardizing dataX = iris.iloc[:, 0:4].valuesy = iris.species.valuesX = standardize_data(X) Calculating the covariance matrix Calculating the covariance matrix Now I will find the covariance matrix of the dataset by multiplying the matrix of features by its transpose. It is a measure of how much each of the dimensions varies from the mean with respect to each other. Covariance matrices, like correlation matrices, contain information about the amount of variance shared between pairs of variables. # Calculating the covariance matrixcovariance_matrix = np.cov(X.T) 2. Eigendecomposition of the Covariance Matrix # Using np.linalg.eig functioneigen_values, eigen_vectors = np.linalg.eig(covariance_matrix)print("Eigenvector: \n",eigen_vectors,"\n")print("Eigenvalues: \n", eigen_values, "\n") Eigenvectors are the principal components. The first principal component is the first column with values of 0.52, -0.26, 0.58, and 0.56. The second principal component is the second column and so on. Each Eigenvector will correspond to an Eigenvalue, each eigenvector can be scaled of its eigenvalue, whose magnitude indicates how much of the data’s variability is explained by its eigenvector. I want to see how much of the variance in data is explained by each one of these components. It is a convention to use 95% explained variance # Calculating the explained variance on each of componentsvariance_explained = []for i in eigen_values: variance_explained.append((i/sum(eigen_values))*100) print(variance_explained) 72.77% of the variance on our data is explained by the first principal component, the second principal component explains 23.03% of data. Some rules to guide in choosing the number of components to keep: Keep components with eigenvalues greater than 1, as they add value (because they contain more information than a single variable). This rule tends to keep more components than is ideal Visualize the eigenvalues in order from highest to lowest, connecting them with a line. Upon visual inspection, keep all the components whose eigenvalue falls above the point where the slope of the line changes the most drastically, also called the “elbow” Including variance cutoffs where we only keep components that explain at least 95% of the variance in the data Keep comes down the reasons for doing PCA. # Identifying components that explain at least 95%cumulative_variance_explained = np.cumsum(variance_explained)print(cumulative_variance_explained) If I use the first feature, it will explain 72.77% of the data; if I use two features I am able to capture 95.8 of the data. If I use all features I am going to describe the entire dataset. # Visualizing the eigenvalues and finding the "elbow" in the graphicsns.lineplot(x = [1,2,3,4], y=cumulative_variance_explained)plt.xlabel("Number of components")plt.ylabel("Cumulative explained variance")plt.title("Explained variance vs Number of components") In this last step, I will compute the PCA transformation on the original dataset, getting the dot product of the original standardized X and the eigenvectors that I got from the eigendecomposition. # Using two first components (because those explain more than 95%)projection_matrix = (eigen_vectors.T[:][:2]).Tprint(projection_matrix) # Getting the product of original standardized X and the eigenvectors X_pca = X.dot(projection_matrix)print(X_pca) Now I can use the components in any analysis exactly as I would use variables. PCA transformation was implemented using these NumPy functions: np.cov, np.linalg.eig, np.linalg.svd (it is an alternative to get eigenvalues and eigenvectors), np.cumsum, np.mean, np.std, np.zeros, np.empty and np.dot The benefit of PCA is that there will be fewer components than variables, thus simplifying the data space and mitigating the curse of dimensionality PCA is also best used when the data is linear because it is projecting it onto a linear subspace spanned by the eigenvectors Using PCA, it is going to project our data into directions that maximize the variance along the axes Of course, Scikit-learn also has libraries to apply PCA Full code in my GitHub Repository. Originally published at https://wendynavarrete.com on May 24, 2020.
[ { "code": null, "e": 358, "s": 171, "text": "It is a technique commonly used for linear dimensionality reduction. The idea behind PCA is to find lower dimensional representations of data that retain as much information as possible." }, { "code": null, "e": 392, "s": 358, "text": "Let’s start following next steps." }, { "code": null, "e": 500, "s": 392, "text": "%matplotlib inlineimport pandas as pdimport matplotlib.pyplot as pltimport numpy as npimport seaborn as sns" }, { "code": null, "e": 731, "s": 500, "text": "This is the classic database to be found in the pattern recognition literature. The data set contains 3 classes of 50 instances each, where each class refers to a type of iris plant. Retrieved from UCI Machine Learning Repository." }, { "code": null, "e": 1003, "s": 731, "text": "iris = pd.read_csv(\"https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data\", header=None)iris.columns = [\"sepal_length\",\"sepal_width\", 'petal_length','petal_width','species']iris.dropna(how='all', inplace=True)iris.head()" }, { "code": null, "e": 1207, "s": 1003, "text": "# Plotting data using seabornplt.style.use(\"ggplot\")plt.rcParams[\"figure.figsize\"] = (12,8)sns.scatterplot(x = iris.sepal_length, y=iris.sepal_width, hue = iris.species, style=iris.species)" }, { "code": null, "e": 1446, "s": 1207, "text": "Before applying PCA, the variables will be standardized to have a mean of 0 and a standard deviation of 1. This is important because all variables go through the origin point (where the value of all axes is 0) and share the same variance." }, { "code": null, "e": 2130, "s": 1446, "text": "def standardize_data(arr): ''' This function standardize an array, its substracts mean value, and then divide the standard deviation. param 1: array return: standardized array ''' rows, columns = arr.shape standardizedArray = np.zeros(shape=(rows, columns)) tempArray = np.zeros(rows) for column in range(columns): mean = np.mean(X[:,column]) std = np.std(X[:,column]) tempArray = np.empty(0) for element in X[:,column]: tempArray = np.append(tempArray, ((element - mean) / std)) standardizedArray[:,column] = tempArray return standardizedArray" }, { "code": null, "e": 2225, "s": 2130, "text": "# Standardizing dataX = iris.iloc[:, 0:4].valuesy = iris.species.valuesX = standardize_data(X)" }, { "code": null, "e": 2259, "s": 2225, "text": "Calculating the covariance matrix" }, { "code": null, "e": 2293, "s": 2259, "text": "Calculating the covariance matrix" }, { "code": null, "e": 2634, "s": 2293, "text": "Now I will find the covariance matrix of the dataset by multiplying the matrix of features by its transpose. It is a measure of how much each of the dimensions varies from the mean with respect to each other. Covariance matrices, like correlation matrices, contain information about the amount of variance shared between pairs of variables." }, { "code": null, "e": 2701, "s": 2634, "text": "# Calculating the covariance matrixcovariance_matrix = np.cov(X.T)" }, { "code": null, "e": 2748, "s": 2701, "text": "2. Eigendecomposition of the Covariance Matrix" }, { "code": null, "e": 2928, "s": 2748, "text": "# Using np.linalg.eig functioneigen_values, eigen_vectors = np.linalg.eig(covariance_matrix)print(\"Eigenvector: \\n\",eigen_vectors,\"\\n\")print(\"Eigenvalues: \\n\", eigen_values, \"\\n\")" }, { "code": null, "e": 3323, "s": 2928, "text": "Eigenvectors are the principal components. The first principal component is the first column with values of 0.52, -0.26, 0.58, and 0.56. The second principal component is the second column and so on. Each Eigenvector will correspond to an Eigenvalue, each eigenvector can be scaled of its eigenvalue, whose magnitude indicates how much of the data’s variability is explained by its eigenvector." }, { "code": null, "e": 3465, "s": 3323, "text": "I want to see how much of the variance in data is explained by each one of these components. It is a convention to use 95% explained variance" }, { "code": null, "e": 3659, "s": 3465, "text": "# Calculating the explained variance on each of componentsvariance_explained = []for i in eigen_values: variance_explained.append((i/sum(eigen_values))*100) print(variance_explained)" }, { "code": null, "e": 3797, "s": 3659, "text": "72.77% of the variance on our data is explained by the first principal component, the second principal component explains 23.03% of data." }, { "code": null, "e": 3863, "s": 3797, "text": "Some rules to guide in choosing the number of components to keep:" }, { "code": null, "e": 4048, "s": 3863, "text": "Keep components with eigenvalues greater than 1, as they add value (because they contain more information than a single variable). This rule tends to keep more components than is ideal" }, { "code": null, "e": 4305, "s": 4048, "text": "Visualize the eigenvalues in order from highest to lowest, connecting them with a line. Upon visual inspection, keep all the components whose eigenvalue falls above the point where the slope of the line changes the most drastically, also called the “elbow”" }, { "code": null, "e": 4416, "s": 4305, "text": "Including variance cutoffs where we only keep components that explain at least 95% of the variance in the data" }, { "code": null, "e": 4459, "s": 4416, "text": "Keep comes down the reasons for doing PCA." }, { "code": null, "e": 4607, "s": 4459, "text": "# Identifying components that explain at least 95%cumulative_variance_explained = np.cumsum(variance_explained)print(cumulative_variance_explained)" }, { "code": null, "e": 4797, "s": 4607, "text": "If I use the first feature, it will explain 72.77% of the data; if I use two features I am able to capture 95.8 of the data. If I use all features I am going to describe the entire dataset." }, { "code": null, "e": 5058, "s": 4797, "text": "# Visualizing the eigenvalues and finding the \"elbow\" in the graphicsns.lineplot(x = [1,2,3,4], y=cumulative_variance_explained)plt.xlabel(\"Number of components\")plt.ylabel(\"Cumulative explained variance\")plt.title(\"Explained variance vs Number of components\")" }, { "code": null, "e": 5256, "s": 5058, "text": "In this last step, I will compute the PCA transformation on the original dataset, getting the dot product of the original standardized X and the eigenvectors that I got from the eigendecomposition." }, { "code": null, "e": 5393, "s": 5256, "text": "# Using two first components (because those explain more than 95%)projection_matrix = (eigen_vectors.T[:][:2]).Tprint(projection_matrix)" }, { "code": null, "e": 5508, "s": 5393, "text": "# Getting the product of original standardized X and the eigenvectors X_pca = X.dot(projection_matrix)print(X_pca)" }, { "code": null, "e": 5587, "s": 5508, "text": "Now I can use the components in any analysis exactly as I would use variables." }, { "code": null, "e": 5806, "s": 5587, "text": "PCA transformation was implemented using these NumPy functions: np.cov, np.linalg.eig, np.linalg.svd (it is an alternative to get eigenvalues and eigenvectors), np.cumsum, np.mean, np.std, np.zeros, np.empty and np.dot" }, { "code": null, "e": 5955, "s": 5806, "text": "The benefit of PCA is that there will be fewer components than variables, thus simplifying the data space and mitigating the curse of dimensionality" }, { "code": null, "e": 6080, "s": 5955, "text": "PCA is also best used when the data is linear because it is projecting it onto a linear subspace spanned by the eigenvectors" }, { "code": null, "e": 6181, "s": 6080, "text": "Using PCA, it is going to project our data into directions that maximize the variance along the axes" }, { "code": null, "e": 6237, "s": 6181, "text": "Of course, Scikit-learn also has libraries to apply PCA" }, { "code": null, "e": 6272, "s": 6237, "text": "Full code in my GitHub Repository." } ]
ArduinoJSON: Serialize and Deserialize
The ArduinoJSON library, as the name suggests, helps you work with JSON objects on Arduino. In order to install it, go to the Library Manager, and search for ArduinoJSON. Install the library by Benoit Blanchon. This is one of the very heavily documented libraries. In fact, it has its own website: https://arduinojson.org/. You can find answers to several questions on this website. In this article, we will look at Serialization (generating a JSON document), and deserialization (parsing a JSON document) using this library. Let's start with Serialization. It is pretty straightforward. And if you've worked with python, the code will look all the more familiar. Once you download the ArduinoJSON library, go to - File→Examples→ArduinoJSON The example we should look at, for Serialization, is the JsonGeneratorExample. You will notice that the code is heavily commented, and you are encouraged to go through the comments in the example. Without the comments, this is what the code looks like − #include <ArduinoJson.h> void setup() { Serial.begin(9600); while (!Serial) continue; StaticJsonDocument<200> doc; doc["sensor"] = "gps"; doc["time"] = 1351824120; JsonArray data = doc.createNestedArray("data"); data.add(48.756080); data.add(2.302038); serializeJson(doc, Serial); Serial.println(); serializeJsonPretty(doc, Serial); } void loop() { } The code is, more or less, self-explanatory. The Serial Monitor output is shown below − A couple of things to note − Adding key-value pairs to the JSON has this syntax − doc_name[key] = value The JsonArray type is used for adding array as a value for any key. The above code explains it well (for key "data") Adding key-value pairs to the JSON has this syntax − doc_name[key] = value The JsonArray type is used for adding array as a value for any key. The above code explains it well (for key "data") serializeJSON takes in two arguments: the JSON doc, and the destination buffer. Therefore, instead of directly printing to Serial, you could have used − serializeJSON takes in two arguments: the JSON doc, and the destination buffer. Therefore, instead of directly printing to Serial, you could have used − serializeJson(doc, serializedJSON); Serial.println(serializedJSON); And, the output would have been the same Deserialization is the opposite of serialization. You have a JSON document (it could have come from any source, Serial, webserver, etc.) and you wish to parse it. Go to - File → Examples → ArduinoJSON and open the JsonParserExample. This again, is a heavily commented code, and you are encouraged to go through the comment in the example. Without the comments, the code is − #include <ArduinoJson.h> void setup() { Serial.begin(9600); while (!Serial) continue; StaticJsonDocument<200> doc; char json[] = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}"; DeserializationError error = deserializeJson(doc, json); if (error) { Serial.print(F("deserializeJson() failed: ")); Serial.println(error.f_str()); return; } const char* sensor = doc["sensor"]; long time = doc["time"]; double latitude = doc["data"][0]; double longitude = doc["data"][1]; Serial.println(sensor); Serial.println(time); Serial.println(latitude, 6); Serial.println(longitude, 6); } void loop() { } The Serial Monitor output is − As you can see, the deserialization syntax is deserializeJson(doc, json) and it returns an error if there is any. It takes in two arguments: the JSON Document in which to store the deserialized output, and the buffer containing the JSON contents. Once you have the deserialized content, extracting the content from it has the following syntax − data_type var_name = doc[key] You are encouraged to go through the other ArduinoJSON examples as well.
[ { "code": null, "e": 1273, "s": 1062, "text": "The ArduinoJSON library, as the name suggests, helps you work with JSON objects on Arduino. In order to install it, go to the Library Manager, and search for ArduinoJSON. Install the library by Benoit Blanchon." }, { "code": null, "e": 1445, "s": 1273, "text": "This is one of the very heavily documented libraries. In fact, it has its own website: https://arduinojson.org/. You can find answers to several questions on this website." }, { "code": null, "e": 1588, "s": 1445, "text": "In this article, we will look at Serialization (generating a JSON document), and deserialization (parsing a JSON document) using this library." }, { "code": null, "e": 1726, "s": 1588, "text": "Let's start with Serialization. It is pretty straightforward. And if you've worked with python, the code will look all the more familiar." }, { "code": null, "e": 1803, "s": 1726, "text": "Once you download the ArduinoJSON library, go to - File→Examples→ArduinoJSON" }, { "code": null, "e": 2000, "s": 1803, "text": "The example we should look at, for Serialization, is the JsonGeneratorExample. You will notice that the code is heavily commented, and you are encouraged to go through the comments in the example." }, { "code": null, "e": 2057, "s": 2000, "text": "Without the comments, this is what the code looks like −" }, { "code": null, "e": 2448, "s": 2057, "text": "#include <ArduinoJson.h>\n\nvoid setup() {\n Serial.begin(9600);\n while (!Serial) continue;\n StaticJsonDocument<200> doc;\n doc[\"sensor\"] = \"gps\";\n doc[\"time\"] = 1351824120;\n\n JsonArray data = doc.createNestedArray(\"data\");\n data.add(48.756080);\n data.add(2.302038);\n\n serializeJson(doc, Serial);\n Serial.println();\n\n serializeJsonPretty(doc, Serial);\n}\n void loop() {\n}" }, { "code": null, "e": 2536, "s": 2448, "text": "The code is, more or less, self-explanatory. The Serial Monitor output is shown below −" }, { "code": null, "e": 2565, "s": 2536, "text": "A couple of things to note −" }, { "code": null, "e": 2757, "s": 2565, "text": "Adding key-value pairs to the JSON has this syntax − doc_name[key] = value The JsonArray type is used for adding array as a value for any key. The above code explains it well (for key \"data\")" }, { "code": null, "e": 2949, "s": 2757, "text": "Adding key-value pairs to the JSON has this syntax − doc_name[key] = value The JsonArray type is used for adding array as a value for any key. The above code explains it well (for key \"data\")" }, { "code": null, "e": 3102, "s": 2949, "text": "serializeJSON takes in two arguments: the JSON doc, and the destination buffer. Therefore, instead of directly printing to Serial, you could have used −" }, { "code": null, "e": 3255, "s": 3102, "text": "serializeJSON takes in two arguments: the JSON doc, and the destination buffer. Therefore, instead of directly printing to Serial, you could have used −" }, { "code": null, "e": 3323, "s": 3255, "text": "serializeJson(doc, serializedJSON);\nSerial.println(serializedJSON);" }, { "code": null, "e": 3364, "s": 3323, "text": "And, the output would have been the same" }, { "code": null, "e": 3703, "s": 3364, "text": "Deserialization is the opposite of serialization. You have a JSON document (it could have come from any source, Serial, webserver, etc.) and you wish to parse it. Go to - File → Examples → ArduinoJSON and open the JsonParserExample. This again, is a heavily commented code, and you are encouraged to go through the comment in the example." }, { "code": null, "e": 3739, "s": 3703, "text": "Without the comments, the code is −" }, { "code": null, "e": 4423, "s": 3739, "text": "#include <ArduinoJson.h>\n\nvoid setup() {\n Serial.begin(9600);\n while (!Serial) continue;\n StaticJsonDocument<200> doc;\n\n char json[] = \"{\\\"sensor\\\":\\\"gps\\\",\\\"time\\\":1351824120,\\\"data\\\":[48.756080,2.302038]}\";\n\n DeserializationError error = deserializeJson(doc, json);\n\n if (error) {\n Serial.print(F(\"deserializeJson() failed: \"));\n Serial.println(error.f_str());\n return;\n }\n\n const char* sensor = doc[\"sensor\"];\n long time = doc[\"time\"];\n double latitude = doc[\"data\"][0];\n double longitude = doc[\"data\"][1];\n\n Serial.println(sensor);\n Serial.println(time);\n Serial.println(latitude, 6);\n Serial.println(longitude, 6);\n}\n\nvoid loop() {\n}" }, { "code": null, "e": 4454, "s": 4423, "text": "The Serial Monitor output is −" }, { "code": null, "e": 4701, "s": 4454, "text": "As you can see, the deserialization syntax is deserializeJson(doc, json) and it returns an error if there is any. It takes in two arguments: the JSON Document in which to store the deserialized output, and the buffer containing the JSON contents." }, { "code": null, "e": 4799, "s": 4701, "text": "Once you have the deserialized content, extracting the content from it has the following syntax −" }, { "code": null, "e": 4829, "s": 4799, "text": "data_type var_name = doc[key]" }, { "code": null, "e": 4902, "s": 4829, "text": "You are encouraged to go through the other ArduinoJSON examples as well." } ]
How to execute multiple select queries in MySQL ?
To execute multiple select queries in MySQL, use the concept of DELIMITER. Let us first create a table − mysql> create table DemoTable1 ( Title text )ENGINE=MyISAM; Query OK, 0 rows affected (0.30 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1 values('The database MySQL is less popular than MongoDB') ; Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable1 values('Java language uses MySQL database'); Query OK, 1 row affected (0.05 sec) mysql> insert into DemoTable1 values('Node.js uses the MongoDB') ; Query OK, 1 row affected (0.05 sec) Display all records from the table using select statement − mysql> select *from DemoTable1; This will produce the following output − +-------------------------------------------------+ | Title | +-------------------------------------------------+ | The database MySQL is less popular than MongoDB | | Java language uses MySQL database | | Node.js uses the MongoDB | +-------------------------------------------------+ 3 rows in set (0.00 sec) Following is the query to create the second table − mysql> create table DemoTable2 ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY ); Query OK, 0 rows affected (0.45 sec) Insert some records in the table using insert command − mysql> insert into DemoTable2 values(),(),(),(),(),(),(),(),(); Query OK, 9 rows affected (0.19 sec) Records: 9 Duplicates: 0 Warnings: 0 Display all records from the table using select statement − mysql> select *from DemoTable2; This will produce the following output − +----+ | Id | +----+ | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | | 7 | | 8 | | 9 | +----+ 9 rows in set (0.00 sec) Following is the query to execute multiple select queries − mysql> DELIMITER // mysql> select *from DemoTable1; select *from DemoTable2; // This will produce the following output displaying the result of both the select statements − +-------------------------------------------------+ | Title | +-------------------------------------------------+ | The database MySQL is less popular than MongoDB | | Java language uses MySQL database | | Node.js uses the MongoDB | +-------------------------------------------------+ 3 rows in set (0.00 sec) +----+ | Id | +----+ | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | | 7 | | 8 | | 9 | +----+ 9 rows in set (0.03 sec)
[ { "code": null, "e": 1167, "s": 1062, "text": "To execute multiple select queries in MySQL, use the concept of DELIMITER. Let us first create a table −" }, { "code": null, "e": 1267, "s": 1167, "text": "mysql> create table DemoTable1\n(\n Title text\n)ENGINE=MyISAM;\nQuery OK, 0 rows affected (0.30 sec)" }, { "code": null, "e": 1323, "s": 1267, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1663, "s": 1323, "text": "mysql> insert into DemoTable1 values('The database MySQL is less popular than MongoDB') ;\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable1 values('Java language uses MySQL database');\nQuery OK, 1 row affected (0.05 sec)\nmysql> insert into DemoTable1 values('Node.js uses the MongoDB') ;\nQuery OK, 1 row affected (0.05 sec)" }, { "code": null, "e": 1723, "s": 1663, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1755, "s": 1723, "text": "mysql> select *from DemoTable1;" }, { "code": null, "e": 1796, "s": 1755, "text": "This will produce the following output −" }, { "code": null, "e": 2185, "s": 1796, "text": "+-------------------------------------------------+\n| Title |\n+-------------------------------------------------+\n| The database MySQL is less popular than MongoDB |\n| Java language uses MySQL database |\n| Node.js uses the MongoDB |\n+-------------------------------------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2237, "s": 2185, "text": "Following is the query to create the second table −" }, { "code": null, "e": 2356, "s": 2237, "text": "mysql> create table DemoTable2\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY\n);\nQuery OK, 0 rows affected (0.45 sec)" }, { "code": null, "e": 2412, "s": 2356, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2550, "s": 2412, "text": "mysql> insert into DemoTable2 values(),(),(),(),(),(),(),(),();\nQuery OK, 9 rows affected (0.19 sec)\nRecords: 9 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2610, "s": 2550, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2642, "s": 2610, "text": "mysql> select *from DemoTable2;" }, { "code": null, "e": 2683, "s": 2642, "text": "This will produce the following output −" }, { "code": null, "e": 2799, "s": 2683, "text": "+----+\n| Id |\n+----+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 5 |\n| 6 |\n| 7 |\n| 8 |\n| 9 |\n+----+\n9 rows in set (0.00 sec)" }, { "code": null, "e": 2859, "s": 2799, "text": "Following is the query to execute multiple select queries −" }, { "code": null, "e": 2939, "s": 2859, "text": "mysql> DELIMITER //\nmysql> select *from DemoTable1;\nselect *from DemoTable2;\n//" }, { "code": null, "e": 3032, "s": 2939, "text": "This will produce the following output displaying the result of both the select statements −" }, { "code": null, "e": 3537, "s": 3032, "text": "+-------------------------------------------------+\n| Title |\n+-------------------------------------------------+\n| The database MySQL is less popular than MongoDB |\n| Java language uses MySQL database |\n| Node.js uses the MongoDB |\n+-------------------------------------------------+\n3 rows in set (0.00 sec)\n+----+\n| Id |\n+----+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 5 |\n| 6 |\n| 7 |\n| 8 |\n| 9 |\n+----+\n9 rows in set (0.03 sec)" } ]
JavaScript | Object Methods - GeeksforGeeks
04 Aug, 2021 Object Methods in JavaScript can be accessed by using functions. Functions in JavaScript are stored as property values. The objects can also be called without using bracket (). In a method, ‘this’ refers to the owner object. Additional information can also be added along with the object method. Syntax: objectName.methodName() Properties: A function may be divided into different property values, which are then combined and returned together. For Ex: Student function contains the properties: name class section Return Value: It returns methods/functions stored as object properties.Example 1: This example use function definition as property value. HTML <!DOCTYPE html><html> <head> <title> JavaScript Object Methods </title></head> <body> <h1>Geeks</h1> <h3>JavaScript Object Method</h3> <p> studentDetail is a function definition, it is stored as a property value. </p> <p id="gfg"></p> <script> // Object creation var student = { name: "Martin", class : "12th", section : "A", studentDetails : function() { return this.name + " " + this.class + " " + this.section + " "; } }; // Display object data document.getElementById("gfg").innerHTML = student.studentDetails(); </script></body> </html> Output: Example 2: This example use storing property values and accessing without bracket (). HTML <!DOCTYPE html><html> <head> <title> JavaScript Object Methods </title></head> <body> <h1>Geeks</h1> <h3>JavaScript Object Method</h3> <p> studentDetail is a function definition, it is stored as a property value. </p> <p> Function definition is returned if we don't use (). </p> <p id="gfg"></p> <script> // Object creation var student = { name: "Martin", class : "12th", section : "A", studentDetails : function() { return this.name + " " + this.class + " " + this.section + " "; } }; // Display object data document.getElementById("gfg").innerHTML = student.studentDetails; </script></body> </html> Output: Example 3: Using function definition as property value and accessing with additional details. HTML <!DOCTYPE html><html> <head> <title> JavaScript Object Methods </title></head> <body> <h1>Geeks</h1> <h3>JavaScript Object Method</h3> <p> studentDetail is a function definition, it is stored as a property value. </p> <p id="gfg"></p> <script> // Object creation var student = { name: "Martin", class : "12th", section : "A", studentDetails : function() { return this.name + " " + this.class + " " + this.section + " "; } }; // Display object data document.getElementById("gfg").innerHTML = "STUDENT " + student.studentDetails(); </script></body> </html> Output: Supported Browser: Google Chrome Microsoft Edge Firefox safari ysachin2314 javascript-object Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript Set the value of an input field in JavaScript Differences between Functional Components and Class Components in React Form validation using HTML and JavaScript Difference between var, let and const keywords in JavaScript Express.js express.Router() Function Installation of Node.js on Linux Convert a string to an integer in JavaScript How to set the default value for an HTML <select> element ? Top 10 Angular Libraries For Web Developers
[ { "code": null, "e": 24069, "s": 24041, "text": "\n04 Aug, 2021" }, { "code": null, "e": 24248, "s": 24069, "text": "Object Methods in JavaScript can be accessed by using functions. Functions in JavaScript are stored as property values. The objects can also be called without using bracket (). " }, { "code": null, "e": 24296, "s": 24248, "text": "In a method, ‘this’ refers to the owner object." }, { "code": null, "e": 24367, "s": 24296, "text": "Additional information can also be added along with the object method." }, { "code": null, "e": 24377, "s": 24367, "text": "Syntax: " }, { "code": null, "e": 24401, "s": 24377, "text": "objectName.methodName()" }, { "code": null, "e": 24570, "s": 24401, "text": "Properties: A function may be divided into different property values, which are then combined and returned together. For Ex: Student function contains the properties: " }, { "code": null, "e": 24575, "s": 24570, "text": "name" }, { "code": null, "e": 24581, "s": 24575, "text": "class" }, { "code": null, "e": 24589, "s": 24581, "text": "section" }, { "code": null, "e": 24729, "s": 24589, "text": "Return Value: It returns methods/functions stored as object properties.Example 1: This example use function definition as property value. " }, { "code": null, "e": 24734, "s": 24729, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript Object Methods </title></head> <body> <h1>Geeks</h1> <h3>JavaScript Object Method</h3> <p> studentDetail is a function definition, it is stored as a property value. </p> <p id=\"gfg\"></p> <script> // Object creation var student = { name: \"Martin\", class : \"12th\", section : \"A\", studentDetails : function() { return this.name + \" \" + this.class + \" \" + this.section + \" \"; } }; // Display object data document.getElementById(\"gfg\").innerHTML = student.studentDetails(); </script></body> </html> ", "e": 25544, "s": 24734, "text": null }, { "code": null, "e": 25554, "s": 25544, "text": "Output: " }, { "code": null, "e": 25642, "s": 25554, "text": "Example 2: This example use storing property values and accessing without bracket (). " }, { "code": null, "e": 25647, "s": 25642, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript Object Methods </title></head> <body> <h1>Geeks</h1> <h3>JavaScript Object Method</h3> <p> studentDetail is a function definition, it is stored as a property value. </p> <p> Function definition is returned if we don't use (). </p> <p id=\"gfg\"></p> <script> // Object creation var student = { name: \"Martin\", class : \"12th\", section : \"A\", studentDetails : function() { return this.name + \" \" + this.class + \" \" + this.section + \" \"; } }; // Display object data document.getElementById(\"gfg\").innerHTML = student.studentDetails; </script></body> </html> ", "e": 26538, "s": 25647, "text": null }, { "code": null, "e": 26548, "s": 26538, "text": "Output: " }, { "code": null, "e": 26644, "s": 26548, "text": "Example 3: Using function definition as property value and accessing with additional details. " }, { "code": null, "e": 26649, "s": 26644, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript Object Methods </title></head> <body> <h1>Geeks</h1> <h3>JavaScript Object Method</h3> <p> studentDetail is a function definition, it is stored as a property value. </p> <p id=\"gfg\"></p> <script> // Object creation var student = { name: \"Martin\", class : \"12th\", section : \"A\", studentDetails : function() { return this.name + \" \" + this.class + \" \" + this.section + \" \"; } }; // Display object data document.getElementById(\"gfg\").innerHTML = \"STUDENT \" + student.studentDetails(); </script></body> </html> ", "e": 27420, "s": 26649, "text": null }, { "code": null, "e": 27430, "s": 27420, "text": "Output: " }, { "code": null, "e": 27449, "s": 27430, "text": "Supported Browser:" }, { "code": null, "e": 27463, "s": 27449, "text": "Google Chrome" }, { "code": null, "e": 27478, "s": 27463, "text": "Microsoft Edge" }, { "code": null, "e": 27486, "s": 27478, "text": "Firefox" }, { "code": null, "e": 27494, "s": 27486, "text": "safari " }, { "code": null, "e": 27506, "s": 27494, "text": "ysachin2314" }, { "code": null, "e": 27524, "s": 27506, "text": "javascript-object" }, { "code": null, "e": 27531, "s": 27524, "text": "Picked" }, { "code": null, "e": 27542, "s": 27531, "text": "JavaScript" }, { "code": null, "e": 27559, "s": 27542, "text": "Web Technologies" }, { "code": null, "e": 27657, "s": 27559, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27666, "s": 27657, "text": "Comments" }, { "code": null, "e": 27679, "s": 27666, "text": "Old Comments" }, { "code": null, "e": 27724, "s": 27679, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27770, "s": 27724, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 27842, "s": 27770, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27884, "s": 27842, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 27945, "s": 27884, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27982, "s": 27945, "text": "Express.js express.Router() Function" }, { "code": null, "e": 28015, "s": 27982, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28060, "s": 28015, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28120, "s": 28060, "text": "How to set the default value for an HTML <select> element ?" } ]
Programmatically opening URLs in a web browser in Python (tkinter)
Python has a rich library of extensions and modules which are used for multiple purposes. To work with web-based content, Python provides a webbrowser module. The module creates an environment which enables the user to display web-based content in the application. To work with webbrowser, you have to make sure that it is installed in your local machine. import webbrowser If the module is not available in your environment, then you can install it using the following command − pip install webbrowser Using the webbrowser module in our program, we will open an URL in our web browser. To open the URL in a default browser, we can use the open() function in the module. # Import the required libraries import webbrowser # Add a URL to open in a new window url= 'https://www.tutorialspoint.com/' # Open the URL in a new Tab webbrowser.open_new_tab(url) Running the above code will open the given URL in a new window of the default browser.
[ { "code": null, "e": 1418, "s": 1062, "text": "Python has a rich library of extensions and modules which are used for multiple purposes. To work with web-based content, Python provides a webbrowser module. The module creates an environment which enables the user to display web-based content in the application. To work with webbrowser, you have to make sure that it is installed in your local machine." }, { "code": null, "e": 1436, "s": 1418, "text": "import webbrowser" }, { "code": null, "e": 1542, "s": 1436, "text": "If the module is not available in your environment, then you can install it using the following command −" }, { "code": null, "e": 1565, "s": 1542, "text": "pip install webbrowser" }, { "code": null, "e": 1733, "s": 1565, "text": "Using the webbrowser module in our program, we will open an URL in our web browser. To open the URL in a default browser, we can use the open() function in the module." }, { "code": null, "e": 1917, "s": 1733, "text": "# Import the required libraries\nimport webbrowser\n\n# Add a URL to open in a new window\nurl= 'https://www.tutorialspoint.com/'\n\n# Open the URL in a new Tab\nwebbrowser.open_new_tab(url)" }, { "code": null, "e": 2004, "s": 1917, "text": "Running the above code will open the given URL in a new window of the default browser." } ]
Correlation Is Simple With Seaborn And Pandas | by Jeremiah Lutes | Towards Data Science
Datasets can tell many stories. A great place to start, to see these stories unfold, is checking for correlations between the variables. One of the first tasks I perform when exploring a dataset to see which variables have correlations. This gives me a better understanding of the data I’m working with. It’s also a great way to develop an interest in the data and establish some initial questions to try to answer. Simply put, correlations are awesome. Luckily Python has some amazing libraries which give us the tools we need to quickly and efficiently look at correlations. Let’s take a brief look at what correlation is and how to find strong correlations in a dataset using a heat map. Correlation is a way to determine if two variables in a dataset are related in any way. Correlations have many real-world applications. We can see if using certain search terms are correlated to views on youtube. Or, we can see if ads are correlated to sales. When building machine learning models correlations are an important factor in determining features. Not only can this help us to see which features are linear related, but if features are strongly correlated we can remove them to prevent duplicating information. In data science we can use the r value, also called Pearson’s correlation coefficient. This measures how closely two sequences of numbers( i.e., columns, lists, series, etc.) are correlated. The r value is a number between -1 and 1. It tells us whether two columns are positively correlated, not correlated, or negatively correlated. The closer to 1, the stronger the positive correlation. The closer to -1, the stronger the negative correlation (i.e., the more “opposite” the columns are). The closer to 0, the weaker the correlation. The rvalue formula is: We aren’t going to explain the math behind the r value, but if you are curious, this youtube video does a great job. Instead, let’s visualize correlations with a simple dataset The dataset below shows data on seven children. It has the following columns, weight, age(in months), amount of baby teeth, and eye color. The eye color column has been categorized where 1 = blue, 2 = green, and 3 = brown. Let’s make 3 scatter plots using the above data. We’ll look at the following 3 relationships: age and weight, age and baby teeth, and age and eye color. When we look at the correlation between age and weight the plot points start to form a positive slope. When we calculate the r value we get 0.954491. With the r value so close to 1, we can come to the conclusion that age and weight have a strong positive correlation. Intuitively, this should check out. In a growing child, as they get older and grow they start to weigh more. Conversely, the plot points on the age and baby teeth scatter plot start to form a negative slope. The r value of this correlation is -0.958188. This signifies a strong negative correlation. Intuitively, this also makes sense. As a child gets older they lose their baby teeth. On our last scatterplot, we see some plot points with no clear slope. This correlation has an r value of -0.126163. There is no significant correlation between age and eye color. This should also make sense as eye color shouldn’t change as a child gets older. If this relationship showed a strong correlation we would want to examine the data to find out why. Let’s look at a larger dataset and see how easy it is to find correlations using Python. The data we’ll look at comes from a Kaggle dataset about movies on streaming platforms. This dataset contains data on which movies are what streaming platforms. It also includes a few various qualifiers about each movie such as name, runtime, IMDB score, etc. We’ll first import the dataset and turn it into a DataFrame using pandas. import pandas as pdmovies = pd.read_csv("MoviesOnStreamingPlatforms_updated.csv") The Rotten Tomatoes column is a string, let’s change the data type to a float. movies['Rotten Tomatoes'] = movies['Rotten Tomatoes'].str.replace("%" , "").astype(float) The Type column doesn’t seem to be entered properly, let’s drop it. movies.drop("Type", inplace=True, axis=1) Alright now for the fun stuff! Using the Pandas correlation method we can see correlations for all numerical columns in the DataFrame. Since this is a method, all we have to do is call it on the DataFrame. The return value will be a new DataFrame showing each correlation. *the corr() method has a parameter that allows you to choose which method to find the correlation coefficient. The Pearson method is the default, but you can also choose the Kendall or Spearman method. correlations = movies.corr()print(correlations)\\ID Year IMDb Rotten Tomatoes Netflix \ID 1.000000 -0.254391 -0.399953 -0.201452 -0.708680 Year -0.254391 1.000000 -0.021181 -0.057137 0.258533 IMDb -0.399953 -0.021181 1.000000 0.616320 0.135105 Rotten Tomatoes -0.201452 -0.057137 0.616320 1.000000 0.017842 Netflix -0.708680 0.258533 0.135105 0.017842 1.000000 Hulu -0.219737 0.098009 0.042191 0.020373 -0.107911 Prime Video 0.554120 -0.253377 -0.163447 -0.049916 -0.757215 Disney+ 0.287011 -0.046819 0.075895 -0.011805 -0.088927 Runtime -0.206003 0.081984 0.088987 0.003791 0.099526Hulu Prime Video Disney+ Runtime ID -0.219737 0.554120 0.287011 -0.206003 Year 0.098009 -0.253377 -0.046819 0.081984 IMDb 0.042191 -0.163447 0.075895 0.088987 Rotten Tomatoes 0.020373 -0.049916 -0.011805 0.003791 Netflix -0.107911 -0.757215 -0.088927 0.099526 Hulu 1.000000 -0.255641 -0.034317 0.033985 Prime Video -0.255641 1.000000 -0.298900 -0.067378 Disney+ -0.034317 -0.298900 1.000000 -0.019976 Runtime 0.033985 -0.067378 -0.019976 1.000000 Yikes! That is a lot of numbers. The output has too many columns making it hard to read. This is only the correlations for 9 variables which results in a 9x9 grid. Can you imagine looking at 20 or 30? It would be very difficult. Things get a little better if we don’t call print and just let Jupyter notebook format the return. movies.corr() We could also check each variable individually by slicing using the column name. print(correlations["Year"])//ID -0.254391Year 1.000000IMDb -0.021181Rotten Tomatoes -0.057137Netflix 0.258533Hulu 0.098009Prime Video -0.253377Disney+ -0.046819Runtime 0.081984 This is a little easier to read and sufficient if only looking at the correlations for 1 variable. But, there must be an easier way to look at a whole dataset. Lucky for us, seaborn gives us the ability to quickly generate a heat map. We simply import seaborn and matplotlib and use seaborn’s heatmap() function. #always remember your magic function if using Jupyter%matplotlib inlineimport seaborn as snsimport matplotlib.pyplot as pltsns.heatmap(correlations)plt.show() Wow! How cool is that? Now we can quickly see a few correlations; A strong positive correlation between IMDb and Rotten Tomatoes. As well as a strong positive correlation between Prime Video and ID.A slight positive correlation between Netflix and Year.Strong negative correlations between Netflix and ID, Netflix and Prime VideoSlight negative correlations between Year and Prime Video, Disney Plus and Prime Video, Hulu and Prime Video, and Netflix and ID.No correlation between runtime and any of the streaming platforms. No correlation between Netflix and year A strong positive correlation between IMDb and Rotten Tomatoes. As well as a strong positive correlation between Prime Video and ID. A slight positive correlation between Netflix and Year. Strong negative correlations between Netflix and ID, Netflix and Prime Video Slight negative correlations between Year and Prime Video, Disney Plus and Prime Video, Hulu and Prime Video, and Netflix and ID. No correlation between runtime and any of the streaming platforms. No correlation between Netflix and year With that information, we can make a few observations. With strong positive and negative correlations between ID and two of the platforms it appears, the data was added sequentially with Netflix first and Prime Video last. If we are going to use this data to build a model it would be best to shuffle it before splitting into test and training data.It looks like Netflix has newer movies. This could be a hypothesis to explore.Netflix and Amazon appear to have the highest amount of unique movies when compared to the other streaming platforms. Another hypothesis to explore.The different platforms don’t appear to choose movies based on scores by critics or runtime. Yet another cool hypothesis we can explore. With strong positive and negative correlations between ID and two of the platforms it appears, the data was added sequentially with Netflix first and Prime Video last. If we are going to use this data to build a model it would be best to shuffle it before splitting into test and training data. It looks like Netflix has newer movies. This could be a hypothesis to explore. Netflix and Amazon appear to have the highest amount of unique movies when compared to the other streaming platforms. Another hypothesis to explore. The different platforms don’t appear to choose movies based on scores by critics or runtime. Yet another cool hypothesis we can explore. In a matter of seconds, we were able to see how the data was entered and get at least 3 ideas to explore. Correlations are useful to help explore a new dataset. By using seaborn’s heatmap we easily saw where the strongest correlations are. Now you can go to Kaggle and check out a few more datasets to see what other correlations might spark your interest!
[ { "code": null, "e": 625, "s": 171, "text": "Datasets can tell many stories. A great place to start, to see these stories unfold, is checking for correlations between the variables. One of the first tasks I perform when exploring a dataset to see which variables have correlations. This gives me a better understanding of the data I’m working with. It’s also a great way to develop an interest in the data and establish some initial questions to try to answer. Simply put, correlations are awesome." }, { "code": null, "e": 862, "s": 625, "text": "Luckily Python has some amazing libraries which give us the tools we need to quickly and efficiently look at correlations. Let’s take a brief look at what correlation is and how to find strong correlations in a dataset using a heat map." }, { "code": null, "e": 1385, "s": 862, "text": "Correlation is a way to determine if two variables in a dataset are related in any way. Correlations have many real-world applications. We can see if using certain search terms are correlated to views on youtube. Or, we can see if ads are correlated to sales. When building machine learning models correlations are an important factor in determining features. Not only can this help us to see which features are linear related, but if features are strongly correlated we can remove them to prevent duplicating information." }, { "code": null, "e": 1576, "s": 1385, "text": "In data science we can use the r value, also called Pearson’s correlation coefficient. This measures how closely two sequences of numbers( i.e., columns, lists, series, etc.) are correlated." }, { "code": null, "e": 1921, "s": 1576, "text": "The r value is a number between -1 and 1. It tells us whether two columns are positively correlated, not correlated, or negatively correlated. The closer to 1, the stronger the positive correlation. The closer to -1, the stronger the negative correlation (i.e., the more “opposite” the columns are). The closer to 0, the weaker the correlation." }, { "code": null, "e": 1944, "s": 1921, "text": "The rvalue formula is:" }, { "code": null, "e": 2121, "s": 1944, "text": "We aren’t going to explain the math behind the r value, but if you are curious, this youtube video does a great job. Instead, let’s visualize correlations with a simple dataset" }, { "code": null, "e": 2344, "s": 2121, "text": "The dataset below shows data on seven children. It has the following columns, weight, age(in months), amount of baby teeth, and eye color. The eye color column has been categorized where 1 = blue, 2 = green, and 3 = brown." }, { "code": null, "e": 2497, "s": 2344, "text": "Let’s make 3 scatter plots using the above data. We’ll look at the following 3 relationships: age and weight, age and baby teeth, and age and eye color." }, { "code": null, "e": 2874, "s": 2497, "text": "When we look at the correlation between age and weight the plot points start to form a positive slope. When we calculate the r value we get 0.954491. With the r value so close to 1, we can come to the conclusion that age and weight have a strong positive correlation. Intuitively, this should check out. In a growing child, as they get older and grow they start to weigh more." }, { "code": null, "e": 3151, "s": 2874, "text": "Conversely, the plot points on the age and baby teeth scatter plot start to form a negative slope. The r value of this correlation is -0.958188. This signifies a strong negative correlation. Intuitively, this also makes sense. As a child gets older they lose their baby teeth." }, { "code": null, "e": 3511, "s": 3151, "text": "On our last scatterplot, we see some plot points with no clear slope. This correlation has an r value of -0.126163. There is no significant correlation between age and eye color. This should also make sense as eye color shouldn’t change as a child gets older. If this relationship showed a strong correlation we would want to examine the data to find out why." }, { "code": null, "e": 3600, "s": 3511, "text": "Let’s look at a larger dataset and see how easy it is to find correlations using Python." }, { "code": null, "e": 3860, "s": 3600, "text": "The data we’ll look at comes from a Kaggle dataset about movies on streaming platforms. This dataset contains data on which movies are what streaming platforms. It also includes a few various qualifiers about each movie such as name, runtime, IMDB score, etc." }, { "code": null, "e": 3934, "s": 3860, "text": "We’ll first import the dataset and turn it into a DataFrame using pandas." }, { "code": null, "e": 4016, "s": 3934, "text": "import pandas as pdmovies = pd.read_csv(\"MoviesOnStreamingPlatforms_updated.csv\")" }, { "code": null, "e": 4095, "s": 4016, "text": "The Rotten Tomatoes column is a string, let’s change the data type to a float." }, { "code": null, "e": 4185, "s": 4095, "text": "movies['Rotten Tomatoes'] = movies['Rotten Tomatoes'].str.replace(\"%\" , \"\").astype(float)" }, { "code": null, "e": 4253, "s": 4185, "text": "The Type column doesn’t seem to be entered properly, let’s drop it." }, { "code": null, "e": 4295, "s": 4253, "text": "movies.drop(\"Type\", inplace=True, axis=1)" }, { "code": null, "e": 4326, "s": 4295, "text": "Alright now for the fun stuff!" }, { "code": null, "e": 4568, "s": 4326, "text": "Using the Pandas correlation method we can see correlations for all numerical columns in the DataFrame. Since this is a method, all we have to do is call it on the DataFrame. The return value will be a new DataFrame showing each correlation." }, { "code": null, "e": 4770, "s": 4568, "text": "*the corr() method has a parameter that allows you to choose which method to find the correlation coefficient. The Pearson method is the default, but you can also choose the Kendall or Spearman method." }, { "code": null, "e": 6121, "s": 4770, "text": "correlations = movies.corr()print(correlations)\\\\ID Year IMDb Rotten Tomatoes Netflix \\ID 1.000000 -0.254391 -0.399953 -0.201452 -0.708680 Year -0.254391 1.000000 -0.021181 -0.057137 0.258533 IMDb -0.399953 -0.021181 1.000000 0.616320 0.135105 Rotten Tomatoes -0.201452 -0.057137 0.616320 1.000000 0.017842 Netflix -0.708680 0.258533 0.135105 0.017842 1.000000 Hulu -0.219737 0.098009 0.042191 0.020373 -0.107911 Prime Video 0.554120 -0.253377 -0.163447 -0.049916 -0.757215 Disney+ 0.287011 -0.046819 0.075895 -0.011805 -0.088927 Runtime -0.206003 0.081984 0.088987 0.003791 0.099526Hulu Prime Video Disney+ Runtime ID -0.219737 0.554120 0.287011 -0.206003 Year 0.098009 -0.253377 -0.046819 0.081984 IMDb 0.042191 -0.163447 0.075895 0.088987 Rotten Tomatoes 0.020373 -0.049916 -0.011805 0.003791 Netflix -0.107911 -0.757215 -0.088927 0.099526 Hulu 1.000000 -0.255641 -0.034317 0.033985 Prime Video -0.255641 1.000000 -0.298900 -0.067378 Disney+ -0.034317 -0.298900 1.000000 -0.019976 Runtime 0.033985 -0.067378 -0.019976 1.000000" }, { "code": null, "e": 6350, "s": 6121, "text": "Yikes! That is a lot of numbers. The output has too many columns making it hard to read. This is only the correlations for 9 variables which results in a 9x9 grid. Can you imagine looking at 20 or 30? It would be very difficult." }, { "code": null, "e": 6449, "s": 6350, "text": "Things get a little better if we don’t call print and just let Jupyter notebook format the return." }, { "code": null, "e": 6463, "s": 6449, "text": "movies.corr()" }, { "code": null, "e": 6544, "s": 6463, "text": "We could also check each variable individually by slicing using the column name." }, { "code": null, "e": 6817, "s": 6544, "text": "print(correlations[\"Year\"])//ID -0.254391Year 1.000000IMDb -0.021181Rotten Tomatoes -0.057137Netflix 0.258533Hulu 0.098009Prime Video -0.253377Disney+ -0.046819Runtime 0.081984" }, { "code": null, "e": 6977, "s": 6817, "text": "This is a little easier to read and sufficient if only looking at the correlations for 1 variable. But, there must be an easier way to look at a whole dataset." }, { "code": null, "e": 7052, "s": 6977, "text": "Lucky for us, seaborn gives us the ability to quickly generate a heat map." }, { "code": null, "e": 7130, "s": 7052, "text": "We simply import seaborn and matplotlib and use seaborn’s heatmap() function." }, { "code": null, "e": 7289, "s": 7130, "text": "#always remember your magic function if using Jupyter%matplotlib inlineimport seaborn as snsimport matplotlib.pyplot as pltsns.heatmap(correlations)plt.show()" }, { "code": null, "e": 7312, "s": 7289, "text": "Wow! How cool is that?" }, { "code": null, "e": 7355, "s": 7312, "text": "Now we can quickly see a few correlations;" }, { "code": null, "e": 7854, "s": 7355, "text": "A strong positive correlation between IMDb and Rotten Tomatoes. As well as a strong positive correlation between Prime Video and ID.A slight positive correlation between Netflix and Year.Strong negative correlations between Netflix and ID, Netflix and Prime VideoSlight negative correlations between Year and Prime Video, Disney Plus and Prime Video, Hulu and Prime Video, and Netflix and ID.No correlation between runtime and any of the streaming platforms. No correlation between Netflix and year" }, { "code": null, "e": 7987, "s": 7854, "text": "A strong positive correlation between IMDb and Rotten Tomatoes. As well as a strong positive correlation between Prime Video and ID." }, { "code": null, "e": 8043, "s": 7987, "text": "A slight positive correlation between Netflix and Year." }, { "code": null, "e": 8120, "s": 8043, "text": "Strong negative correlations between Netflix and ID, Netflix and Prime Video" }, { "code": null, "e": 8250, "s": 8120, "text": "Slight negative correlations between Year and Prime Video, Disney Plus and Prime Video, Hulu and Prime Video, and Netflix and ID." }, { "code": null, "e": 8357, "s": 8250, "text": "No correlation between runtime and any of the streaming platforms. No correlation between Netflix and year" }, { "code": null, "e": 8412, "s": 8357, "text": "With that information, we can make a few observations." }, { "code": null, "e": 9069, "s": 8412, "text": "With strong positive and negative correlations between ID and two of the platforms it appears, the data was added sequentially with Netflix first and Prime Video last. If we are going to use this data to build a model it would be best to shuffle it before splitting into test and training data.It looks like Netflix has newer movies. This could be a hypothesis to explore.Netflix and Amazon appear to have the highest amount of unique movies when compared to the other streaming platforms. Another hypothesis to explore.The different platforms don’t appear to choose movies based on scores by critics or runtime. Yet another cool hypothesis we can explore." }, { "code": null, "e": 9364, "s": 9069, "text": "With strong positive and negative correlations between ID and two of the platforms it appears, the data was added sequentially with Netflix first and Prime Video last. If we are going to use this data to build a model it would be best to shuffle it before splitting into test and training data." }, { "code": null, "e": 9443, "s": 9364, "text": "It looks like Netflix has newer movies. This could be a hypothesis to explore." }, { "code": null, "e": 9592, "s": 9443, "text": "Netflix and Amazon appear to have the highest amount of unique movies when compared to the other streaming platforms. Another hypothesis to explore." }, { "code": null, "e": 9729, "s": 9592, "text": "The different platforms don’t appear to choose movies based on scores by critics or runtime. Yet another cool hypothesis we can explore." }, { "code": null, "e": 9835, "s": 9729, "text": "In a matter of seconds, we were able to see how the data was entered and get at least 3 ideas to explore." } ]
Ant - Executing Java code
You can use Ant to execute the Java code. In the following example, the java class takes in an argument (administrator's email address) and send out an email. public class NotifyAdministrator { public static void main(String[] args) { String email = args[0]; notifyAdministratorviaEmail(email); System.out.println("Administrator "+email+" has been notified"); } public static void notifyAdministratorviaEmail(String email { //...... } } Here is a simple build that executes this java class. <?xml version="1.0"?> <project name="sample" basedir="." default="notify"> <target name="notify"> <java fork="true" failonerror="yes" classname="NotifyAdministrator"> <arg line="[email protected]"/> </java> </target> </project> When the build is executed, it produces the following outcome − C:\>ant Buildfile: C:\build.xml notify: [java] Administrator [email protected] has been notified BUILD SUCCESSFUL Total time: 1 second In this example, the java code does a simple thing which is, to send an email. We could have used the built in the Ant task to do that. However, now that you have got the idea, you can extend your build file to call the java code that performs complicated things. For example: encrypts your source code. 20 Lectures 2 hours Deepti Trivedi 19 Lectures 2.5 hours Deepti Trivedi 139 Lectures 14 hours Er. Himanshu Vasishta 30 Lectures 1.5 hours Pushpendu Mondal 65 Lectures 6.5 hours Ridhi Arora 10 Lectures 2 hours Manish Gupta Print Add Notes Bookmark this page
[ { "code": null, "e": 2256, "s": 2097, "text": "You can use Ant to execute the Java code. In the following example, the java class takes in an argument (administrator's email address) and send out an email." }, { "code": null, "e": 2570, "s": 2256, "text": "public class NotifyAdministrator {\n public static void main(String[] args) {\n String email = args[0];\n notifyAdministratorviaEmail(email);\n System.out.println(\"Administrator \"+email+\" has been notified\");\n }\n public static void notifyAdministratorviaEmail(String email {\n //......\n }\n}" }, { "code": null, "e": 2624, "s": 2570, "text": "Here is a simple build that executes this java class." }, { "code": null, "e": 2876, "s": 2624, "text": "<?xml version=\"1.0\"?>\n<project name=\"sample\" basedir=\".\" default=\"notify\">\n <target name=\"notify\">\n <java fork=\"true\" failonerror=\"yes\" classname=\"NotifyAdministrator\">\n <arg line=\"[email protected]\"/>\n </java>\n </target>\n</project>" }, { "code": null, "e": 2940, "s": 2876, "text": "When the build is executed, it produces the following outcome −" }, { "code": null, "e": 3074, "s": 2940, "text": "C:\\>ant\nBuildfile: C:\\build.xml\n\nnotify: [java] Administrator [email protected] has been notified\n\nBUILD SUCCESSFUL\nTotal time: 1 second" }, { "code": null, "e": 3210, "s": 3074, "text": "In this example, the java code does a simple thing which is, to send an email. We could have used the built in the Ant task to do that." }, { "code": null, "e": 3378, "s": 3210, "text": "However, now that you have got the idea, you can extend your build file to call the java code that performs complicated things. For example: encrypts your source code." }, { "code": null, "e": 3411, "s": 3378, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 3427, "s": 3411, "text": " Deepti Trivedi" }, { "code": null, "e": 3462, "s": 3427, "text": "\n 19 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3478, "s": 3462, "text": " Deepti Trivedi" }, { "code": null, "e": 3513, "s": 3478, "text": "\n 139 Lectures \n 14 hours \n" }, { "code": null, "e": 3536, "s": 3513, "text": " Er. Himanshu Vasishta" }, { "code": null, "e": 3571, "s": 3536, "text": "\n 30 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3589, "s": 3571, "text": " Pushpendu Mondal" }, { "code": null, "e": 3624, "s": 3589, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3637, "s": 3624, "text": " Ridhi Arora" }, { "code": null, "e": 3670, "s": 3637, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 3684, "s": 3670, "text": " Manish Gupta" }, { "code": null, "e": 3691, "s": 3684, "text": " Print" }, { "code": null, "e": 3702, "s": 3691, "text": " Add Notes" } ]
C Program for Matrix Chain Multiplication
In this problem, we are given a sequence( array) of metrics. our task is to create a C program for Matrix chain multiplication. We need to find a way to multiply these matrixes so that, the minimum number of multiplications is required. The array of matrices will contain n elements, which define the dimensions of the matrices as, arr[i-1] X arr[i]. Let’s take an example to understand the problem, array[] = {3, 4, 5, 6} the matrices will be of the order − Mat1 = 3X4, Mat2 = 4X5, Mat3 = 5X6 For these three matrices, there can be two ways to multiply, mat1*(mat2*mat3) -> (3*4*6) + (4*5*6) = 72 + 120 = 192 (mat1*mat2)*mat3 -> (3*4*5) + (3*5*6) = 60 + 90 = 150 The minimum number of mulitplications will be 150 in case of (mat1*mat2)*mat3. The problem can be solved using dynamic programming as it posses both the properties i.e. optimal substructure and overlapping substructure in dynamic programming. So here is C Program for Matrix Chain Multiplication using dynamic programming Live Demo #include <stdio.h> int MatrixChainMultuplication(int arr[], int n) { int minMul[n][n]; int j, q; for (int i = 1; i < n; i++) minMul[i][i] = 0; for (int L = 2; L < n; L++) { for (int i = 1; i < n - L + 1; i++) { j = i + L - 1; minMul[i][j] = 99999999; for (int k = i; k <= j - 1; k++) { q = minMul[i][k] + minMul[k + 1][j] + arr[i - 1] * arr[k] * arr[j]; if (q < minMul[i][j]) minMul[i][j] = q; } } } return minMul[1][n - 1]; } int main(){ int arr[] = {3, 4, 5, 6, 7, 8}; int size = sizeof(arr) / sizeof(arr[0]); printf("Minimum number of multiplications required for the matrices multiplication is %d ", MatrixChainMultuplication(arr, size)); getchar(); return 0; } Minimum number of multiplications required for the matrices multiplication is 444
[ { "code": null, "e": 1299, "s": 1062, "text": "In this problem, we are given a sequence( array) of metrics. our task is to create a C program for Matrix chain multiplication. We need to find a way to multiply these matrixes so that, the minimum number of multiplications is required." }, { "code": null, "e": 1413, "s": 1299, "text": "The array of matrices will contain n elements, which define the dimensions of the matrices as, arr[i-1] X arr[i]." }, { "code": null, "e": 1462, "s": 1413, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1485, "s": 1462, "text": "array[] = {3, 4, 5, 6}" }, { "code": null, "e": 1521, "s": 1485, "text": "the matrices will be of the order −" }, { "code": null, "e": 1556, "s": 1521, "text": "Mat1 = 3X4, Mat2 = 4X5, Mat3 = 5X6" }, { "code": null, "e": 1617, "s": 1556, "text": "For these three matrices, there can be two ways to multiply," }, { "code": null, "e": 1726, "s": 1617, "text": "mat1*(mat2*mat3) -> (3*4*6) + (4*5*6) = 72 + 120 = 192\n(mat1*mat2)*mat3 -> (3*4*5) + (3*5*6) = 60 + 90 = 150" }, { "code": null, "e": 1805, "s": 1726, "text": "The minimum number of mulitplications will be 150 in case of (mat1*mat2)*mat3." }, { "code": null, "e": 1969, "s": 1805, "text": "The problem can be solved using dynamic programming as it posses both the properties i.e. optimal substructure and overlapping substructure in dynamic programming." }, { "code": null, "e": 2048, "s": 1969, "text": "So here is C Program for Matrix Chain Multiplication using dynamic programming" }, { "code": null, "e": 2059, "s": 2048, "text": " Live Demo" }, { "code": null, "e": 2851, "s": 2059, "text": "#include <stdio.h>\nint MatrixChainMultuplication(int arr[], int n) {\n int minMul[n][n];\n int j, q;\n for (int i = 1; i < n; i++)\n minMul[i][i] = 0;\n for (int L = 2; L < n; L++) {\n for (int i = 1; i < n - L + 1; i++) {\n j = i + L - 1;\n minMul[i][j] = 99999999;\n for (int k = i; k <= j - 1; k++) {\n q = minMul[i][k] + minMul[k + 1][j] + arr[i - 1] * arr[k] * arr[j];\n if (q < minMul[i][j])\n minMul[i][j] = q;\n }\n }\n }\n return minMul[1][n - 1];\n}\nint main(){\n int arr[] = {3, 4, 5, 6, 7, 8};\n int size = sizeof(arr) / sizeof(arr[0]);\n printf(\"Minimum number of multiplications required for the matrices multiplication is %d \", MatrixChainMultuplication(arr, size));\n getchar();\n return 0;\n}" }, { "code": null, "e": 2933, "s": 2851, "text": "Minimum number of multiplications required for the matrices multiplication is 444" } ]
SQLite - ALIAS Syntax
You can rename a table or a column temporarily by giving another name, which is known as ALIAS. The use of table aliases means to rename a table in a particular SQLite statement. Renaming is a temporary change and the actual table name does not change in the database. The column aliases are used to rename a table's columns for the purpose of a particular SQLite query. Following is the basic syntax of table alias. SELECT column1, column2.... FROM table_name AS alias_name WHERE [condition]; Following is the basic syntax of column alias. SELECT column_name AS alias_name FROM table_name WHERE [condition]; Consider the following two tables, (a) COMPANY table is as follows − sqlite> select * from COMPANY; ID NAME AGE ADDRESS SALARY ---------- -------------------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 (b) Another table is DEPARTMENT as follows − ID DEPT EMP_ID ---------- -------------------- ---------- 1 IT Billing 1 2 Engineering 2 3 Finance 7 4 Engineering 3 5 Finance 4 6 Engineering 5 7 Finance 6 Now, following is the usage of TABLE ALIAS where we use C and D as aliases for COMPANY and DEPARTMENT tables respectively − sqlite> SELECT C.ID, C.NAME, C.AGE, D.DEPT FROM COMPANY AS C, DEPARTMENT AS D WHERE C.ID = D.EMP_ID; The above SQLite statement will produce the following result − ID NAME AGE DEPT ---------- ---------- ---------- ---------- 1 Paul 32 IT Billing 2 Allen 25 Engineering 3 Teddy 23 Engineering 4 Mark 25 Finance 5 David 27 Engineering 6 Kim 22 Finance 7 James 24 Finance Consider an example for the usage of COLUMN ALIAS where COMPANY_ID is an alias of ID column and COMPANY_NAME is an alias of name column. sqlite> SELECT C.ID AS COMPANY_ID, C.NAME AS COMPANY_NAME, C.AGE, D.DEPT FROM COMPANY AS C, DEPARTMENT AS D WHERE C.ID = D.EMP_ID; The above SQLite statement will produce the following result − COMPANY_ID COMPANY_NAME AGE DEPT ---------- ------------ ---------- ---------- 1 Paul 32 IT Billing 2 Allen 25 Engineering 3 Teddy 23 Engineering 4 Mark 25 Finance 5 David 27 Engineering 6 Kim 22 Finance 7 James 24 Finance 25 Lectures 4.5 hours Sandip Bhattacharya 17 Lectures 1 hours Laurence Svekis 5 Lectures 51 mins Vinay Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2907, "s": 2638, "text": "You can rename a table or a column temporarily by giving another name, which is known as ALIAS. The use of table aliases means to rename a table in a particular SQLite statement. Renaming is a temporary change and the actual table name does not change in the database." }, { "code": null, "e": 3009, "s": 2907, "text": "The column aliases are used to rename a table's columns for the purpose of a particular SQLite query." }, { "code": null, "e": 3055, "s": 3009, "text": "Following is the basic syntax of table alias." }, { "code": null, "e": 3133, "s": 3055, "text": "SELECT column1, column2....\nFROM table_name AS alias_name\nWHERE [condition];\n" }, { "code": null, "e": 3180, "s": 3133, "text": "Following is the basic syntax of column alias." }, { "code": null, "e": 3249, "s": 3180, "text": "SELECT column_name AS alias_name\nFROM table_name\nWHERE [condition];\n" }, { "code": null, "e": 3318, "s": 3249, "text": "Consider the following two tables, (a) COMPANY table is as follows −" }, { "code": null, "e": 3945, "s": 3318, "text": "sqlite> select * from COMPANY;\nID NAME AGE ADDRESS SALARY\n---------- -------------------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0" }, { "code": null, "e": 3990, "s": 3945, "text": "(b) Another table is DEPARTMENT as follows −" }, { "code": null, "e": 4328, "s": 3990, "text": "ID DEPT EMP_ID\n---------- -------------------- ----------\n1 IT Billing 1\n2 Engineering 2\n3 Finance 7\n4 Engineering 3\n5 Finance 4\n6 Engineering 5\n7 Finance 6" }, { "code": null, "e": 4452, "s": 4328, "text": "Now, following is the usage of TABLE ALIAS where we use C and D as aliases for COMPANY and DEPARTMENT tables respectively −" }, { "code": null, "e": 4570, "s": 4452, "text": "sqlite> SELECT C.ID, C.NAME, C.AGE, D.DEPT\n FROM COMPANY AS C, DEPARTMENT AS D\n WHERE C.ID = D.EMP_ID;" }, { "code": null, "e": 4633, "s": 4570, "text": "The above SQLite statement will produce the following result −" }, { "code": null, "e": 5045, "s": 4633, "text": "ID NAME AGE DEPT\n---------- ---------- ---------- ----------\n1 Paul 32 IT Billing\n2 Allen 25 Engineering\n3 Teddy 23 Engineering\n4 Mark 25 Finance\n5 David 27 Engineering\n6 Kim 22 Finance\n7 James 24 Finance\n" }, { "code": null, "e": 5182, "s": 5045, "text": "Consider an example for the usage of COLUMN ALIAS where COMPANY_ID is an alias of ID column and COMPANY_NAME is an alias of name column." }, { "code": null, "e": 5330, "s": 5182, "text": "sqlite> SELECT C.ID AS COMPANY_ID, C.NAME AS COMPANY_NAME, C.AGE, D.DEPT\n FROM COMPANY AS C, DEPARTMENT AS D\n WHERE C.ID = D.EMP_ID;" }, { "code": null, "e": 5393, "s": 5330, "text": "The above SQLite statement will produce the following result −" }, { "code": null, "e": 5823, "s": 5393, "text": "COMPANY_ID COMPANY_NAME AGE DEPT\n---------- ------------ ---------- ----------\n1 Paul 32 IT Billing\n2 Allen 25 Engineering\n3 Teddy 23 Engineering\n4 Mark 25 Finance\n5 David 27 Engineering\n6 Kim 22 Finance\n7 James 24 Finance\n" }, { "code": null, "e": 5858, "s": 5823, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5879, "s": 5858, "text": " Sandip Bhattacharya" }, { "code": null, "e": 5912, "s": 5879, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 5929, "s": 5912, "text": " Laurence Svekis" }, { "code": null, "e": 5960, "s": 5929, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 5973, "s": 5960, "text": " Vinay Kumar" }, { "code": null, "e": 5980, "s": 5973, "text": " Print" }, { "code": null, "e": 5991, "s": 5980, "text": " Add Notes" } ]
Advanced Topics in Deep Convolutional Neural Networks | by Matthew Stewart, PhD Researcher | Towards Data Science
“If We Want Machines to Think, We Need to Teach Them to See” — Fei-Fei Li Throughout this article, I will discuss some of the more complex aspects of convolutional neural networks and how they related to specific tasks such as object detection and facial recognition. The topics that will be discussed in this tutorial are: CNN review Receptive Fields and Dilated Convolutions Saliency Maps Transposed Convolutions Classic Networks Residual networks Transfer Learning This article is a natural extension to my article titled: Simple Introductions to Neural Networks. I recommend looking at this before tackling the rest of this article if you are not well-versed in the idea and function of convolutional neural networks. Due to the excessive length of the original article, I have decided to leave out several topics related to object detection and facial recognition systems, as well as some of the more esoteric network architectures and practices currently being trialed in the research literature. I will likely discuss these in a future article related more specifically to the application of deep learning for computer vision. All related code can now be found at my GitHub repository: github.com In my original article, I discussed the motivation behind why fully connected networks are insufficient for the task of image analysis. The unique aspects of CNN’s are as follows: Fewer parameters (weights and biases) than a fully connected network. Invariant to object translation — they do not depend on where the feature occurs in the image. Can tolerate some distortion in the images. Capable of generalizing and learning features. Requires grid input. Convolutional layers are formed by filters, feature maps, and activation functions. These convolutional layers can be full, same or valid. We can determine the number of output layers of a given convolutional block if the number of layers in the input is known, ni, the number of filters in that stage, f, the size of the stride, s, and the pixel dimension of the image, p (assuming it is square). Pooling layers are used to reduce overfitting. Fully connected layers are used to mix spacial and channel features together. Each of the filter layers corresponds to the image after a feature map has been drawn across the image, which is how features are extracted. It is important to know the number of input and output layers as this determines the number of weights and biases that make up the parameters of the neural network. The more parameters in the network, the more parameters need to be trained which results in longer training time. Training time is very important for deep learning as it a limiting factor unless you have access to powerful computing resources such as a computing cluster. Below is an example network for which we will calculate the total number of parameters. In this network, we have 250 weights on the convolutional filter and 10 bias terms. We have no weights on the max-pooling layer. We have 13 × 13 × 10 = 1,690 output elements after the max-pooling layer. We have a 200 node fully connected layer, which results in a total of 1, 690 × 200 = 338, 000 weights and 200 bias terms in the fully connected layer. Thus, we have a total of 338,460 parameters to be trained in the network. We can see that the majority of the trained parameters occur at the fully connected output layer. Each CNN layer learns filters of increasing complexity. The first layers learn basic feature detection filters such as edges and corners. The middle layers learn filters that detect parts of objects — for faces, they might learn to respond to eyes and noses. The last layers have higher representations: they learn to recognize full objects, in different shapes and positions. For those of you who need a more visceral feel to understand the convolutional neural network before continuing, it may be helpful to look at this three-dimensional representation: scs.ryerson.ca In the next section, we will discuss the concept of receptive fields of a convolutional layer in more detail. The receptive field is defined as the region in the input space that a particular CNN’s feature is looking at (i.e. be affected by). Applying a convolution C with kernel size k = 3 × 3, padding size p = 1 × 1, and stride s = 2 × 2 on a 5 × 5 input map, we will get a 3 × 3 output feature map (green map). Applying the same convolution on top of the 3 × 3 feature map, we will get a 2 × 2 feature map (orange map). Let’s look at the receptive field again in one-dimension, with no padding, a stride of 1 and a kernel of size 3 × 1. We can skip some of these connections in order to create a dilated convolution, as shown below. This dilated convolution works in a similar way to a normal convolution, the major difference being that the receptive field no longer consists of contiguous pixels, but of individual pixels separated by other pixels. The way in which a dilated convolutional layer is applied to an image is shown in the figure below. The below figure shows dilated convolution on two-dimensional data. The red dots are the inputs to a filter which is 3 × 3, and the green area is the receptive field captured by each of these inputs. The receptive field is the implicit area captured on the initial input by each input (unit) to the next layer. The motivation behind using dilated convolutions are: The detection of fine details by processing inputs in higher resolutions. A broader view of the input to capture more contextual information. Faster run-time with fewer parameters In the next section, we will discuss using saliency maps to examine the performance of convolutional networks. Saliency maps are a useful technique that data scientists can use to examine convolutional networks. They can be used to study the activation patterns of neurons to see which particular sections of an image are important for a particular feature. Let’s imagine that you are given an image of a dog and asked to classify it. This is pretty simple for a human to do, however, a deep learning network might not be as smart as you, and might instead classify it as a cat or a lion. Why does it do this? The two main reasons why the network may misclassify the image: bias in training data no regularization We want to understand what made the network give a certain class as output — one way of doing this is to use saliency maps. Saliency maps are a way to measure the spatial support of a particular class in a given image. “Find me pixels responsible for the class C having score S(C) when the image I is passed through my network”. How do we do that? We differentiate! For any function f(x, y, z), we can find the impact of variables x, y, z on fat any specific point (x1, y1, z1) by finding its partial derivative with respect to these variables at that point. Similarly, to find the responsible pixels, we take the score function S, for class C and take the partial derivatives with respect to every pixel. This is fairly difficult to implement by yourself, but fortunately, auto-grad can do this! The procedure works as follows: Forward pass the image through the network.Calculate the scores for every class.Enforce derivative of score S at last layer for all classes except class C to be 0. For C, set it to 1.Backpropagate this derivative through the network.Render them and you have your saliency map. Forward pass the image through the network. Calculate the scores for every class. Enforce derivative of score S at last layer for all classes except class C to be 0. For C, set it to 1. Backpropagate this derivative through the network. Render them and you have your saliency map. Note: On step #2, instead of doing softmax, we turn it to binary classification and use the probabilities. Here are some examples of saliency maps. What do we do with color images? Take the saliency map for each channel and either take the max, average, or use all 3 channels. Two good papers outlining the functioning of saliency maps are: Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps Attention-based Extraction of Structured Information from Street View Imagery There is a GitHub repository associated with this article in which I show how to generate saliency maps (the repository can be found here). Here is a snippet of the code from the Jupyter notebook: from vis.visualization import visualize_saliencyfrom vis.utils import utilsfrom keras import activations# Utility to search for layer index by name. # Alternatively we can specify this as -1 since it corresponds to the last layer.layer_idx = utils.find_layer_idx(model, 'preds')plt.rcParams["figure.figsize"] = (5,5)from vis.visualization import visualize_camimport warningswarnings.filterwarnings('ignore')# This corresponds to the Dense linear layer.for class_idx in np.arange(10): indices = np.where(test_labels[:, class_idx] == 1.)[0] idx = indices[0] f, ax = plt.subplots(1, 4) ax[0].imshow(test_images[idx][..., 0]) for i, modifier in enumerate([None, 'guided', 'relu']): grads = visualize_cam(model, layer_idx, filter_indices=class_idx, seed_input=test_images[idx], backprop_modifier=modifier) if modifier is None: modifier = 'vanilla' ax[i+1].set_title(modifier) ax[i+1].imshow(grads, cmap='jet') This code results in the following saliency maps being generated (assuming that the relevant libraries vis.utils and vis.visualization are installed). Please see the notebook if you want a fuller walkthrough of the implementation. In the next section, we will discuss the idea of upsampling through the use of transposed convolutions. So far, the convolutions we have looked at either maintain the size of their input or make it smaller. We can use the same technique to make the input tensor larger. This process is called upsampling. When we do it inside of a convolution step, it is called transposed convolution or fractional striding. Note: Some authors call upsampling while convolving deconvolution, but that name is already taken by a different idea outlined in the following paper: https://arxiv.org/pdf/1311.2901.pdf To illustrate how the transposed convolution works, we will look at some illustrated examples of convolutions. The first is an example of a typical convolutional layer with no padding, acting on an image of size 5 × 5. After the convolution, we end up with a 3 × 3 image. Now we look at a convolutional layer with a padding of 1. The original image is 5 × 5, and the output image after the convolution is also 5 × 5. Now we look at a convolutional layer with a padding of 2. The original image is 3× 3, and the output image after the convolution is also 5 × 5. When used in Keras, such as in the development of a variational autoencoder, these are implemented using an upsampling layer. Hopefully, if you have seen this before, it now makes sense as to how these convolution layers are able to increase the size of the image through the use of transposed convolutions. In the next section, we will discuss the architectures of some of the classic networks. Each of these networks was revolutionary in some sense in forwarding the field of deep convolutional networks. In this section, I will go over some of the classic architectures of CNN’s. These networks were utilized in some of the seminal work done in the field of deep learning, and are often used for transfer learning purposes (this is a topic for a future article). The first piece of research proposing something similar to a Convolutional Neural Network was authored by Kunihiko Fukushima in 1980 and was called the NeoCognitron1, who was inspired by discoveries of the visual cortex of mammals. Fukushima applied the NeoCognitron to hand-written character recognition. By the end of the 1980’s, several papers were produced that considerably advanced the field. The idea of backpropagation was first published in French by Yann LeCun in 1985 (which was independently discovered by other researchers as well), followed shortly by TDNN by Waiber et al. in 1989 — the development of a convolutional-like network trained with backpropagation. One of the first applications was by LeCun et al. in 1989, using backpropagation applied to handwritten zip code recognition. The formulation of LeNet-5 is a bit outdated in comparison to current practices. This is one of the first neural architectures that was developed during the nascent phase of deep learning at the end of the 20th century. In November 1998, LeCun published one of his most recognized papers describing a “modern” CNN architecture for document recognition, called LeNet1. This was not his first iteration, this was, in fact, LeNet-5, but this paper is the commonly cited publication when talking about LeNet. It uses convolutional networks followed by pooling layers and finishes with fully connected layers. The network first starts with high dimensional features and reduces its size while increasing the number of channels. There are around 60,000 parameters in this network. The AlexNet architecture is one of the most important architectures in deep learning, with more than 25,000 citations — this is practically unheard of in research literature. Developed by Alex Krizhevsky, Ilya Sutskever, and Geoffrey Hinton at the University of Toronto in 2012, AlexNet destroyed the competition in the 2012 ImageNet Large Scale Visual Recognition Challenge (ILSVRC). The network was trained on the ImageNet dataset, a collection of 1.2 million high-resolution (227x227x3) images consisting of 1000 different classes, using data augmentation. The depth of the model was larger than any other network at the time, and was trained using GPU’s for 5–6 days. The network consists of 12 layers and utilized dropout and smart optimizer layers and was one of the first networks to implement the ReLU activation function, which is still widely used today. The network had more than 60 million parameters to optimize (~255 MB). This network almost single-handedly kickstarted the AI revolution by showing the impressive performance and potential benefits of CNN’s. The network won the ImageNet contest with a top-5 error of 15.3%, more than 10.8 percentage points lower than the next runner-up. We will be discussing the remaining networks that have won the ILSVRC, since most of these are the revolutionary networks at the forefront of research in deep learning. This network was introduced by Matthew Zeiler and Rob Fergus from New York University, which won ILSVRC 2013 with an 11.2% error rate. The network decreased the sizes of filters and was trained for 12 days. The paper presented a visualization technique named “deconvolutional network”, which helps to examine different feature activations and their relation to the input space. The VGG network was introduced by Simonyan and Zisserman (Oxford) in 2014. This network is revolutionary in its inherent simplicity and its structure. It consists of 16 or 19 layers (hence the name) with a total of 138 million parameters (522 MB) and uses 3x3 convolutional filters exclusively using same padding and a stride of 1, and 2x2 max-pooling layers with a stride of 2. The authors showed that two 3x3 filters have an effective receptive field of 5x5 and that as spatial size decreases, the depth increases. The network was trained for two to three weeks and is still used to this today — mainly for transfer learning. The network was originally developed for the ImageNet Challenge in 2014. ImageNet Challenge 2014; 16 or 19 layers 138 million parameters (522 MB). Convolutional layers use ‘same’ padding and stride s = 1. Max-pooling layers use a filter size f = 2 and stride s = 2. The GoogLeNet network was introduced by Szegedy et al. (Google) in 2014. The network was the winner of ILSVRC 2014, beating the VGG architecture. The network introduces the concept of the inception module — parallel convolutional layers with different filter sizes. The idea here is that we do not a priori know which filter size is best, so we just let the network decide. The inception network is formed by concatenating other inception modules. It includes several softmax output units to enforce regularization. This was a key idea which has been important in the development of future architectures. Another interesting feature is that there is no fully connected layer at the end, and this is instead replaced with an average-pooling layer. The removal of this fully connected layer results in a network with 12x fewer parameters than AlexNet, making it much faster to train. The first residual network was presented by He et al. (Microsoft) in 2015. This network won ILSVRC 2015 in multiple categories. The main idea behind this network is the residual block. The network allows for the development of extremely deep neural networks, which can contain 100 layers or more. This is revolutionary since up to this point, the development of deep neural networks was inhibited by the vanishing gradient problem, which occurs when propagating and multiplying small gradients across a large number of layers. The authors believe that it is easier to optimize residual mapping than an archetypal neural architecture. Furthermore, residual block can decide to “shut itself down” if needed. Let’s compare the network structure for a plain network and a residual network. The plain network structure is as follows: A residual network structure looks like this: The equations describing this network are: With this extra connection, gradients can travel backward more easily. It becomes a flexible block that can expand the capacity of the network, or simply transform into an identity function that would not affect training. A residual network stacks residual blocks sequentially. The idea is to allow the network to become deeper without increasing the training complexity. Residual networks implement blocks with convolutional layers that use ‘same’ padding option (even when max-pooling). This allows the block to learn the identity function. The designer may want to reduce the size of features and use ‘valid’ padding. — In such a case, the shortcut path can implement a new set of convolutional layers that reduces the size appropriately. These networks can get huge and extremely complicated, and their diagrams begin to look akin to those that describe the functioning of a power plant. Here is an example of such a network. Comparing the error values for the previous winners of ImageNet to those of the ResNet formulations, we can see a clear enhancement in the performance. Alexnet (2012) achieved a top-5 error of 15.3% (second place was 26.2%), followed by ZFNet (2013) achieved a top-5 error of 14.8% (visualization of features), followed by GoogLeNet (2014) with an error of 7.8%, and then ResNet (2015) which achieved accuracies below 5% for the first time. Initially proposed by Huang et al. in 2016 as a radical extension of the ResNet philosophy. Each block uses every previous feature map as input, effectively concatenating them. These connections mean that the network has L(L+1)/ 2 direct connections, where L is the number of layers in the network. One can think of the architecture as an unrolled recurrent neural network. Each layer adds k feature-maps of its own to this state. The growth rate regulates how much new information each layer contributes to the global state. The idea here is that we have all the previous information available at each point. Counter-intuitively, this architecture reduces the total number of parameters needed. The network works by allowing maximum information (and gradient) flow at each layer by connecting every layer directly with every other layer. In this way, DenseNets exploit the potential of the network through feature reuse, which means there is no need to learn redundant feature maps. DenseNet layers are relatively narrow (e.g. 12 filters), and they just add a small set of new feature-maps. The DenseNet architecture typically has superior performance to the ResNet architecture and can achieve the same or better accuracy with fewer parameters overall, and the networks are easier to train. The network formulation may be a bit confusing at first, but it is essentially a ResNet architecture the resolution blocks are replaced by dense blocks. The dense connections have a regularizing effect, which reduces overfitting on tasks with smaller training set sizes. It is important to note that DenseNets do not sum the output feature maps of the layer with the incoming feature maps, they, in fact, concatenate them: Dimensions of the feature maps remain constant within a block, but the number of filters changes between them, which is known as the growth rate, k. Below is the full architecture of a dense network. It is fairly involved when we look at the network in its full resolution, which is why it is typically easier to visualize in an abstracted form (like we did above). For more information on DenseNet, I recommend the following article. towardsdatascience.com As we can see, over the course of just a few years, we have gone from an error rate of around 15% on the ImageNet dataset (which, if you remember, consists of 1.2 million images) to an error rate of around 3–4%. Nowadays the most state-of-the-art networks are able to get below 3% pretty consistently. There is still quite a long way to go before we are able to obtain perfect scores for these networks, but the rate of progress is quite staggering in this past decade, and it should be apparent from this why we are currently undergoing a deep learning revolution — we have gone from the stage where humans have superior visual recognition, to a stage where these networks have superior vision (a human cannot achieve 3% on the ImageNet dataset). This has fueled the transition of machine learning algorithms into various commercial fields that require heavy use of image analysis, such as medical imaging (examining brain scans, x-rays, mammography scans) and self-driving cars (computer vision). Image analysis is easily extended to video since this is just a rapid succession of multiple image frames every second — although this requires more computing power. Transfer learning is an important topic, and it is definitely worthy of having an article all to itself. However, for now, I will outline the basic idea behind transfer learning so that the reader is able to do more research on it if they are interested. How do you make an image classifier that can be trained in a few hours (minutes) on a CPU? Normally, image classification models can take hours, days, or even weeks to train, especially if they are trained on exceptionally large networks and datasets. However, we know that companies such as Google and Microsoft have dedicated teams of data scientists that have spent years developing exceptional networks for the purpose of image classification — why not just use these networks as a starting point for your own image classification projects? This is the idea behind transfer learning, to use pre-trained models, i.e. models with known weights, in order to apply them to a different machine learning problem. Obviously, just purely transferring the model will not be helpful, you must still train the network on your new data, but it is common to freeze the weights of the former layers as these are more generalized features that will likely be unchanged during training. You can think of this as an intelligent way of generating a pre-initialized network, as opposed to having a randomly initialized network (the default case when training a network in Keras). Typically, smaller learning rates are used in transfer learning than in typical network training, as we are essentially tuning the network. If large learning rates are used and the early layers in the network are not frozen, transfer learning may not provide any benefit. Often, it is only the last layer or the last couple of layers that is trained in a transfer learning problem. Transfer learning works best for problems that are fairly general and there are networks freely available online (such as image analysis) and when the user has a relatively small dataset available such that it is insufficient to train a neural network — this is a fairly common problem. To summarize the main idea: earlier layers of a network learn low-level features, which can be adapted to new domains by changing weights at later and fully-connected layers. An example of this would be to use ImageNet trained with any sophisticated huge network, and then to retrain the network on a few thousand hotdog images and you get. The steps involved in transfer learning are as follows: Get existing network weightsUnfreeze the “head” fully connected layers and train on your new imagesUnfreeze the latest convolutional layers and train at a very low learning rate starting with the weights from the previously trained weights. This will change the latest layer convolutional weights without triggering large gradient updates which would have occurred had we not done #2. Get existing network weights Unfreeze the “head” fully connected layers and train on your new images Unfreeze the latest convolutional layers and train at a very low learning rate starting with the weights from the previously trained weights. This will change the latest layer convolutional weights without triggering large gradient updates which would have occurred had we not done #2. For more information, there are several other Medium articles I recommend: medium.com Congratulations on making it to the end of this article! This was a long article that touched on multiple facets of deep learning. The reader should now be fairly well equipped to venture into deep convolutional learning and computer vision literature. I encourage the reader to do more individual research on the topics that I have discussed here so that they can deepen their knowledge. I have added links to some further reading in the next section, as well as some of the references to research articles that I borrowed images from during this article. Thanks for reading and happy deep learning! MobileNetV2 (https://arxiv.org/abs/1801.04381) Inception-Resnet, v1 and v2 (https://arxiv.org/abs/1602.07261) Wide-Resnet (https://arxiv.org/abs/1605.07146) Xception (https://arxiv.org/abs/1610.02357) ResNeXt (https://arxiv.org/pdf/1611.05431) ShuffleNet, v1 and v2 (https://arxiv.org/abs/1707.01083) Squeeze and Excitation Nets (https://arxiv.org/abs/1709.01507) Original DenseNet paper (https://arxiv.org/pdf/1608.06993v3.pdf) DenseNet Semantic Segmentation (https://arxiv.org/pdf/1611.09326v2.pdf) DenseNet for Optical flow (https://arxiv.org/pdf/1707.06316v1.pdf) Yann LeCun, Leon Bottou, Yoshua Bengio, and Patrick Haffner, “Gradient-based learning applied to document recognition,” Proceedings of the IEEE, vol. 86, no. 11, pp. 2278–2324, 1998. Alex Krizhevsky, Ilya Sutskever, and Geoffrey E Hinton, “Imagenet classification with deep convolutional neural networks,” in Advances in neural information processing systems, pp. 1097–1105, 2012 Karen Simonyan and Andrew Zisserman, “Very deep convolutional networks for large-scale image recognition,” 2014. Min Lin, Qiang Chen, and Shuicheng Yan, “Network in network,” 2013. Christian Szegedy, Wei Liu, Yangqing Jia, Pierre Sermanet, Scott Reed, Dragomir Anguelov, Dumitru Erhan, Vincent Vanhoucke, and Andrew Rabinovich, “Going deeper with convolutions,” in Proceedings of the IEEE conference on computer vision and pattern recognition, 2015, pp. 1–9. Schroff, Florian, Dmitry Kalenichenko, and James Philbin. ”Facenet: A unified embedding for face recognition and clustering.” In Proceedings of the IEEE conference on computer vision and pattern recognition, pp. 815–823. 2015 Long, J., Shelhamer, E., & Darrell, T. (2014). Fully Convolutional Networks for Semantic Segmentation. Retrieved from http://arxiv.org/abs/1411.4038v1 Chen, L.-C., Papandreou, G., Kokkinos, I., Murphy, K., & Yuille, A. L. (2014). Semantic Image Segmentation with Deep Convolutional Nets and Fully Connected CRFs. Iclr, 1–14. Retrieved from http://arxiv.org/abs/1412.7062 Yu, F., & Koltun, V. (2016). Multi-Scale Context Aggregation by Dilated Convolutions. Iclr, 1–9. http://doi.org/10.16373/j.cnki.ahr.150049 Oord, A. van den, Dieleman, S., Zen, H., Simonyan, K., Vinyals, O., Graves, A., ... Kavukcuoglu, K. (2016). WaveNet: A Generative Model for Raw Audio, 1–15. Retrieved from http://arxiv.org/abs/1609.03499 Kalchbrenner, N., Espeholt, L., Simonyan, K., Oord, A. van den, Graves, A., & Kavukcuoglu, K. (2016). Neural Machine Translation in Linear Time. Arxiv, 1–11. Retrieved from http://arxiv.org/abs/1610.10099
[ { "code": null, "e": 245, "s": 171, "text": "“If We Want Machines to Think, We Need to Teach Them to See” — Fei-Fei Li" }, { "code": null, "e": 439, "s": 245, "text": "Throughout this article, I will discuss some of the more complex aspects of convolutional neural networks and how they related to specific tasks such as object detection and facial recognition." }, { "code": null, "e": 495, "s": 439, "text": "The topics that will be discussed in this tutorial are:" }, { "code": null, "e": 506, "s": 495, "text": "CNN review" }, { "code": null, "e": 548, "s": 506, "text": "Receptive Fields and Dilated Convolutions" }, { "code": null, "e": 562, "s": 548, "text": "Saliency Maps" }, { "code": null, "e": 586, "s": 562, "text": "Transposed Convolutions" }, { "code": null, "e": 603, "s": 586, "text": "Classic Networks" }, { "code": null, "e": 621, "s": 603, "text": "Residual networks" }, { "code": null, "e": 639, "s": 621, "text": "Transfer Learning" }, { "code": null, "e": 893, "s": 639, "text": "This article is a natural extension to my article titled: Simple Introductions to Neural Networks. I recommend looking at this before tackling the rest of this article if you are not well-versed in the idea and function of convolutional neural networks." }, { "code": null, "e": 1305, "s": 893, "text": "Due to the excessive length of the original article, I have decided to leave out several topics related to object detection and facial recognition systems, as well as some of the more esoteric network architectures and practices currently being trialed in the research literature. I will likely discuss these in a future article related more specifically to the application of deep learning for computer vision." }, { "code": null, "e": 1364, "s": 1305, "text": "All related code can now be found at my GitHub repository:" }, { "code": null, "e": 1375, "s": 1364, "text": "github.com" }, { "code": null, "e": 1555, "s": 1375, "text": "In my original article, I discussed the motivation behind why fully connected networks are insufficient for the task of image analysis. The unique aspects of CNN’s are as follows:" }, { "code": null, "e": 1625, "s": 1555, "text": "Fewer parameters (weights and biases) than a fully connected network." }, { "code": null, "e": 1720, "s": 1625, "text": "Invariant to object translation — they do not depend on where the feature occurs in the image." }, { "code": null, "e": 1764, "s": 1720, "text": "Can tolerate some distortion in the images." }, { "code": null, "e": 1811, "s": 1764, "text": "Capable of generalizing and learning features." }, { "code": null, "e": 1832, "s": 1811, "text": "Requires grid input." }, { "code": null, "e": 1971, "s": 1832, "text": "Convolutional layers are formed by filters, feature maps, and activation functions. These convolutional layers can be full, same or valid." }, { "code": null, "e": 2230, "s": 1971, "text": "We can determine the number of output layers of a given convolutional block if the number of layers in the input is known, ni, the number of filters in that stage, f, the size of the stride, s, and the pixel dimension of the image, p (assuming it is square)." }, { "code": null, "e": 2496, "s": 2230, "text": "Pooling layers are used to reduce overfitting. Fully connected layers are used to mix spacial and channel features together. Each of the filter layers corresponds to the image after a feature map has been drawn across the image, which is how features are extracted." }, { "code": null, "e": 2933, "s": 2496, "text": "It is important to know the number of input and output layers as this determines the number of weights and biases that make up the parameters of the neural network. The more parameters in the network, the more parameters need to be trained which results in longer training time. Training time is very important for deep learning as it a limiting factor unless you have access to powerful computing resources such as a computing cluster." }, { "code": null, "e": 3021, "s": 2933, "text": "Below is an example network for which we will calculate the total number of parameters." }, { "code": null, "e": 3547, "s": 3021, "text": "In this network, we have 250 weights on the convolutional filter and 10 bias terms. We have no weights on the max-pooling layer. We have 13 × 13 × 10 = 1,690 output elements after the max-pooling layer. We have a 200 node fully connected layer, which results in a total of 1, 690 × 200 = 338, 000 weights and 200 bias terms in the fully connected layer. Thus, we have a total of 338,460 parameters to be trained in the network. We can see that the majority of the trained parameters occur at the fully connected output layer." }, { "code": null, "e": 3924, "s": 3547, "text": "Each CNN layer learns filters of increasing complexity. The first layers learn basic feature detection filters such as edges and corners. The middle layers learn filters that detect parts of objects — for faces, they might learn to respond to eyes and noses. The last layers have higher representations: they learn to recognize full objects, in different shapes and positions." }, { "code": null, "e": 4105, "s": 3924, "text": "For those of you who need a more visceral feel to understand the convolutional neural network before continuing, it may be helpful to look at this three-dimensional representation:" }, { "code": null, "e": 4120, "s": 4105, "text": "scs.ryerson.ca" }, { "code": null, "e": 4230, "s": 4120, "text": "In the next section, we will discuss the concept of receptive fields of a convolutional layer in more detail." }, { "code": null, "e": 4535, "s": 4230, "text": "The receptive field is defined as the region in the input space that a particular CNN’s feature is looking at (i.e. be affected by). Applying a convolution C with kernel size k = 3 × 3, padding size p = 1 × 1, and stride s = 2 × 2 on a 5 × 5 input map, we will get a 3 × 3 output feature map (green map)." }, { "code": null, "e": 4644, "s": 4535, "text": "Applying the same convolution on top of the 3 × 3 feature map, we will get a 2 × 2 feature map (orange map)." }, { "code": null, "e": 4761, "s": 4644, "text": "Let’s look at the receptive field again in one-dimension, with no padding, a stride of 1 and a kernel of size 3 × 1." }, { "code": null, "e": 4857, "s": 4761, "text": "We can skip some of these connections in order to create a dilated convolution, as shown below." }, { "code": null, "e": 5175, "s": 4857, "text": "This dilated convolution works in a similar way to a normal convolution, the major difference being that the receptive field no longer consists of contiguous pixels, but of individual pixels separated by other pixels. The way in which a dilated convolutional layer is applied to an image is shown in the figure below." }, { "code": null, "e": 5486, "s": 5175, "text": "The below figure shows dilated convolution on two-dimensional data. The red dots are the inputs to a filter which is 3 × 3, and the green area is the receptive field captured by each of these inputs. The receptive field is the implicit area captured on the initial input by each input (unit) to the next layer." }, { "code": null, "e": 5540, "s": 5486, "text": "The motivation behind using dilated convolutions are:" }, { "code": null, "e": 5614, "s": 5540, "text": "The detection of fine details by processing inputs in higher resolutions." }, { "code": null, "e": 5682, "s": 5614, "text": "A broader view of the input to capture more contextual information." }, { "code": null, "e": 5720, "s": 5682, "text": "Faster run-time with fewer parameters" }, { "code": null, "e": 5831, "s": 5720, "text": "In the next section, we will discuss using saliency maps to examine the performance of convolutional networks." }, { "code": null, "e": 6078, "s": 5831, "text": "Saliency maps are a useful technique that data scientists can use to examine convolutional networks. They can be used to study the activation patterns of neurons to see which particular sections of an image are important for a particular feature." }, { "code": null, "e": 6330, "s": 6078, "text": "Let’s imagine that you are given an image of a dog and asked to classify it. This is pretty simple for a human to do, however, a deep learning network might not be as smart as you, and might instead classify it as a cat or a lion. Why does it do this?" }, { "code": null, "e": 6394, "s": 6330, "text": "The two main reasons why the network may misclassify the image:" }, { "code": null, "e": 6416, "s": 6394, "text": "bias in training data" }, { "code": null, "e": 6434, "s": 6416, "text": "no regularization" }, { "code": null, "e": 6653, "s": 6434, "text": "We want to understand what made the network give a certain class as output — one way of doing this is to use saliency maps. Saliency maps are a way to measure the spatial support of a particular class in a given image." }, { "code": null, "e": 6763, "s": 6653, "text": "“Find me pixels responsible for the class C having score S(C) when the image I is passed through my network”." }, { "code": null, "e": 7140, "s": 6763, "text": "How do we do that? We differentiate! For any function f(x, y, z), we can find the impact of variables x, y, z on fat any specific point (x1, y1, z1) by finding its partial derivative with respect to these variables at that point. Similarly, to find the responsible pixels, we take the score function S, for class C and take the partial derivatives with respect to every pixel." }, { "code": null, "e": 7263, "s": 7140, "text": "This is fairly difficult to implement by yourself, but fortunately, auto-grad can do this! The procedure works as follows:" }, { "code": null, "e": 7540, "s": 7263, "text": "Forward pass the image through the network.Calculate the scores for every class.Enforce derivative of score S at last layer for all classes except class C to be 0. For C, set it to 1.Backpropagate this derivative through the network.Render them and you have your saliency map." }, { "code": null, "e": 7584, "s": 7540, "text": "Forward pass the image through the network." }, { "code": null, "e": 7622, "s": 7584, "text": "Calculate the scores for every class." }, { "code": null, "e": 7726, "s": 7622, "text": "Enforce derivative of score S at last layer for all classes except class C to be 0. For C, set it to 1." }, { "code": null, "e": 7777, "s": 7726, "text": "Backpropagate this derivative through the network." }, { "code": null, "e": 7821, "s": 7777, "text": "Render them and you have your saliency map." }, { "code": null, "e": 7928, "s": 7821, "text": "Note: On step #2, instead of doing softmax, we turn it to binary classification and use the probabilities." }, { "code": null, "e": 7969, "s": 7928, "text": "Here are some examples of saliency maps." }, { "code": null, "e": 8098, "s": 7969, "text": "What do we do with color images? Take the saliency map for each channel and either take the max, average, or use all 3 channels." }, { "code": null, "e": 8162, "s": 8098, "text": "Two good papers outlining the functioning of saliency maps are:" }, { "code": null, "e": 8256, "s": 8162, "text": "Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps" }, { "code": null, "e": 8334, "s": 8256, "text": "Attention-based Extraction of Structured Information from Street View Imagery" }, { "code": null, "e": 8531, "s": 8334, "text": "There is a GitHub repository associated with this article in which I show how to generate saliency maps (the repository can be found here). Here is a snippet of the code from the Jupyter notebook:" }, { "code": null, "e": 9540, "s": 8531, "text": "from vis.visualization import visualize_saliencyfrom vis.utils import utilsfrom keras import activations# Utility to search for layer index by name. # Alternatively we can specify this as -1 since it corresponds to the last layer.layer_idx = utils.find_layer_idx(model, 'preds')plt.rcParams[\"figure.figsize\"] = (5,5)from vis.visualization import visualize_camimport warningswarnings.filterwarnings('ignore')# This corresponds to the Dense linear layer.for class_idx in np.arange(10): indices = np.where(test_labels[:, class_idx] == 1.)[0] idx = indices[0] f, ax = plt.subplots(1, 4) ax[0].imshow(test_images[idx][..., 0]) for i, modifier in enumerate([None, 'guided', 'relu']): grads = visualize_cam(model, layer_idx, filter_indices=class_idx, seed_input=test_images[idx], backprop_modifier=modifier) if modifier is None: modifier = 'vanilla' ax[i+1].set_title(modifier) ax[i+1].imshow(grads, cmap='jet')" }, { "code": null, "e": 9771, "s": 9540, "text": "This code results in the following saliency maps being generated (assuming that the relevant libraries vis.utils and vis.visualization are installed). Please see the notebook if you want a fuller walkthrough of the implementation." }, { "code": null, "e": 9875, "s": 9771, "text": "In the next section, we will discuss the idea of upsampling through the use of transposed convolutions." }, { "code": null, "e": 10180, "s": 9875, "text": "So far, the convolutions we have looked at either maintain the size of their input or make it smaller. We can use the same technique to make the input tensor larger. This process is called upsampling. When we do it inside of a convolution step, it is called transposed convolution or fractional striding." }, { "code": null, "e": 10331, "s": 10180, "text": "Note: Some authors call upsampling while convolving deconvolution, but that name is already taken by a different idea outlined in the following paper:" }, { "code": null, "e": 10367, "s": 10331, "text": "https://arxiv.org/pdf/1311.2901.pdf" }, { "code": null, "e": 10478, "s": 10367, "text": "To illustrate how the transposed convolution works, we will look at some illustrated examples of convolutions." }, { "code": null, "e": 10639, "s": 10478, "text": "The first is an example of a typical convolutional layer with no padding, acting on an image of size 5 × 5. After the convolution, we end up with a 3 × 3 image." }, { "code": null, "e": 10784, "s": 10639, "text": "Now we look at a convolutional layer with a padding of 1. The original image is 5 × 5, and the output image after the convolution is also 5 × 5." }, { "code": null, "e": 10928, "s": 10784, "text": "Now we look at a convolutional layer with a padding of 2. The original image is 3× 3, and the output image after the convolution is also 5 × 5." }, { "code": null, "e": 11236, "s": 10928, "text": "When used in Keras, such as in the development of a variational autoencoder, these are implemented using an upsampling layer. Hopefully, if you have seen this before, it now makes sense as to how these convolution layers are able to increase the size of the image through the use of transposed convolutions." }, { "code": null, "e": 11435, "s": 11236, "text": "In the next section, we will discuss the architectures of some of the classic networks. Each of these networks was revolutionary in some sense in forwarding the field of deep convolutional networks." }, { "code": null, "e": 11694, "s": 11435, "text": "In this section, I will go over some of the classic architectures of CNN’s. These networks were utilized in some of the seminal work done in the field of deep learning, and are often used for transfer learning purposes (this is a topic for a future article)." }, { "code": null, "e": 12000, "s": 11694, "text": "The first piece of research proposing something similar to a Convolutional Neural Network was authored by Kunihiko Fukushima in 1980 and was called the NeoCognitron1, who was inspired by discoveries of the visual cortex of mammals. Fukushima applied the NeoCognitron to hand-written character recognition." }, { "code": null, "e": 12496, "s": 12000, "text": "By the end of the 1980’s, several papers were produced that considerably advanced the field. The idea of backpropagation was first published in French by Yann LeCun in 1985 (which was independently discovered by other researchers as well), followed shortly by TDNN by Waiber et al. in 1989 — the development of a convolutional-like network trained with backpropagation. One of the first applications was by LeCun et al. in 1989, using backpropagation applied to handwritten zip code recognition." }, { "code": null, "e": 12716, "s": 12496, "text": "The formulation of LeNet-5 is a bit outdated in comparison to current practices. This is one of the first neural architectures that was developed during the nascent phase of deep learning at the end of the 20th century." }, { "code": null, "e": 13001, "s": 12716, "text": "In November 1998, LeCun published one of his most recognized papers describing a “modern” CNN architecture for document recognition, called LeNet1. This was not his first iteration, this was, in fact, LeNet-5, but this paper is the commonly cited publication when talking about LeNet." }, { "code": null, "e": 13271, "s": 13001, "text": "It uses convolutional networks followed by pooling layers and finishes with fully connected layers. The network first starts with high dimensional features and reduces its size while increasing the number of channels. There are around 60,000 parameters in this network." }, { "code": null, "e": 13656, "s": 13271, "text": "The AlexNet architecture is one of the most important architectures in deep learning, with more than 25,000 citations — this is practically unheard of in research literature. Developed by Alex Krizhevsky, Ilya Sutskever, and Geoffrey Hinton at the University of Toronto in 2012, AlexNet destroyed the competition in the 2012 ImageNet Large Scale Visual Recognition Challenge (ILSVRC)." }, { "code": null, "e": 14207, "s": 13656, "text": "The network was trained on the ImageNet dataset, a collection of 1.2 million high-resolution (227x227x3) images consisting of 1000 different classes, using data augmentation. The depth of the model was larger than any other network at the time, and was trained using GPU’s for 5–6 days. The network consists of 12 layers and utilized dropout and smart optimizer layers and was one of the first networks to implement the ReLU activation function, which is still widely used today. The network had more than 60 million parameters to optimize (~255 MB)." }, { "code": null, "e": 14474, "s": 14207, "text": "This network almost single-handedly kickstarted the AI revolution by showing the impressive performance and potential benefits of CNN’s. The network won the ImageNet contest with a top-5 error of 15.3%, more than 10.8 percentage points lower than the next runner-up." }, { "code": null, "e": 14643, "s": 14474, "text": "We will be discussing the remaining networks that have won the ILSVRC, since most of these are the revolutionary networks at the forefront of research in deep learning." }, { "code": null, "e": 14850, "s": 14643, "text": "This network was introduced by Matthew Zeiler and Rob Fergus from New York University, which won ILSVRC 2013 with an 11.2% error rate. The network decreased the sizes of filters and was trained for 12 days." }, { "code": null, "e": 15021, "s": 14850, "text": "The paper presented a visualization technique named “deconvolutional network”, which helps to examine different feature activations and their relation to the input space." }, { "code": null, "e": 15400, "s": 15021, "text": "The VGG network was introduced by Simonyan and Zisserman (Oxford) in 2014. This network is revolutionary in its inherent simplicity and its structure. It consists of 16 or 19 layers (hence the name) with a total of 138 million parameters (522 MB) and uses 3x3 convolutional filters exclusively using same padding and a stride of 1, and 2x2 max-pooling layers with a stride of 2." }, { "code": null, "e": 15722, "s": 15400, "text": "The authors showed that two 3x3 filters have an effective receptive field of 5x5 and that as spatial size decreases, the depth increases. The network was trained for two to three weeks and is still used to this today — mainly for transfer learning. The network was originally developed for the ImageNet Challenge in 2014." }, { "code": null, "e": 15763, "s": 15722, "text": "ImageNet Challenge 2014; 16 or 19 layers" }, { "code": null, "e": 15796, "s": 15763, "text": "138 million parameters (522 MB)." }, { "code": null, "e": 15854, "s": 15796, "text": "Convolutional layers use ‘same’ padding and stride s = 1." }, { "code": null, "e": 15915, "s": 15854, "text": "Max-pooling layers use a filter size f = 2 and stride s = 2." }, { "code": null, "e": 16181, "s": 15915, "text": "The GoogLeNet network was introduced by Szegedy et al. (Google) in 2014. The network was the winner of ILSVRC 2014, beating the VGG architecture. The network introduces the concept of the inception module — parallel convolutional layers with different filter sizes." }, { "code": null, "e": 16520, "s": 16181, "text": "The idea here is that we do not a priori know which filter size is best, so we just let the network decide. The inception network is formed by concatenating other inception modules. It includes several softmax output units to enforce regularization. This was a key idea which has been important in the development of future architectures." }, { "code": null, "e": 16797, "s": 16520, "text": "Another interesting feature is that there is no fully connected layer at the end, and this is instead replaced with an average-pooling layer. The removal of this fully connected layer results in a network with 12x fewer parameters than AlexNet, making it much faster to train." }, { "code": null, "e": 17094, "s": 16797, "text": "The first residual network was presented by He et al. (Microsoft) in 2015. This network won ILSVRC 2015 in multiple categories. The main idea behind this network is the residual block. The network allows for the development of extremely deep neural networks, which can contain 100 layers or more." }, { "code": null, "e": 17324, "s": 17094, "text": "This is revolutionary since up to this point, the development of deep neural networks was inhibited by the vanishing gradient problem, which occurs when propagating and multiplying small gradients across a large number of layers." }, { "code": null, "e": 17626, "s": 17324, "text": "The authors believe that it is easier to optimize residual mapping than an archetypal neural architecture. Furthermore, residual block can decide to “shut itself down” if needed. Let’s compare the network structure for a plain network and a residual network. The plain network structure is as follows:" }, { "code": null, "e": 17672, "s": 17626, "text": "A residual network structure looks like this:" }, { "code": null, "e": 17715, "s": 17672, "text": "The equations describing this network are:" }, { "code": null, "e": 17937, "s": 17715, "text": "With this extra connection, gradients can travel backward more easily. It becomes a flexible block that can expand the capacity of the network, or simply transform into an identity function that would not affect training." }, { "code": null, "e": 17993, "s": 17937, "text": "A residual network stacks residual blocks sequentially." }, { "code": null, "e": 18087, "s": 17993, "text": "The idea is to allow the network to become deeper without increasing the training complexity." }, { "code": null, "e": 18258, "s": 18087, "text": "Residual networks implement blocks with convolutional layers that use ‘same’ padding option (even when max-pooling). This allows the block to learn the identity function." }, { "code": null, "e": 18457, "s": 18258, "text": "The designer may want to reduce the size of features and use ‘valid’ padding. — In such a case, the shortcut path can implement a new set of convolutional layers that reduces the size appropriately." }, { "code": null, "e": 18645, "s": 18457, "text": "These networks can get huge and extremely complicated, and their diagrams begin to look akin to those that describe the functioning of a power plant. Here is an example of such a network." }, { "code": null, "e": 19086, "s": 18645, "text": "Comparing the error values for the previous winners of ImageNet to those of the ResNet formulations, we can see a clear enhancement in the performance. Alexnet (2012) achieved a top-5 error of 15.3% (second place was 26.2%), followed by ZFNet (2013) achieved a top-5 error of 14.8% (visualization of features), followed by GoogLeNet (2014) with an error of 7.8%, and then ResNet (2015) which achieved accuracies below 5% for the first time." }, { "code": null, "e": 19460, "s": 19086, "text": "Initially proposed by Huang et al. in 2016 as a radical extension of the ResNet philosophy. Each block uses every previous feature map as input, effectively concatenating them. These connections mean that the network has L(L+1)/ 2 direct connections, where L is the number of layers in the network. One can think of the architecture as an unrolled recurrent neural network." }, { "code": null, "e": 19782, "s": 19460, "text": "Each layer adds k feature-maps of its own to this state. The growth rate regulates how much new information each layer contributes to the global state. The idea here is that we have all the previous information available at each point. Counter-intuitively, this architecture reduces the total number of parameters needed." }, { "code": null, "e": 20178, "s": 19782, "text": "The network works by allowing maximum information (and gradient) flow at each layer by connecting every layer directly with every other layer. In this way, DenseNets exploit the potential of the network through feature reuse, which means there is no need to learn redundant feature maps. DenseNet layers are relatively narrow (e.g. 12 filters), and they just add a small set of new feature-maps." }, { "code": null, "e": 20379, "s": 20178, "text": "The DenseNet architecture typically has superior performance to the ResNet architecture and can achieve the same or better accuracy with fewer parameters overall, and the networks are easier to train." }, { "code": null, "e": 20650, "s": 20379, "text": "The network formulation may be a bit confusing at first, but it is essentially a ResNet architecture the resolution blocks are replaced by dense blocks. The dense connections have a regularizing effect, which reduces overfitting on tasks with smaller training set sizes." }, { "code": null, "e": 20802, "s": 20650, "text": "It is important to note that DenseNets do not sum the output feature maps of the layer with the incoming feature maps, they, in fact, concatenate them:" }, { "code": null, "e": 20951, "s": 20802, "text": "Dimensions of the feature maps remain constant within a block, but the number of filters changes between them, which is known as the growth rate, k." }, { "code": null, "e": 21168, "s": 20951, "text": "Below is the full architecture of a dense network. It is fairly involved when we look at the network in its full resolution, which is why it is typically easier to visualize in an abstracted form (like we did above)." }, { "code": null, "e": 21237, "s": 21168, "text": "For more information on DenseNet, I recommend the following article." }, { "code": null, "e": 21260, "s": 21237, "text": "towardsdatascience.com" }, { "code": null, "e": 21562, "s": 21260, "text": "As we can see, over the course of just a few years, we have gone from an error rate of around 15% on the ImageNet dataset (which, if you remember, consists of 1.2 million images) to an error rate of around 3–4%. Nowadays the most state-of-the-art networks are able to get below 3% pretty consistently." }, { "code": null, "e": 22008, "s": 21562, "text": "There is still quite a long way to go before we are able to obtain perfect scores for these networks, but the rate of progress is quite staggering in this past decade, and it should be apparent from this why we are currently undergoing a deep learning revolution — we have gone from the stage where humans have superior visual recognition, to a stage where these networks have superior vision (a human cannot achieve 3% on the ImageNet dataset)." }, { "code": null, "e": 22425, "s": 22008, "text": "This has fueled the transition of machine learning algorithms into various commercial fields that require heavy use of image analysis, such as medical imaging (examining brain scans, x-rays, mammography scans) and self-driving cars (computer vision). Image analysis is easily extended to video since this is just a rapid succession of multiple image frames every second — although this requires more computing power." }, { "code": null, "e": 22680, "s": 22425, "text": "Transfer learning is an important topic, and it is definitely worthy of having an article all to itself. However, for now, I will outline the basic idea behind transfer learning so that the reader is able to do more research on it if they are interested." }, { "code": null, "e": 22771, "s": 22680, "text": "How do you make an image classifier that can be trained in a few hours (minutes) on a CPU?" }, { "code": null, "e": 23225, "s": 22771, "text": "Normally, image classification models can take hours, days, or even weeks to train, especially if they are trained on exceptionally large networks and datasets. However, we know that companies such as Google and Microsoft have dedicated teams of data scientists that have spent years developing exceptional networks for the purpose of image classification — why not just use these networks as a starting point for your own image classification projects?" }, { "code": null, "e": 23845, "s": 23225, "text": "This is the idea behind transfer learning, to use pre-trained models, i.e. models with known weights, in order to apply them to a different machine learning problem. Obviously, just purely transferring the model will not be helpful, you must still train the network on your new data, but it is common to freeze the weights of the former layers as these are more generalized features that will likely be unchanged during training. You can think of this as an intelligent way of generating a pre-initialized network, as opposed to having a randomly initialized network (the default case when training a network in Keras)." }, { "code": null, "e": 24227, "s": 23845, "text": "Typically, smaller learning rates are used in transfer learning than in typical network training, as we are essentially tuning the network. If large learning rates are used and the early layers in the network are not frozen, transfer learning may not provide any benefit. Often, it is only the last layer or the last couple of layers that is trained in a transfer learning problem." }, { "code": null, "e": 24514, "s": 24227, "text": "Transfer learning works best for problems that are fairly general and there are networks freely available online (such as image analysis) and when the user has a relatively small dataset available such that it is insufficient to train a neural network — this is a fairly common problem." }, { "code": null, "e": 24689, "s": 24514, "text": "To summarize the main idea: earlier layers of a network learn low-level features, which can be adapted to new domains by changing weights at later and fully-connected layers." }, { "code": null, "e": 24855, "s": 24689, "text": "An example of this would be to use ImageNet trained with any sophisticated huge network, and then to retrain the network on a few thousand hotdog images and you get." }, { "code": null, "e": 24911, "s": 24855, "text": "The steps involved in transfer learning are as follows:" }, { "code": null, "e": 25296, "s": 24911, "text": "Get existing network weightsUnfreeze the “head” fully connected layers and train on your new imagesUnfreeze the latest convolutional layers and train at a very low learning rate starting with the weights from the previously trained weights. This will change the latest layer convolutional weights without triggering large gradient updates which would have occurred had we not done #2." }, { "code": null, "e": 25325, "s": 25296, "text": "Get existing network weights" }, { "code": null, "e": 25397, "s": 25325, "text": "Unfreeze the “head” fully connected layers and train on your new images" }, { "code": null, "e": 25683, "s": 25397, "text": "Unfreeze the latest convolutional layers and train at a very low learning rate starting with the weights from the previously trained weights. This will change the latest layer convolutional weights without triggering large gradient updates which would have occurred had we not done #2." }, { "code": null, "e": 25758, "s": 25683, "text": "For more information, there are several other Medium articles I recommend:" }, { "code": null, "e": 25769, "s": 25758, "text": "medium.com" }, { "code": null, "e": 26158, "s": 25769, "text": "Congratulations on making it to the end of this article! This was a long article that touched on multiple facets of deep learning. The reader should now be fairly well equipped to venture into deep convolutional learning and computer vision literature. I encourage the reader to do more individual research on the topics that I have discussed here so that they can deepen their knowledge." }, { "code": null, "e": 26326, "s": 26158, "text": "I have added links to some further reading in the next section, as well as some of the references to research articles that I borrowed images from during this article." }, { "code": null, "e": 26370, "s": 26326, "text": "Thanks for reading and happy deep learning!" }, { "code": null, "e": 26417, "s": 26370, "text": "MobileNetV2 (https://arxiv.org/abs/1801.04381)" }, { "code": null, "e": 26480, "s": 26417, "text": "Inception-Resnet, v1 and v2 (https://arxiv.org/abs/1602.07261)" }, { "code": null, "e": 26527, "s": 26480, "text": "Wide-Resnet (https://arxiv.org/abs/1605.07146)" }, { "code": null, "e": 26571, "s": 26527, "text": "Xception (https://arxiv.org/abs/1610.02357)" }, { "code": null, "e": 26614, "s": 26571, "text": "ResNeXt (https://arxiv.org/pdf/1611.05431)" }, { "code": null, "e": 26671, "s": 26614, "text": "ShuffleNet, v1 and v2 (https://arxiv.org/abs/1707.01083)" }, { "code": null, "e": 26734, "s": 26671, "text": "Squeeze and Excitation Nets (https://arxiv.org/abs/1709.01507)" }, { "code": null, "e": 26799, "s": 26734, "text": "Original DenseNet paper (https://arxiv.org/pdf/1608.06993v3.pdf)" }, { "code": null, "e": 26871, "s": 26799, "text": "DenseNet Semantic Segmentation (https://arxiv.org/pdf/1611.09326v2.pdf)" }, { "code": null, "e": 26938, "s": 26871, "text": "DenseNet for Optical flow (https://arxiv.org/pdf/1707.06316v1.pdf)" }, { "code": null, "e": 27121, "s": 26938, "text": "Yann LeCun, Leon Bottou, Yoshua Bengio, and Patrick Haffner, “Gradient-based learning applied to document recognition,” Proceedings of the IEEE, vol. 86, no. 11, pp. 2278–2324, 1998." }, { "code": null, "e": 27318, "s": 27121, "text": "Alex Krizhevsky, Ilya Sutskever, and Geoffrey E Hinton, “Imagenet classification with deep convolutional neural networks,” in Advances in neural information processing systems, pp. 1097–1105, 2012" }, { "code": null, "e": 27431, "s": 27318, "text": "Karen Simonyan and Andrew Zisserman, “Very deep convolutional networks for large-scale image recognition,” 2014." }, { "code": null, "e": 27499, "s": 27431, "text": "Min Lin, Qiang Chen, and Shuicheng Yan, “Network in network,” 2013." }, { "code": null, "e": 27777, "s": 27499, "text": "Christian Szegedy, Wei Liu, Yangqing Jia, Pierre Sermanet, Scott Reed, Dragomir Anguelov, Dumitru Erhan, Vincent Vanhoucke, and Andrew Rabinovich, “Going deeper with convolutions,” in Proceedings of the IEEE conference on computer vision and pattern recognition, 2015, pp. 1–9." }, { "code": null, "e": 28003, "s": 27777, "text": "Schroff, Florian, Dmitry Kalenichenko, and James Philbin. ”Facenet: A unified embedding for face recognition and clustering.” In Proceedings of the IEEE conference on computer vision and pattern recognition, pp. 815–823. 2015" }, { "code": null, "e": 28154, "s": 28003, "text": "Long, J., Shelhamer, E., & Darrell, T. (2014). Fully Convolutional Networks for Semantic Segmentation. Retrieved from http://arxiv.org/abs/1411.4038v1" }, { "code": null, "e": 28374, "s": 28154, "text": "Chen, L.-C., Papandreou, G., Kokkinos, I., Murphy, K., & Yuille, A. L. (2014). Semantic Image Segmentation with Deep Convolutional Nets and Fully Connected CRFs. Iclr, 1–14. Retrieved from http://arxiv.org/abs/1412.7062" }, { "code": null, "e": 28513, "s": 28374, "text": "Yu, F., & Koltun, V. (2016). Multi-Scale Context Aggregation by Dilated Convolutions. Iclr, 1–9. http://doi.org/10.16373/j.cnki.ahr.150049" }, { "code": null, "e": 28717, "s": 28513, "text": "Oord, A. van den, Dieleman, S., Zen, H., Simonyan, K., Vinyals, O., Graves, A., ... Kavukcuoglu, K. (2016). WaveNet: A Generative Model for Raw Audio, 1–15. Retrieved from http://arxiv.org/abs/1609.03499" } ]
How to implement Alarm Manager in android?
This example demonstrates how do I implement alarm manager in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="103dp" /> <EditText android:id="@+id/time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="22dp" android:ems="10" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button start; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); start = findViewById(R.id.button); start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startAlert(); } }); } public void startAlert() { EditText text = findViewById(R.id.time); int i = Integer.parseInt(text.getText().toString()); Intent intent = new Intent(this, MyBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, 0); AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (i * 1000), pendingIntent); Toast.makeText(this, "Alarm set in " + i + " seconds", Toast.LENGTH_LONG).show(); } } Step 4 − Create a java class naming BroadcastReceiver and add the following code − import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.media.MediaPlayer; import android.widget.Toast; class MyBroadcastReceiver extends BroadcastReceiver { MediaPlayer mp; @Override public void onReceive(Context context, Intent intent) { mp=MediaPlayer.create(context, R.raw.alarm); mp.start(); Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show(); } } Step 5 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name="MyBroadcastReceiver" ></receiver> </application> </manifest> Step 6 − Click file → New → Android Resource Directory, From the New resource directory, select “raw” from Resource type and click okay. Download an alarm ringtone, copy and paste it in the raw folder on your project. Naming the alarm ringtone file is really important. Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1133, "s": 1062, "text": "This example demonstrates how do I implement alarm manager in android." }, { "code": null, "e": 1262, "s": 1133, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1327, "s": 1262, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2193, "s": 1327, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\"MainActivity\">\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Start\"\n android:layout_alignParentBottom=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginBottom=\"103dp\" />\n <EditText\n android:id=\"@+id/time\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"22dp\"\n android:ems=\"10\" />\n</RelativeLayout>" }, { "code": null, "e": 2250, "s": 2193, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3582, "s": 2250, "text": "import android.app.AlarmManager;\nimport android.app.PendingIntent;\nimport android.content.Intent;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n Button start;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n start = findViewById(R.id.button);\n start.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n startAlert();\n }\n });\n }\n public void startAlert() {\n EditText text = findViewById(R.id.time);\n int i = Integer.parseInt(text.getText().toString());\n Intent intent = new Intent(this, MyBroadcastReceiver.class);\n PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, 0);\n AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);\n alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (i * 1000), pendingIntent);\n Toast.makeText(this, \"Alarm set in \" + i + \" seconds\", Toast.LENGTH_LONG).show();\n }\n}" }, { "code": null, "e": 3665, "s": 3582, "text": "Step 4 − Create a java class naming BroadcastReceiver and add the following code −" }, { "code": null, "e": 4124, "s": 3665, "text": "import android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.media.MediaPlayer;\nimport android.widget.Toast;\nclass MyBroadcastReceiver extends BroadcastReceiver {\n MediaPlayer mp;\n @Override\n public void onReceive(Context context, Intent intent) {\n mp=MediaPlayer.create(context, R.raw.alarm);\n mp.start();\n Toast.makeText(context, \"Alarm....\", Toast.LENGTH_LONG).show();\n }\n}" }, { "code": null, "e": 4179, "s": 4124, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4913, "s": 4179, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <receiver android:name=\"MyBroadcastReceiver\" ></receiver>\n </application>\n</manifest>" }, { "code": null, "e": 5183, "s": 4913, "text": "Step 6 − Click file → New → Android Resource Directory, From the New resource directory, select “raw” from Resource type and click okay. Download an alarm ringtone, copy and paste it in the raw folder on your project. Naming the alarm ringtone file is really important." }, { "code": null, "e": 5530, "s": 5183, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 5571, "s": 5530, "text": "Click here to download the project code." } ]
Display HashMap elements in Java
Create a HashMap − HashMap hm = new HashMap(); Add elements to the HashMap that we will be displaying afterward − hm.put("Maths", new Integer(98)); hm.put("Science", new Integer(90)); hm.put("English", new Integer(97)); hm.put("Physics", new Integer(91)); Now, to display the HashMap elements, use Iterator. The following is an example to display HashMap elements − Live Demo import java.util.*; public class Demo { public static void main(String args[]) { // Create a hash map HashMap hm = new HashMap(); // Put elements to the map hm.put("Maths", new Integer(98)); hm.put("Science", new Integer(90)); hm.put("English", new Integer(97)); hm.put("Physics", new Integer(91)); hm.put("Chemistry", new Integer(93)); // Get a set of the entries Set set = hm.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); System.out.println("Elements: "+hm); } } Maths: 98 English: 97 Chemistry: 93 Science: 90 Physics: 91 Elements: {Maths=98, English=97, Chemistry=93, Science=90, Physics=91}
[ { "code": null, "e": 1081, "s": 1062, "text": "Create a HashMap −" }, { "code": null, "e": 1109, "s": 1081, "text": "HashMap hm = new HashMap();" }, { "code": null, "e": 1176, "s": 1109, "text": "Add elements to the HashMap that we will be displaying afterward −" }, { "code": null, "e": 1318, "s": 1176, "text": "hm.put(\"Maths\", new Integer(98));\nhm.put(\"Science\", new Integer(90));\nhm.put(\"English\", new Integer(97));\nhm.put(\"Physics\", new Integer(91));" }, { "code": null, "e": 1428, "s": 1318, "text": "Now, to display the HashMap elements, use Iterator. The following is an example to display HashMap elements −" }, { "code": null, "e": 1439, "s": 1428, "text": " Live Demo" }, { "code": null, "e": 2227, "s": 1439, "text": "import java.util.*;\npublic class Demo {\n public static void main(String args[]) {\n // Create a hash map\n HashMap hm = new HashMap();\n // Put elements to the map\n hm.put(\"Maths\", new Integer(98));\n hm.put(\"Science\", new Integer(90));\n hm.put(\"English\", new Integer(97));\n hm.put(\"Physics\", new Integer(91));\n hm.put(\"Chemistry\", new Integer(93));\n // Get a set of the entries\n Set set = hm.entrySet();\n // Get an iterator\n Iterator i = set.iterator();\n // Display elements\n while(i.hasNext()) {\n Map.Entry me = (Map.Entry)i.next();\n System.out.print(me.getKey() + \": \");\n System.out.println(me.getValue());\n }\n System.out.println();\n System.out.println(\"Elements: \"+hm);\n }\n}" }, { "code": null, "e": 2358, "s": 2227, "text": "Maths: 98\nEnglish: 97\nChemistry: 93\nScience: 90\nPhysics: 91\nElements: {Maths=98, English=97, Chemistry=93, Science=90, Physics=91}" } ]
PHP 7 - Apache Configuration
Apache uses httpd.conf file for global settings, and the .htaccess file for per-directory access settings. Older versions of Apache split up httpd.conf into three files (access.conf, httpd.conf, and srm.conf), and some users still prefer this arrangement. Apache server has a very powerful, but slightly complex, configuration system of its own. Learn more about it at the Apache Web site − www.apache.org The following section describes the settings in httpd.conf that affect PHP directly and cannot be set elsewhere. If you have standard installation then httpd.conf will be found at /etc/httpd/conf: This value sets the default number of seconds before any HTTP request will time out. If you set PHP's max_execution_time to longer than this value, PHP will keep grinding away but the user may see a 404 error. In safe mode, this value will be ignored; instead, you must use the timeout value in php.ini. DocumentRoot designates the root directory for all HTTP processes on that server. It looks something like this on Unix − DocumentRoot ./usr/local/apache_2.4.0/htdocs. You can choose any directory as the document root. The PHP MIME type needs to be set here for PHP files to be parsed. Remember that you can associate any file extension with PHP like .php3, .php5 or .htm. AddType application/x-httpd-php .php AddType application/x-httpd-phps .phps AddType application/x-httpd-php3 .php3 .phtml AddType application/x-httpd-php .html You must uncomment this line for the Windows apxs module version of Apache with shared object support − LoadModule php7_module modules/php7apache2_4.dll on Unix flavors − LoadModule php7_module modules/mod_php.so You must uncomment this line for the static module version of Apache. AddModule mod_php7.c 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2333, "s": 2077, "text": "Apache uses httpd.conf file for global settings, and the .htaccess file for per-directory access settings. Older versions of Apache split up httpd.conf into three files (access.conf, httpd.conf, and srm.conf), and some users still prefer this arrangement." }, { "code": null, "e": 2483, "s": 2333, "text": "Apache server has a very powerful, but slightly complex, configuration system of its own. Learn more about it at the Apache Web site − www.apache.org" }, { "code": null, "e": 2680, "s": 2483, "text": "The following section describes the settings in httpd.conf that affect PHP directly and cannot be set elsewhere. If you have standard installation then httpd.conf will be found at /etc/httpd/conf:" }, { "code": null, "e": 2984, "s": 2680, "text": "This value sets the default number of seconds before any HTTP request will time out. If you set PHP's max_execution_time to longer than this value, PHP will keep grinding away but the user may see a 404 error. In safe mode, this value will be ignored; instead, you must use the timeout value in php.ini." }, { "code": null, "e": 3105, "s": 2984, "text": "DocumentRoot designates the root directory for all HTTP processes on that server. It looks something like this on Unix −" }, { "code": null, "e": 3152, "s": 3105, "text": "DocumentRoot ./usr/local/apache_2.4.0/htdocs.\n" }, { "code": null, "e": 3203, "s": 3152, "text": "You can choose any directory as the document root." }, { "code": null, "e": 3357, "s": 3203, "text": "The PHP MIME type needs to be set here for PHP files to be parsed. Remember that you can associate any file extension with PHP like .php3, .php5 or .htm." }, { "code": null, "e": 3518, "s": 3357, "text": "AddType application/x-httpd-php .php\nAddType application/x-httpd-phps .phps\nAddType application/x-httpd-php3 .php3 .phtml\nAddType application/x-httpd-php .html\n" }, { "code": null, "e": 3622, "s": 3518, "text": "You must uncomment this line for the Windows apxs module version of Apache with shared object support −" }, { "code": null, "e": 3672, "s": 3622, "text": "LoadModule php7_module modules/php7apache2_4.dll\n" }, { "code": null, "e": 3690, "s": 3672, "text": "on Unix flavors −" }, { "code": null, "e": 3733, "s": 3690, "text": "LoadModule php7_module modules/mod_php.so\n" }, { "code": null, "e": 3803, "s": 3733, "text": "You must uncomment this line for the static module version of Apache." }, { "code": null, "e": 3825, "s": 3803, "text": "AddModule mod_php7.c\n" }, { "code": null, "e": 3858, "s": 3825, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 3874, "s": 3858, "text": " Malhar Lathkar" }, { "code": null, "e": 3907, "s": 3874, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 3918, "s": 3907, "text": " Syed Raza" }, { "code": null, "e": 3953, "s": 3918, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3970, "s": 3953, "text": " Frahaan Hussain" }, { "code": null, "e": 4003, "s": 3970, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 4018, "s": 4003, "text": " Nivedita Jain" }, { "code": null, "e": 4053, "s": 4018, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 4065, "s": 4053, "text": " Azaz Patel" }, { "code": null, "e": 4100, "s": 4065, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4128, "s": 4100, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 4135, "s": 4128, "text": " Print" }, { "code": null, "e": 4146, "s": 4135, "text": " Add Notes" } ]
Fortran - Constants
The constants refer to the fixed values that the program cannot alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, a complex constant, or a string literal. There are only two logical constants : .true. and .false. The constants are treated just like regular variables, except that their values cannot be modified after their definition. There are two types of constants − Literal constants Named constants A literal constant have a value, but no name. For example, following are the literal constants − "PQR" "a" "123'abc$%#@!" " a quote "" " 'PQR' 'a' '123"abc$%#@!' ' an apostrophe '' ' A named constant has a value as well as a name. Named constants should be declared at the beginning of a program or procedure, just like a variable type declaration, indicating its name and type. Named constants are declared with the parameter attribute. For example, real, parameter :: pi = 3.1415927 The following program calculates the displacement due to vertical motion under gravity. program gravitationalDisp ! this program calculates vertical motion under gravity implicit none ! gravitational acceleration real, parameter :: g = 9.81 ! variable declaration real :: s ! displacement real :: t ! time real :: u ! initial speed ! assigning values t = 5.0 u = 50 ! displacement s = u * t - g * (t**2) / 2 ! output print *, "Time = ", t print *, 'Displacement = ',s end program gravitationalDisp When the above code is compiled and executed, it produces the following result − Time = 5.00000000 Displacement = 127.374992 Print Add Notes Bookmark this page
[ { "code": null, "e": 2283, "s": 2146, "text": "The constants refer to the fixed values that the program cannot alter during its execution. These fixed values are also called literals." }, { "code": null, "e": 2499, "s": 2283, "text": "Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, a complex constant, or a string literal. There are only two logical constants : .true. and .false." }, { "code": null, "e": 2622, "s": 2499, "text": "The constants are treated just like regular variables, except that their values cannot be modified after their definition." }, { "code": null, "e": 2657, "s": 2622, "text": "There are two types of constants −" }, { "code": null, "e": 2675, "s": 2657, "text": "Literal constants" }, { "code": null, "e": 2691, "s": 2675, "text": "Named constants" }, { "code": null, "e": 2737, "s": 2691, "text": "A literal constant have a value, but no name." }, { "code": null, "e": 2788, "s": 2737, "text": "For example, following are the literal constants −" }, { "code": null, "e": 2813, "s": 2788, "text": "\"PQR\" \"a\" \"123'abc$%#@!\"" }, { "code": null, "e": 2828, "s": 2813, "text": "\" a quote \"\" \"" }, { "code": null, "e": 2853, "s": 2828, "text": "'PQR' 'a' '123\"abc$%#@!'" }, { "code": null, "e": 2874, "s": 2853, "text": "' an apostrophe '' '" }, { "code": null, "e": 2922, "s": 2874, "text": "A named constant has a value as well as a name." }, { "code": null, "e": 3142, "s": 2922, "text": "Named constants should be declared at the beginning of a program or procedure, just like a variable type declaration, indicating its name and type. Named constants are declared with the parameter attribute. For example," }, { "code": null, "e": 3177, "s": 3142, "text": "real, parameter :: pi = 3.1415927\n" }, { "code": null, "e": 3265, "s": 3177, "text": "The following program calculates the displacement due to vertical motion under gravity." }, { "code": null, "e": 3766, "s": 3265, "text": "program gravitationalDisp\n\n! this program calculates vertical motion under gravity \nimplicit none \n\n ! gravitational acceleration\n real, parameter :: g = 9.81 \n \n ! variable declaration\n real :: s ! displacement \n real :: t ! time \n real :: u ! initial speed \n \n ! assigning values \n t = 5.0 \n u = 50 \n \n ! displacement \n s = u * t - g * (t**2) / 2 \n \n ! output \n print *, \"Time = \", t\n print *, 'Displacement = ',s \n \nend program gravitationalDisp" }, { "code": null, "e": 3847, "s": 3766, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3900, "s": 3847, "text": "Time = 5.00000000 \nDisplacement = 127.374992 \n" }, { "code": null, "e": 3907, "s": 3900, "text": " Print" }, { "code": null, "e": 3918, "s": 3907, "text": " Add Notes" } ]
Create a navbar scrolling with the page in Bootstrap
To create a navbar that scrolls with the page, add the .navbar-static-top class. This class does not require adding the padding to the <body>. Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <nav class = "navbar navbar-default navbar-static-top" role = "navigation"> <div class = "navbar-header"> <a class = "navbar-brand" href = "#">Car Accessories</a> </div> <div> <ul class = "nav navbar-nav"> <li class = "active"><a href = "#">Car Cover</a></li> <li><a href = "#">Car Mobile Holder</a></li> <li><a href = "#">Car Mobile Charger</a></li> </ul> </div> </nav> </body> </html>
[ { "code": null, "e": 1205, "s": 1062, "text": "To create a navbar that scrolls with the page, add the .navbar-static-top class. This class does not require adding the padding to the <body>." }, { "code": null, "e": 1215, "s": 1205, "text": "Live Demo" }, { "code": null, "e": 2019, "s": 1215, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <nav class = \"navbar navbar-default navbar-static-top\" role = \"navigation\">\n <div class = \"navbar-header\">\n <a class = \"navbar-brand\" href = \"#\">Car Accessories</a>\n </div>\n <div>\n <ul class = \"nav navbar-nav\">\n <li class = \"active\"><a href = \"#\">Car Cover</a></li>\n <li><a href = \"#\">Car Mobile Holder</a></li>\n <li><a href = \"#\">Car Mobile Charger</a></li>\n </ul>\n </div>\n </nav>\n </body>\n</html>" } ]
Batch Script - Files Inputs
When a batch file is run, it gives you the option to pass in command line parameters which can then be read within the program for further processing. The batch files parameters can be recalled from within the program using the % operator along with the numeric position of the parameter. Following is how the command line parameters are defined. %0 is the program name as it was called. %1 is the first command line parameter. %2 is the second command line parameter. So on till %9. Let’s take a look at a simple example of how command line parameters can be used. @echo off echo The first parameter is %1 echo The second parameter is %2 echo The third parameter is %3 If the above code is stored in a file called test.bat and the file is run as test.bat 5 10 15 then, following will be the output. The first parameter is 5 The second parameter is 10 The third parameter is 15 Print Add Notes Bookmark this page
[ { "code": null, "e": 2516, "s": 2169, "text": "When a batch file is run, it gives you the option to pass in command line parameters which can then be read within the program for further processing. The batch files parameters can be recalled from within the program using the % operator along with the numeric position of the parameter. Following is how the command line parameters are defined." }, { "code": null, "e": 2557, "s": 2516, "text": "%0 is the program name as it was called." }, { "code": null, "e": 2597, "s": 2557, "text": "%1 is the first command line parameter." }, { "code": null, "e": 2638, "s": 2597, "text": "%2 is the second command line parameter." }, { "code": null, "e": 2653, "s": 2638, "text": "So on till %9." }, { "code": null, "e": 2735, "s": 2653, "text": "Let’s take a look at a simple example of how command line parameters can be used." }, { "code": null, "e": 2839, "s": 2735, "text": "@echo off\necho The first parameter is %1\necho The second parameter is %2\necho The third parameter is %3" }, { "code": null, "e": 2916, "s": 2839, "text": "If the above code is stored in a file called test.bat and the file is run as" }, { "code": null, "e": 2934, "s": 2916, "text": "test.bat 5 10 15\n" }, { "code": null, "e": 2970, "s": 2934, "text": "then, following will be the output." }, { "code": null, "e": 3049, "s": 2970, "text": "The first parameter is 5\nThe second parameter is 10\nThe third parameter is 15\n" }, { "code": null, "e": 3056, "s": 3049, "text": " Print" }, { "code": null, "e": 3067, "s": 3056, "text": " Add Notes" } ]
JSF - Using DataModel in a DataTable
In this section, we'll showcase the use of datamodel in a dataTable. Let us create a test JSF application to test the above functionality. package com.tutorialspoint.test; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.model.ArrayDataModel; import javax.faces.model.DataModel; @ManagedBean(name = "userData", eager = true) @SessionScoped public class UserData implements Serializable { private static final long serialVersionUID = 1L; private static final Employee[] employees = new Employee[] { new Employee("John", "Marketing", 30,2000.00), new Employee("Robert", "Marketing", 35,3000.00), new Employee("Mark", "Sales", 25,2500.00), new Employee("Chris", "Marketing", 33,2500.00), new Employee("Peter", "Customer Care", 20,1500.00) }; private DataModel<Employee> employeeDataModel = new ArrayDataModel<Employee>(employees); public DataModel<Employee> getEmployees() { return employeeDataModel; } } <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:f = "http://java.sun.com/jsf/core"> <h:head> <title>JSF tutorial</title> <h:outputStylesheet library = "css" name = "styles.css" /> </h:head> <h:body> <h2>DataTable Example</h2> <h:form> <h:dataTable value = "#{userData.employees}" var = "employee" styleClass = "employeeTable" headerClass = "employeeTableHeader" rowClasses = "employeeTableOddRow,employeeTableEvenRow"> <h:column> <f:facet name = "header">Sr. No</f:facet> #{userData.employees.rowIndex + 1} </h:column> <h:column> <f:facet name = "header">Name</f:facet> #{employee.name} </h:column> <h:column> <f:facet name = "header">Department</f:facet> #{employee.department} </h:column> <h:column> <f:facet name = "header">Age</f:facet> #{employee.age} </h:column> <h:column> <f:facet name = "header">Salary</f:facet> #{employee.salary} </h:column> </h:dataTable> </h:form> </h:body> </html> Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result. 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2021, "s": 1952, "text": "In this section, we'll showcase the use of datamodel in a dataTable." }, { "code": null, "e": 2091, "s": 2021, "text": "Let us create a test JSF application to test the above functionality." }, { "code": null, "e": 3000, "s": 2091, "text": "package com.tutorialspoint.test;\n\nimport java.io.Serializable;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.SessionScoped;\nimport javax.faces.model.ArrayDataModel;\nimport javax.faces.model.DataModel;\n\n@ManagedBean(name = \"userData\", eager = true)\n@SessionScoped\npublic class UserData implements Serializable {\n private static final long serialVersionUID = 1L;\n\n private static final Employee[] employees = new Employee[] {\n new Employee(\"John\", \"Marketing\", 30,2000.00),\n new Employee(\"Robert\", \"Marketing\", 35,3000.00),\n new Employee(\"Mark\", \"Sales\", 25,2500.00),\n new Employee(\"Chris\", \"Marketing\", 33,2500.00),\n new Employee(\"Peter\", \"Customer Care\", 20,1500.00)\n };\n\n private DataModel<Employee> employeeDataModel \n = new ArrayDataModel<Employee>(employees);\n\n public DataModel<Employee> getEmployees() { \n return employeeDataModel; \n }\t\n}" }, { "code": null, "e": 4577, "s": 3000, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \nxmlns:h = \"http://java.sun.com/jsf/html\"\nxmlns:f = \"http://java.sun.com/jsf/core\">\n \n <h:head>\n <title>JSF tutorial</title>\t\t\n <h:outputStylesheet library = \"css\" name = \"styles.css\" /> \t\n </h:head>\n \n <h:body> \n <h2>DataTable Example</h2>\n \n <h:form>\n <h:dataTable value = \"#{userData.employees}\" var = \"employee\"\n styleClass = \"employeeTable\"\n headerClass = \"employeeTableHeader\"\n rowClasses = \"employeeTableOddRow,employeeTableEvenRow\">\n \n <h:column> \n <f:facet name = \"header\">Sr. No</f:facet>\n #{userData.employees.rowIndex + 1}\n </h:column>\n \n <h:column> \t\t\t\t\n <f:facet name = \"header\">Name</f:facet> \t\t\t\t\n #{employee.name}\n </h:column>\n \n <h:column>\n <f:facet name = \"header\">Department</f:facet>\n #{employee.department}\n </h:column>\n \n <h:column>\n <f:facet name = \"header\">Age</f:facet>\n #{employee.age}\n </h:column>\n \n <h:column>\n <f:facet name = \"header\">Salary</f:facet>\n #{employee.salary}\n </h:column>\n </h:dataTable>\n </h:form>\n \n </h:body>\n</html>" }, { "code": null, "e": 4793, "s": 4577, "text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result." }, { "code": null, "e": 4828, "s": 4793, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4843, "s": 4828, "text": " Chaand Sheikh" }, { "code": null, "e": 4850, "s": 4843, "text": " Print" }, { "code": null, "e": 4861, "s": 4850, "text": " Add Notes" } ]
HTML | DOM Select multiple Property - GeeksforGeeks
14 Dec, 2021 The Select multiple property in HTML DOM is used to set or return whether more than one option can be selected from a drop-down list or not. It returns true if multiple selection in the drop-down list is enabled, otherwise returns false.Syntax: It returns the select multiple property. selectObject.multiple It is used to set select multiple property. selectObject.multiple = true|false Property Values: It contains two values either true or false which is used to specify whether multiple selection in the drop-down list is enabled or not. It is false by default. Return Values: It returns true if multiple selection in the drop-down list is enabled, otherwise returns false.Below program illustrates the Select multiple property in HTML DOM:Example: This example uses Select multiple property to allow multiple selection in a drop-down list. html <!DOCTYPE html><html> <head> <title> HTML DOM Select multiple Property </title> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h2 style="font-family: Impact;"> Select multiple Property </h2><br> Select your preferred course from the drop-down list:<br> <select id="myCourses" size="4"> <option value="C++">c++</option> <option value="Placement">Placement</option> <option value="Java">Java</option> <option value="Python">Python</option> </select> <p> To enable multiple selection, double-click the "Enable Multiple Selection" button. </p> <button ondblclick="myGeeks()"> Enable Multiple Selection </button> <p id="GFG"></p> <script> function myGeeks() { document.getElementById("myCourses").multiple = true; document.getElementById("GFG").innerHTML = "Multiple options can be selected now" + " from the drop down list."; } </script></body> </html> Output: Before Clicking the button: After Clicking the button: Supported Browsers: The browser supported by DOM Select multiple Property are listed below: Apple Safari Internet Explorer Firefox Google Chrome Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ManasChhabra2 chhabradhanvi hritikbhatnagar2182 HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? REST API (Introduction) Design a web page using HTML and CSS Express.js express.Router() Function Installation of Node.js on Linux Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page? How to float three div side by side using CSS?
[ { "code": null, "e": 25037, "s": 25009, "text": "\n14 Dec, 2021" }, { "code": null, "e": 25284, "s": 25037, "text": "The Select multiple property in HTML DOM is used to set or return whether more than one option can be selected from a drop-down list or not. It returns true if multiple selection in the drop-down list is enabled, otherwise returns false.Syntax: " }, { "code": null, "e": 25327, "s": 25284, "text": "It returns the select multiple property. " }, { "code": null, "e": 25349, "s": 25327, "text": "selectObject.multiple" }, { "code": null, "e": 25395, "s": 25349, "text": "It is used to set select multiple property. " }, { "code": null, "e": 25430, "s": 25395, "text": "selectObject.multiple = true|false" }, { "code": null, "e": 25608, "s": 25430, "text": "Property Values: It contains two values either true or false which is used to specify whether multiple selection in the drop-down list is enabled or not. It is false by default." }, { "code": null, "e": 25889, "s": 25608, "text": "Return Values: It returns true if multiple selection in the drop-down list is enabled, otherwise returns false.Below program illustrates the Select multiple property in HTML DOM:Example: This example uses Select multiple property to allow multiple selection in a drop-down list. " }, { "code": null, "e": 25894, "s": 25889, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM Select multiple Property </title> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2 style=\"font-family: Impact;\"> Select multiple Property </h2><br> Select your preferred course from the drop-down list:<br> <select id=\"myCourses\" size=\"4\"> <option value=\"C++\">c++</option> <option value=\"Placement\">Placement</option> <option value=\"Java\">Java</option> <option value=\"Python\">Python</option> </select> <p> To enable multiple selection, double-click the \"Enable Multiple Selection\" button. </p> <button ondblclick=\"myGeeks()\"> Enable Multiple Selection </button> <p id=\"GFG\"></p> <script> function myGeeks() { document.getElementById(\"myCourses\").multiple = true; document.getElementById(\"GFG\").innerHTML = \"Multiple options can be selected now\" + \" from the drop down list.\"; } </script></body> </html> ", "e": 27108, "s": 25894, "text": null }, { "code": null, "e": 27146, "s": 27108, "text": "Output: Before Clicking the button: " }, { "code": null, "e": 27175, "s": 27146, "text": "After Clicking the button: " }, { "code": null, "e": 27269, "s": 27175, "text": "Supported Browsers: The browser supported by DOM Select multiple Property are listed below: " }, { "code": null, "e": 27282, "s": 27269, "text": "Apple Safari" }, { "code": null, "e": 27300, "s": 27282, "text": "Internet Explorer" }, { "code": null, "e": 27308, "s": 27300, "text": "Firefox" }, { "code": null, "e": 27322, "s": 27308, "text": "Google Chrome" }, { "code": null, "e": 27328, "s": 27322, "text": "Opera" }, { "code": null, "e": 27467, "s": 27330, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27481, "s": 27467, "text": "ManasChhabra2" }, { "code": null, "e": 27495, "s": 27481, "text": "chhabradhanvi" }, { "code": null, "e": 27515, "s": 27495, "text": "hritikbhatnagar2182" }, { "code": null, "e": 27524, "s": 27515, "text": "HTML-DOM" }, { "code": null, "e": 27529, "s": 27524, "text": "HTML" }, { "code": null, "e": 27546, "s": 27529, "text": "Web Technologies" }, { "code": null, "e": 27551, "s": 27546, "text": "HTML" }, { "code": null, "e": 27649, "s": 27551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27658, "s": 27649, "text": "Comments" }, { "code": null, "e": 27671, "s": 27658, "text": "Old Comments" }, { "code": null, "e": 27719, "s": 27671, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27756, "s": 27719, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27806, "s": 27756, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27830, "s": 27806, "text": "REST API (Introduction)" }, { "code": null, "e": 27867, "s": 27830, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27904, "s": 27867, "text": "Express.js express.Router() Function" }, { "code": null, "e": 27937, "s": 27904, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28009, "s": 27937, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28067, "s": 28009, "text": "How to create footer to stay at the bottom of a Web page?" } ]
C++ Program to Check Armstrong Number
An Armstrong Number is a number where the sum of the digits raised to the power of total number of digits is equal to the number. Some examples of Armstrong numbers are as follows. 3 = 3^1 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 371 = 3^3 + 7^3 + 1^3 = 27 + 343 + 1 = 371 407 = 4^3 + 0^3 + 7^3 = 64 +0 + 343 = 407 A program that checks whether a number is an Armstrong number or not is as follows. Live Demo #include <iostream> #include <cmath< using namespace std; int main() { int num = 153, digitSum, temp, remainderNum, digitNum ; temp = num; digitNum = 0; while (temp != 0) { digitNum++; temp = temp/10; } temp = num; digitSum = 0; while (temp != 0) { remainderNum = temp%10; digitSum = digitSum + pow(remainderNum, digitNum); temp = temp/10; } if (num == digitSum) cout<<num<<" is an Armstrong number"; else cout<<num<<" is not an Armstrong number"; return 0; } 153 is an Armstrong number In the above program, it is determined if the given number is an Armstrong number or not. This is done using multiple steps. First the number of digits in the number are found. This is done by adding one to digitNum for each digit. This is demonstrated by the following code snippet − temp = num; digitNum = 0; while (temp != 0) { digitNum++; temp = temp/10; } After the number of digits are known, digitSum is calculated by adding each digit raised to the power of digitNum i.e. number of digits. This can be seen in the following code snippet. temp = num; digitSum = 0; while (temp != 0) { remainderNum = temp%10; digitSum = digitSum + pow(remainderNum, digitNum); temp = temp/10; } If the number is equal to the digitSum, then that number is an Armstrong number and that is printed. If not, then it is not an Armstrong number. This is seen in the below code snippet. if (num == digitSum) cout<<num<<" is an Armstrong number"; else cout<<num<<" is not an Armstrong number";
[ { "code": null, "e": 1243, "s": 1062, "text": "An Armstrong Number is a number where the sum of the digits raised to the power of total number of digits is equal to the number. Some examples of Armstrong numbers are as follows." }, { "code": null, "e": 1379, "s": 1243, "text": "3 = 3^1\n153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153\n371 = 3^3 + 7^3 + 1^3 = 27 + 343 + 1 = 371\n407 = 4^3 + 0^3 + 7^3 = 64 +0 + 343 = 407" }, { "code": null, "e": 1463, "s": 1379, "text": "A program that checks whether a number is an Armstrong number or not is as follows." }, { "code": null, "e": 1474, "s": 1463, "text": " Live Demo" }, { "code": null, "e": 2006, "s": 1474, "text": "#include <iostream>\n#include <cmath<\nusing namespace std;\nint main() {\n int num = 153, digitSum, temp, remainderNum, digitNum ;\n temp = num;\n digitNum = 0;\n while (temp != 0) {\n digitNum++;\n temp = temp/10;\n }\n temp = num;\n digitSum = 0;\n while (temp != 0) {\n remainderNum = temp%10;\n digitSum = digitSum + pow(remainderNum, digitNum);\n temp = temp/10;\n }\n if (num == digitSum)\n cout<<num<<\" is an Armstrong number\";\n else\n cout<<num<<\" is not an Armstrong number\";\n return 0;\n}" }, { "code": null, "e": 2033, "s": 2006, "text": "153 is an Armstrong number" }, { "code": null, "e": 2265, "s": 2033, "text": "In the above program, it is determined if the given number is an Armstrong number or not. This is done using multiple steps. First the number of digits in the number are found. This is done by adding one to digitNum for each digit." }, { "code": null, "e": 2318, "s": 2265, "text": "This is demonstrated by the following code snippet −" }, { "code": null, "e": 2400, "s": 2318, "text": "temp = num;\ndigitNum = 0;\nwhile (temp != 0) {\n digitNum++;\n temp = temp/10;\n}" }, { "code": null, "e": 2585, "s": 2400, "text": "After the number of digits are known, digitSum is calculated by adding each digit raised to the power of digitNum i.e. number of digits. This can be seen in the following code snippet." }, { "code": null, "e": 2733, "s": 2585, "text": "temp = num;\ndigitSum = 0;\nwhile (temp != 0) {\n remainderNum = temp%10;\n digitSum = digitSum + pow(remainderNum, digitNum);\n temp = temp/10;\n}" }, { "code": null, "e": 2918, "s": 2733, "text": "If the number is equal to the digitSum, then that number is an Armstrong number and that is printed. If not, then it is not an Armstrong number. This is seen in the below code snippet." }, { "code": null, "e": 3024, "s": 2918, "text": "if (num == digitSum)\ncout<<num<<\" is an Armstrong number\";\nelse\ncout<<num<<\" is not an Armstrong number\";" } ]
JSP - File Uploading
In this chapter, we will discuss File Uploading in JSP. A JSP can be used with an HTML form tag to allow users to upload files to the server. An uploaded file can be a text file or a binary or an image file or just any document. Let us now understand how to create a file upload form. The following HTML code creates an uploader form. Following are the important points to be noted down − The form method attribute should be set to POST method and GET method can not be used. The form method attribute should be set to POST method and GET method can not be used. The form enctype attribute should be set to multipart/form-data. The form enctype attribute should be set to multipart/form-data. The form action attribute should be set to a JSP file which would handle file uploading at backend server. Following example is using uploadFile.jsp program file to upload file. The form action attribute should be set to a JSP file which would handle file uploading at backend server. Following example is using uploadFile.jsp program file to upload file. To upload a single file you should use a single <input .../> tag with attribute type = "file". To allow multiple files uploading, include more than one input tag with different values for the name attribute. The browser associates a Browse button with each of them. To upload a single file you should use a single <input .../> tag with attribute type = "file". To allow multiple files uploading, include more than one input tag with different values for the name attribute. The browser associates a Browse button with each of them. <html> <head> <title>File Uploading Form</title> </head> <body> <h3>File Upload:</h3> Select a file to upload: <br /> <form action = "UploadServlet" method = "post" enctype = "multipart/form-data"> <input type = "file" name = "file" size = "50" /> <br /> <input type = "submit" value = "Upload File" /> </form> </body> </html> This will display the following result. You can now select a file from the local PC and when the user clicks "Upload File", the form gets submitted along with the selected file − File Upload − Select a file to upload − Select a file to upload − NOTE − Above form is just dummy form and would not work, you should try above code at your machine to make it work. Let us now define a location where the uploaded files will be stored. You can hard code this in your program or this directory name can also be added using an external configuration such as a context-param element in web.xml as follows − <web-app> .... <context-param> <description>Location to store uploaded file</description> <param-name>file-upload</param-name> <param-value> c:\apache-tomcat-5.5.29\webapps\data\ </param-value> </context-param> .... </web-app> Following is the source code for UploadFile.jsp. This can handle uploading of multiple files at a time. Let us now consider the following before proceeding with the uploading of files. The following example depends on FileUpload; make sure you have the latest version of commons-fileupload.x.x.jar file in your classpath. You can download it from https://commons.apache.org/fileupload/. The following example depends on FileUpload; make sure you have the latest version of commons-fileupload.x.x.jar file in your classpath. You can download it from https://commons.apache.org/fileupload/. FileUpload depends on Commons IO; make sure you have the latest version of commons-io-x.x.jar file in your classpath. You can download it from https://commons.apache.org/io/. FileUpload depends on Commons IO; make sure you have the latest version of commons-io-x.x.jar file in your classpath. You can download it from https://commons.apache.org/io/. While testing the following example, you should upload a file which is of less size than maxFileSize otherwise the file will not be uploaded. While testing the following example, you should upload a file which is of less size than maxFileSize otherwise the file will not be uploaded. Make sure you have created directories c:\temp and c:\apache-tomcat5.5.29\webapps\data well in advance. Make sure you have created directories c:\temp and c:\apache-tomcat5.5.29\webapps\data well in advance. <%@ page import = "java.io.*,java.util.*, javax.servlet.*" %> <%@ page import = "javax.servlet.http.*" %> <%@ page import = "org.apache.commons.fileupload.*" %> <%@ page import = "org.apache.commons.fileupload.disk.*" %> <%@ page import = "org.apache.commons.fileupload.servlet.*" %> <%@ page import = "org.apache.commons.io.output.*" %> <% File file ; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; ServletContext context = pageContext.getServletContext(); String filePath = context.getInitParameter("file-upload"); // Verify the content type String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File("c:\\temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax( maxFileSize ); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>JSP File upload</title>"); out.println("</head>"); out.println("<body>"); while ( i.hasNext () ) { FileItem fi = (FileItem)i.next(); if ( !fi.isFormField () ) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if( fileName.lastIndexOf("\\") >= 0 ) { file = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ; } else { file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\")+1)) ; } fi.write( file ) ; out.println("Uploaded Filename: " + filePath + fileName + "<br>"); } } out.println("</body>"); out.println("</html>"); } catch(Exception ex) { System.out.println(ex); } } else { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); } %> Now try to upload files using the HTML form which you created above. When you try http://localhost:8080/UploadFile.htm, it will display the following result. This will help you upload any file from your local machine. File Upload − Select a file to upload − Select a file to upload − If your JSP script works fine, your file should be uploaded in c:\apache-tomcat5.5.29\webapps\data\ directory. 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2468, "s": 2239, "text": "In this chapter, we will discuss File Uploading in JSP. A JSP can be used with an HTML form tag to allow users to upload files to the server. An uploaded file can be a text file or a binary or an image file or just any document." }, { "code": null, "e": 2628, "s": 2468, "text": "Let us now understand how to create a file upload form. The following HTML code creates an uploader form. Following are the important points to be noted down −" }, { "code": null, "e": 2715, "s": 2628, "text": "The form method attribute should be set to POST method and GET method can not be used." }, { "code": null, "e": 2802, "s": 2715, "text": "The form method attribute should be set to POST method and GET method can not be used." }, { "code": null, "e": 2867, "s": 2802, "text": "The form enctype attribute should be set to multipart/form-data." }, { "code": null, "e": 2932, "s": 2867, "text": "The form enctype attribute should be set to multipart/form-data." }, { "code": null, "e": 3110, "s": 2932, "text": "The form action attribute should be set to a JSP file which would handle file uploading at backend server. Following example is using uploadFile.jsp program file to upload file." }, { "code": null, "e": 3288, "s": 3110, "text": "The form action attribute should be set to a JSP file which would handle file uploading at backend server. Following example is using uploadFile.jsp program file to upload file." }, { "code": null, "e": 3554, "s": 3288, "text": "To upload a single file you should use a single <input .../> tag with attribute type = \"file\". To allow multiple files uploading, include more than one input tag with different values for the name attribute. The browser associates a Browse button with each of them." }, { "code": null, "e": 3820, "s": 3554, "text": "To upload a single file you should use a single <input .../> tag with attribute type = \"file\". To allow multiple files uploading, include more than one input tag with different values for the name attribute. The browser associates a Browse button with each of them." }, { "code": null, "e": 4233, "s": 3820, "text": "<html>\n <head>\n <title>File Uploading Form</title>\n </head>\n \n <body>\n <h3>File Upload:</h3>\n Select a file to upload: <br />\n <form action = \"UploadServlet\" method = \"post\"\n enctype = \"multipart/form-data\">\n <input type = \"file\" name = \"file\" size = \"50\" />\n <br />\n <input type = \"submit\" value = \"Upload File\" />\n </form>\n </body>\n \n</html>" }, { "code": null, "e": 4412, "s": 4233, "text": "This will display the following result. You can now select a file from the local PC and when the user clicks \"Upload File\", the form gets submitted along with the selected file −" }, { "code": null, "e": 4463, "s": 4412, "text": "File Upload − \nSelect a file to upload − \n \n \n \n \n" }, { "code": null, "e": 4489, "s": 4463, "text": "Select a file to upload −" }, { "code": null, "e": 4605, "s": 4489, "text": "NOTE − Above form is just dummy form and would not work, you should try above code at your machine to make it work." }, { "code": null, "e": 4843, "s": 4605, "text": "Let us now define a location where the uploaded files will be stored. You can hard code this in your program or this directory name can also be added using an external configuration such as a context-param element in web.xml as follows −" }, { "code": null, "e": 5092, "s": 4843, "text": "<web-app>\n....\n<context-param> \n <description>Location to store uploaded file</description> \n <param-name>file-upload</param-name> \n <param-value>\n c:\\apache-tomcat-5.5.29\\webapps\\data\\\n </param-value> \n</context-param>\n....\n</web-app>" }, { "code": null, "e": 5277, "s": 5092, "text": "Following is the source code for UploadFile.jsp. This can handle uploading of multiple files at a time. Let us now consider the following before proceeding with the uploading of files." }, { "code": null, "e": 5479, "s": 5277, "text": "The following example depends on FileUpload; make sure you have the latest version of commons-fileupload.x.x.jar file in your classpath. You can download it from https://commons.apache.org/fileupload/." }, { "code": null, "e": 5681, "s": 5479, "text": "The following example depends on FileUpload; make sure you have the latest version of commons-fileupload.x.x.jar file in your classpath. You can download it from https://commons.apache.org/fileupload/." }, { "code": null, "e": 5856, "s": 5681, "text": "FileUpload depends on Commons IO; make sure you have the latest version of commons-io-x.x.jar file in your classpath. You can download it from https://commons.apache.org/io/." }, { "code": null, "e": 6031, "s": 5856, "text": "FileUpload depends on Commons IO; make sure you have the latest version of commons-io-x.x.jar file in your classpath. You can download it from https://commons.apache.org/io/." }, { "code": null, "e": 6173, "s": 6031, "text": "While testing the following example, you should upload a file which is of less size than maxFileSize otherwise the file will not be uploaded." }, { "code": null, "e": 6315, "s": 6173, "text": "While testing the following example, you should upload a file which is of less size than maxFileSize otherwise the file will not be uploaded." }, { "code": null, "e": 6419, "s": 6315, "text": "Make sure you have created directories c:\\temp and c:\\apache-tomcat5.5.29\\webapps\\data well in advance." }, { "code": null, "e": 6523, "s": 6419, "text": "Make sure you have created directories c:\\temp and c:\\apache-tomcat5.5.29\\webapps\\data well in advance." }, { "code": null, "e": 9444, "s": 6523, "text": "<%@ page import = \"java.io.*,java.util.*, javax.servlet.*\" %>\n<%@ page import = \"javax.servlet.http.*\" %>\n<%@ page import = \"org.apache.commons.fileupload.*\" %>\n<%@ page import = \"org.apache.commons.fileupload.disk.*\" %>\n<%@ page import = \"org.apache.commons.fileupload.servlet.*\" %>\n<%@ page import = \"org.apache.commons.io.output.*\" %>\n\n<%\n File file ;\n int maxFileSize = 5000 * 1024;\n int maxMemSize = 5000 * 1024;\n ServletContext context = pageContext.getServletContext();\n String filePath = context.getInitParameter(\"file-upload\");\n\n // Verify the content type\n String contentType = request.getContentType();\n \n if ((contentType.indexOf(\"multipart/form-data\") >= 0)) {\n DiskFileItemFactory factory = new DiskFileItemFactory();\n // maximum size that will be stored in memory\n factory.setSizeThreshold(maxMemSize);\n \n // Location to save data that is larger than maxMemSize.\n factory.setRepository(new File(\"c:\\\\temp\"));\n\n // Create a new file upload handler\n ServletFileUpload upload = new ServletFileUpload(factory);\n \n // maximum file size to be uploaded.\n upload.setSizeMax( maxFileSize );\n \n try { \n // Parse the request to get file items.\n List fileItems = upload.parseRequest(request);\n\n // Process the uploaded file items\n Iterator i = fileItems.iterator();\n\n out.println(\"<html>\");\n out.println(\"<head>\");\n out.println(\"<title>JSP File upload</title>\"); \n out.println(\"</head>\");\n out.println(\"<body>\");\n \n while ( i.hasNext () ) {\n FileItem fi = (FileItem)i.next();\n if ( !fi.isFormField () ) {\n // Get the uploaded file parameters\n String fieldName = fi.getFieldName();\n String fileName = fi.getName();\n boolean isInMemory = fi.isInMemory();\n long sizeInBytes = fi.getSize();\n \n // Write the file\n if( fileName.lastIndexOf(\"\\\\\") >= 0 ) {\n file = new File( filePath + \n fileName.substring( fileName.lastIndexOf(\"\\\\\"))) ;\n } else {\n file = new File( filePath + \n fileName.substring(fileName.lastIndexOf(\"\\\\\")+1)) ;\n }\n fi.write( file ) ;\n out.println(\"Uploaded Filename: \" + filePath + \n fileName + \"<br>\");\n }\n }\n out.println(\"</body>\");\n out.println(\"</html>\");\n } catch(Exception ex) {\n System.out.println(ex);\n }\n } else {\n out.println(\"<html>\");\n out.println(\"<head>\");\n out.println(\"<title>Servlet upload</title>\"); \n out.println(\"</head>\");\n out.println(\"<body>\");\n out.println(\"<p>No file uploaded</p>\"); \n out.println(\"</body>\");\n out.println(\"</html>\");\n }\n%>" }, { "code": null, "e": 9662, "s": 9444, "text": "Now try to upload files using the HTML form which you created above. When you try http://localhost:8080/UploadFile.htm, it will display the following result. This will help you upload any file from your local machine." }, { "code": null, "e": 9711, "s": 9662, "text": "File Upload − \nSelect a file to upload − \n \n \n \n" }, { "code": null, "e": 9737, "s": 9711, "text": "Select a file to upload −" }, { "code": null, "e": 9848, "s": 9737, "text": "If your JSP script works fine, your file should be uploaded in c:\\apache-tomcat5.5.29\\webapps\\data\\ directory." }, { "code": null, "e": 9883, "s": 9848, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 9898, "s": 9883, "text": " Chaand Sheikh" }, { "code": null, "e": 9933, "s": 9898, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 9948, "s": 9933, "text": " Chaand Sheikh" }, { "code": null, "e": 9983, "s": 9948, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9997, "s": 9983, "text": " Karthikeya T" }, { "code": null, "e": 10032, "s": 9997, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 10048, "s": 10032, "text": " TELCOMA Global" }, { "code": null, "e": 10081, "s": 10048, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 10097, "s": 10081, "text": " TELCOMA Global" }, { "code": null, "e": 10131, "s": 10097, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 10139, "s": 10131, "text": " Uplatz" }, { "code": null, "e": 10146, "s": 10139, "text": " Print" }, { "code": null, "e": 10157, "s": 10146, "text": " Add Notes" } ]
VAF - Fast and Advance Fuzzer Tool in Kali Linux - GeeksforGeeks
07 Feb, 2022 In this article, we are going to see the VAF tools, which is used to automated software testing technique that involves providing invalid, unexpected, or random data as inputs to a computer program and detect the bug. URL Fuzzing is the art of finding hidden files and directories on the target domain server. These files and directories can have sensitive data and information that can reveal the application’s internal architecture. Doing this fuzzing task in an automated way makes it a more straightforward and time saver process for every penetration tester. VAF is the computerized tool used to fuzz the files and directories from the target domain. VAF tool is open-source and free to use. We can filter out our results by excluding specific status codes and including only the essential extensions of files like .php, .html. Step 1: Open up your Kali Linux terminal and move to Desktop using the following command. cd Desktop Step 2: You are on Desktop now create a new directory called VAF using the following command. In this directory, we will complete the installation of the VAF tool. mkdir VAF Step 3: Now switch to the VAF directory using the following command. cd VAF Step 4: Now you have to install the tool. You have to clone the tool from GitHub. git clone https://github.com/d4rckh/vaf.git Step 5: The tool has been downloaded successfully in the VAF directory. Now list out the contents of the tool by using the below command. ls Step 6: You can observe that there is a new directory created of the VAF tool that has been generated while we were installing the tool. Now move to that directory using the below command: cd vaf Step 7: Once again to discover the contents of the tool, use the below command. ls Step 8: Run the Bash Script using the following command. ./vaf_linux_amd64 -h Example 1: Simple Fuzz In this example, We will be fuzzing files and directories from the target domain testphp.vulnweb.com. We have specified the target domain in the -u tag and specified the wordlist of possible files and directories phrases in the -w tag. ./vaf_linux_amd64 -u http://testphp.vulnweb.com/[] -w /usr/share/wordlists/dirb/common.txt In the below Screenshot, We have got the results or the directories and files hosted on the target domain server. Example 2: Specific Response Code In this example, We will be fuzzing the directories and files with all the status code responses. We have used -sc tag to use all status codes. ./vaf_linux_amd64 -u http://testphp.vulnweb.com/[ ] -sc any -w /usr/share/wordlists/dirb/common.txt In the below Screenshot, We have got the results of various status codes like 200, 404. Example 3: Specific Extension Files In this example, We will be fuzzing directories and files with a specific extension like PHP, HTML. We have used -sf tag to specify the extensions. ./vaf_linux_amd64 -u http://testphp.vulnweb.com/[] -w /usr/share/wordlists/dirb/common.txt -sf .php,.html In the below Screenshot, We have got the results which are only the files that have the extension of .php, .html. Example 4: Print URL In this example, We will be displaying the full URL of identified files and directories. ./vaf_linux_amd64 -u http://testphp.vulnweb.com/[] -w /usr/share/wordlists/dirb/common.txt -sf .php,.html -pu In the below Screenshot, We have got the full URL of identified files and directories. In the below Screenshot, We are actually visiting the URL which contains file 404.php. varshagumber28 Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Thread functions in C/C++ Array Basics in Shell Scripting | Set 1 scp command in Linux with Examples chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program mv command in Linux with examples SED command in Linux | Set 2 Basic Operators in Shell Scripting Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 24326, "s": 24298, "text": "\n07 Feb, 2022" }, { "code": null, "e": 24544, "s": 24326, "text": "In this article, we are going to see the VAF tools, which is used to automated software testing technique that involves providing invalid, unexpected, or random data as inputs to a computer program and detect the bug." }, { "code": null, "e": 25159, "s": 24544, "text": "URL Fuzzing is the art of finding hidden files and directories on the target domain server. These files and directories can have sensitive data and information that can reveal the application’s internal architecture. Doing this fuzzing task in an automated way makes it a more straightforward and time saver process for every penetration tester. VAF is the computerized tool used to fuzz the files and directories from the target domain. VAF tool is open-source and free to use. We can filter out our results by excluding specific status codes and including only the essential extensions of files like .php, .html." }, { "code": null, "e": 25249, "s": 25159, "text": "Step 1: Open up your Kali Linux terminal and move to Desktop using the following command." }, { "code": null, "e": 25260, "s": 25249, "text": "cd Desktop" }, { "code": null, "e": 25424, "s": 25260, "text": "Step 2: You are on Desktop now create a new directory called VAF using the following command. In this directory, we will complete the installation of the VAF tool." }, { "code": null, "e": 25435, "s": 25424, "text": "mkdir VAF " }, { "code": null, "e": 25504, "s": 25435, "text": "Step 3: Now switch to the VAF directory using the following command." }, { "code": null, "e": 25512, "s": 25504, "text": "cd VAF " }, { "code": null, "e": 25594, "s": 25512, "text": "Step 4: Now you have to install the tool. You have to clone the tool from GitHub." }, { "code": null, "e": 25638, "s": 25594, "text": "git clone https://github.com/d4rckh/vaf.git" }, { "code": null, "e": 25776, "s": 25638, "text": "Step 5: The tool has been downloaded successfully in the VAF directory. Now list out the contents of the tool by using the below command." }, { "code": null, "e": 25779, "s": 25776, "text": "ls" }, { "code": null, "e": 25968, "s": 25779, "text": "Step 6: You can observe that there is a new directory created of the VAF tool that has been generated while we were installing the tool. Now move to that directory using the below command:" }, { "code": null, "e": 25975, "s": 25968, "text": "cd vaf" }, { "code": null, "e": 26055, "s": 25975, "text": "Step 7: Once again to discover the contents of the tool, use the below command." }, { "code": null, "e": 26058, "s": 26055, "text": "ls" }, { "code": null, "e": 26115, "s": 26058, "text": "Step 8: Run the Bash Script using the following command." }, { "code": null, "e": 26136, "s": 26115, "text": "./vaf_linux_amd64 -h" }, { "code": null, "e": 26159, "s": 26136, "text": "Example 1: Simple Fuzz" }, { "code": null, "e": 26395, "s": 26159, "text": "In this example, We will be fuzzing files and directories from the target domain testphp.vulnweb.com. We have specified the target domain in the -u tag and specified the wordlist of possible files and directories phrases in the -w tag." }, { "code": null, "e": 26486, "s": 26395, "text": "./vaf_linux_amd64 -u http://testphp.vulnweb.com/[] -w /usr/share/wordlists/dirb/common.txt" }, { "code": null, "e": 26600, "s": 26486, "text": "In the below Screenshot, We have got the results or the directories and files hosted on the target domain server." }, { "code": null, "e": 26634, "s": 26600, "text": "Example 2: Specific Response Code" }, { "code": null, "e": 26778, "s": 26634, "text": "In this example, We will be fuzzing the directories and files with all the status code responses. We have used -sc tag to use all status codes." }, { "code": null, "e": 26878, "s": 26778, "text": "./vaf_linux_amd64 -u http://testphp.vulnweb.com/[ ] -sc any -w /usr/share/wordlists/dirb/common.txt" }, { "code": null, "e": 26966, "s": 26878, "text": "In the below Screenshot, We have got the results of various status codes like 200, 404." }, { "code": null, "e": 27002, "s": 26966, "text": "Example 3: Specific Extension Files" }, { "code": null, "e": 27150, "s": 27002, "text": "In this example, We will be fuzzing directories and files with a specific extension like PHP, HTML. We have used -sf tag to specify the extensions." }, { "code": null, "e": 27256, "s": 27150, "text": "./vaf_linux_amd64 -u http://testphp.vulnweb.com/[] -w /usr/share/wordlists/dirb/common.txt -sf .php,.html" }, { "code": null, "e": 27370, "s": 27256, "text": "In the below Screenshot, We have got the results which are only the files that have the extension of .php, .html." }, { "code": null, "e": 27391, "s": 27370, "text": "Example 4: Print URL" }, { "code": null, "e": 27480, "s": 27391, "text": "In this example, We will be displaying the full URL of identified files and directories." }, { "code": null, "e": 27590, "s": 27480, "text": "./vaf_linux_amd64 -u http://testphp.vulnweb.com/[] -w /usr/share/wordlists/dirb/common.txt -sf .php,.html -pu" }, { "code": null, "e": 27677, "s": 27590, "text": "In the below Screenshot, We have got the full URL of identified files and directories." }, { "code": null, "e": 27764, "s": 27677, "text": "In the below Screenshot, We are actually visiting the URL which contains file 404.php." }, { "code": null, "e": 27779, "s": 27764, "text": "varshagumber28" }, { "code": null, "e": 27790, "s": 27779, "text": "Kali-Linux" }, { "code": null, "e": 27802, "s": 27790, "text": "Linux-Tools" }, { "code": null, "e": 27813, "s": 27802, "text": "Linux-Unix" }, { "code": null, "e": 27911, "s": 27813, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27920, "s": 27911, "text": "Comments" }, { "code": null, "e": 27933, "s": 27920, "text": "Old Comments" }, { "code": null, "e": 27959, "s": 27933, "text": "Thread functions in C/C++" }, { "code": null, "e": 27999, "s": 27959, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 28034, "s": 27999, "text": "scp command in Linux with Examples" }, { "code": null, "e": 28071, "s": 28034, "text": "chown command in Linux with Examples" }, { "code": null, "e": 28108, "s": 28071, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 28150, "s": 28108, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 28184, "s": 28150, "text": "mv command in Linux with examples" }, { "code": null, "e": 28213, "s": 28184, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 28248, "s": 28213, "text": "Basic Operators in Shell Scripting" } ]
Why is Linear Algebra Taught So Badly? | by Callum Ballard | Towards Data Science
Here’s a quick maths question for you. Raise your hand if you can multiply these two matrices together: Congratulations if you said: Now keep your hand up if you know why. And by ‘why’, I don’t mean because: Whilst mathematically true, this formula is more descriptive of ‘how’ than it is of ‘why’. In and of itself, this formula is pretty much devoid of intuition. And yet, this is how matrix multiplication is nearly always taught. Memorise the formula. Use it in an exam. Profit? This was certainly my experience, both when first learning linear algebra as a 16 year old, and then while attending an ostensibly world-leading university to study for my mathematics bachelors. Here’s another question for you: what is the determinant of the following matrix? Congratulations if you said 2. But you might be able to guess where I’m going with this. We know that for a 2x2 matrix, the determinant is given by the following formula: But why? And for that matter, what even is the determinant? We are taught that it has a couple of useful properties (for example, a determinant of 0 is a red flag if you’re trying to solve systems of linear equations with row reduction). But in the two compulsory modules of linear algebra I took at university (an institution whose reputation, I suspect, relies on its excellence in research, rather than teaching), not once was the determinant of a matrix contextualised or explained at anything beyond a surface level. This slightly utilitarian attitude to teaching linear algebra is clearly problematic. Mathematics is a discipline that relies on an ‘incremental’ learning — gaining new knowledge often requires you to build upon what you already know. If your theoretical foundations are predicated on rote learning and plugging numbers into formulae, without a deeper appreciation and understanding of what’s actually going on, then they tend to fall down under the weight of something as heavy as, let’s say, machine learning. At this point, I’ll mention that this blog was heavily inspired by a series of videos made by Grant Sanderson (a.k.a. 3Blue1Brown). For those unfamiliar with his work, Sanderson creates really nicely animated videos in a way that makes complicated mathematical subjects accessible to the educated layman (his videos explaining neural networks and cryptocurrency are well worth your time). At its core, Sanderson’s ‘Essence of Linear Algebra’ series seeks to introduce, motivate, and conceptualise many of the basic ideas around linear algebra in terms of linear transformations and their associated visualisations. As it turns out, this is a really helpful way to get your head around many of the core fundamentals. “The goal here is not to try to teach everything, it’s that you come away with a strong intuition... and that those intuitions make any future learning that you do more fruitful...” — Grant Sanderson Before answering this question, let’s take a step back and think about what a linear transformation is. To keep things simple, let’s keep things in two dimensions (though the following applies to higher dimensions as well). A linear transformation is a way of changing the shape of a ‘space’ (in this case, the 2D plane), in such a way that: Keeps parallel lines parallel Maintains an equal distance between parallel lines that were equally spaced to begin with Leaves the origin at the origin Broadly speaking, this gives us three different types of linear transformations that we could do: Rotations Scaling (reducing or increasing the space between parallel lines). Note — this also accounts for reflections in either of the x or y axes, these simply have negative scale factors. And sheers (note how this preserves equal distance between parallel lines) Any combination of these three types of operation would also be a linear transformation on its own terms (more on this idea later). Whilst these illustrations above are created to demonstrate the fact that a linear transformation affects the entirety of 2D space, it transpires that we can describe them in terms of what they do to the two ‘unit vectors’, called î (i-hat) and ĵ (j-hat) respectively. There’s more detail that one can go into, but in essence, this is driven by the fact that you can reach any point on the 2D plane with a linear combination of î and ĵ (for example, a vector v [3, -2] will simply be equivalent to 3 lots of î plus -2 lots of ĵ). Suppose we want to think about a linear transformation that rotates everything counter-clockwise by a quarter turn. What becomes of our vector, v? It turns out we can describe what happens to v purely in terms of what happens to î and ĵ. Recall that v, [3, -2], was given as 3 lots of î plus -2 lots of ĵ. Well, it turns out that transformed v is equivalent to 3 lots of transformed î plus -2 lots of transformed ĵ. In Sanderson’s words, this line: transformed_v = 3*[0,1] + (-2)*[-1,0] is “where all the intuition is”. In particular, we can take the vectors of ‘transformed î’ and ‘transformed ĵ’, put them together to form a 2x2 matrix, refer back to this more ‘intuitive’ view of what happens to v, and all of a sudden we’ve justified vector multiplication. So what about the multiplication of two 2x2 matrices that we examined earlier? We’ve just demonstrated that a 2x2 matrix will necessarily represent some kind of linear transformation in 2D space. In particular, for a given matrix [[a, b], [c, d]], the vectors [a, c] and [b, d] represent the coordinates of ‘transformed î’ and ‘transformed ĵ’ respectively. Suppose we want to make two linear transformations one after the other. For illustration, let’s suppose we perform the counter-clockwise quarter-turn that we looked at before, and follow this with a reflection in the x-axis. These two transformations can be both be represented by 2x2 matrices. We already know the matrix that represents the rotation, so what about the reflection? We can use the same technique as before — watch what happens to î and ĵ. Of course, î remains the same, and ĵ becomes negative. We’ve previously shown that we can put these ‘transformed î’ and ‘transformed ĵ’ vectors together to form the matrix representative of the overall transformation. So how can we think about the case when two transformations are performed one after another; first the rotation, then the reflection? We can approach this in the same way as before — watch what happens to î and ĵ. We know from before that the rotation takes î from [1, 0] to [0, 1]. If we then want to apply the reflection to this ‘transformed î’, we simply need to multiply the matrix representing this reflection by the vector representing ‘transformed î’, [0, 1] (recall — we’ve already shown that multiplying a transformation matrix by a vector describes what happens to that vector when transformed). Of course, we now need to observe what happens to ĵ, using the same reasoning. Now that we know what happens to î and ĵ after they go through the rotation and reflection transformations one after another, we can put these two vectors together to describe the cumulative effect as a single matrix. Which looks an awful lot like a representation of our standard formula for matrix multiplication. Of course, you could try this thought experiment with any sequence of linear transformations. By following what happens to î and ĵ, you can effectively. It’s worth noting that, by thinking about matrix multiplication in terms of sequential linear transformations, it becomes quite easy to justify our standard rules of matrix multiplication. For three different matrices A, B, and C, think about why the following properties hold: A*B ≠ B*A A*(B*C) = (A*B)*C A*(B+C) = A*B + A*C Towards the start of the blog, I showed how to mechanically calculate the determinant. I then asked why the formula holds (and, for that matter, what the determinant even is). I cover this in another blog, but, spoiler alert, the determinant of a 2x2 matrix simply represents the scale by which a given area in 2D space increases or decreases following the transformation given by that matrix. Not unreasonably, the YouTube comments of Sanderson’s video on the determinant are filled with people who are baffled as to why this isn’t typically mentioned when taught, since it’s such an intuitive concept. I can’t blame them. Thanks for reading all the way to the end of the blog! I’d love to hear any comments about the above analysis, or any of the concepts that the piece touches on. Feel free to leave a message below, or reach out to me through LinkedIn.
[ { "code": null, "e": 275, "s": 171, "text": "Here’s a quick maths question for you. Raise your hand if you can multiply these two matrices together:" }, { "code": null, "e": 304, "s": 275, "text": "Congratulations if you said:" }, { "code": null, "e": 379, "s": 304, "text": "Now keep your hand up if you know why. And by ‘why’, I don’t mean because:" }, { "code": null, "e": 537, "s": 379, "text": "Whilst mathematically true, this formula is more descriptive of ‘how’ than it is of ‘why’. In and of itself, this formula is pretty much devoid of intuition." }, { "code": null, "e": 849, "s": 537, "text": "And yet, this is how matrix multiplication is nearly always taught. Memorise the formula. Use it in an exam. Profit? This was certainly my experience, both when first learning linear algebra as a 16 year old, and then while attending an ostensibly world-leading university to study for my mathematics bachelors." }, { "code": null, "e": 931, "s": 849, "text": "Here’s another question for you: what is the determinant of the following matrix?" }, { "code": null, "e": 1102, "s": 931, "text": "Congratulations if you said 2. But you might be able to guess where I’m going with this. We know that for a 2x2 matrix, the determinant is given by the following formula:" }, { "code": null, "e": 1624, "s": 1102, "text": "But why? And for that matter, what even is the determinant? We are taught that it has a couple of useful properties (for example, a determinant of 0 is a red flag if you’re trying to solve systems of linear equations with row reduction). But in the two compulsory modules of linear algebra I took at university (an institution whose reputation, I suspect, relies on its excellence in research, rather than teaching), not once was the determinant of a matrix contextualised or explained at anything beyond a surface level." }, { "code": null, "e": 2136, "s": 1624, "text": "This slightly utilitarian attitude to teaching linear algebra is clearly problematic. Mathematics is a discipline that relies on an ‘incremental’ learning — gaining new knowledge often requires you to build upon what you already know. If your theoretical foundations are predicated on rote learning and plugging numbers into formulae, without a deeper appreciation and understanding of what’s actually going on, then they tend to fall down under the weight of something as heavy as, let’s say, machine learning." }, { "code": null, "e": 2525, "s": 2136, "text": "At this point, I’ll mention that this blog was heavily inspired by a series of videos made by Grant Sanderson (a.k.a. 3Blue1Brown). For those unfamiliar with his work, Sanderson creates really nicely animated videos in a way that makes complicated mathematical subjects accessible to the educated layman (his videos explaining neural networks and cryptocurrency are well worth your time)." }, { "code": null, "e": 2852, "s": 2525, "text": "At its core, Sanderson’s ‘Essence of Linear Algebra’ series seeks to introduce, motivate, and conceptualise many of the basic ideas around linear algebra in terms of linear transformations and their associated visualisations. As it turns out, this is a really helpful way to get your head around many of the core fundamentals." }, { "code": null, "e": 3052, "s": 2852, "text": "“The goal here is not to try to teach everything, it’s that you come away with a strong intuition... and that those intuitions make any future learning that you do more fruitful...” — Grant Sanderson" }, { "code": null, "e": 3276, "s": 3052, "text": "Before answering this question, let’s take a step back and think about what a linear transformation is. To keep things simple, let’s keep things in two dimensions (though the following applies to higher dimensions as well)." }, { "code": null, "e": 3394, "s": 3276, "text": "A linear transformation is a way of changing the shape of a ‘space’ (in this case, the 2D plane), in such a way that:" }, { "code": null, "e": 3424, "s": 3394, "text": "Keeps parallel lines parallel" }, { "code": null, "e": 3514, "s": 3424, "text": "Maintains an equal distance between parallel lines that were equally spaced to begin with" }, { "code": null, "e": 3546, "s": 3514, "text": "Leaves the origin at the origin" }, { "code": null, "e": 3644, "s": 3546, "text": "Broadly speaking, this gives us three different types of linear transformations that we could do:" }, { "code": null, "e": 3654, "s": 3644, "text": "Rotations" }, { "code": null, "e": 3835, "s": 3654, "text": "Scaling (reducing or increasing the space between parallel lines). Note — this also accounts for reflections in either of the x or y axes, these simply have negative scale factors." }, { "code": null, "e": 3910, "s": 3835, "text": "And sheers (note how this preserves equal distance between parallel lines)" }, { "code": null, "e": 4042, "s": 3910, "text": "Any combination of these three types of operation would also be a linear transformation on its own terms (more on this idea later)." }, { "code": null, "e": 4313, "s": 4042, "text": "Whilst these illustrations above are created to demonstrate the fact that a linear transformation affects the entirety of 2D space, it transpires that we can describe them in terms of what they do to the two ‘unit vectors’, called î (i-hat) and ĵ (j-hat) respectively." }, { "code": null, "e": 4578, "s": 4313, "text": "There’s more detail that one can go into, but in essence, this is driven by the fact that you can reach any point on the 2D plane with a linear combination of î and ĵ (for example, a vector v [3, -2] will simply be equivalent to 3 lots of î plus -2 lots of ĵ)." }, { "code": null, "e": 4818, "s": 4578, "text": "Suppose we want to think about a linear transformation that rotates everything counter-clockwise by a quarter turn. What becomes of our vector, v? It turns out we can describe what happens to v purely in terms of what happens to î and ĵ." }, { "code": null, "e": 5000, "s": 4818, "text": "Recall that v, [3, -2], was given as 3 lots of î plus -2 lots of ĵ. Well, it turns out that transformed v is equivalent to 3 lots of transformed î plus -2 lots of transformed ĵ." }, { "code": null, "e": 5033, "s": 5000, "text": "In Sanderson’s words, this line:" }, { "code": null, "e": 5071, "s": 5033, "text": "transformed_v = 3*[0,1] + (-2)*[-1,0]" }, { "code": null, "e": 5104, "s": 5071, "text": "is “where all the intuition is”." }, { "code": null, "e": 5347, "s": 5104, "text": "In particular, we can take the vectors of ‘transformed î’ and ‘transformed ĵ’, put them together to form a 2x2 matrix, refer back to this more ‘intuitive’ view of what happens to v, and all of a sudden we’ve justified vector multiplication." }, { "code": null, "e": 5426, "s": 5347, "text": "So what about the multiplication of two 2x2 matrices that we examined earlier?" }, { "code": null, "e": 5706, "s": 5426, "text": "We’ve just demonstrated that a 2x2 matrix will necessarily represent some kind of linear transformation in 2D space. In particular, for a given matrix [[a, b], [c, d]], the vectors [a, c] and [b, d] represent the coordinates of ‘transformed î’ and ‘transformed ĵ’ respectively." }, { "code": null, "e": 6163, "s": 5706, "text": "Suppose we want to make two linear transformations one after the other. For illustration, let’s suppose we perform the counter-clockwise quarter-turn that we looked at before, and follow this with a reflection in the x-axis. These two transformations can be both be represented by 2x2 matrices. We already know the matrix that represents the rotation, so what about the reflection? We can use the same technique as before — watch what happens to î and ĵ." }, { "code": null, "e": 6385, "s": 6163, "text": "Of course, î remains the same, and ĵ becomes negative. We’ve previously shown that we can put these ‘transformed î’ and ‘transformed ĵ’ vectors together to form the matrix representative of the overall transformation." }, { "code": null, "e": 6601, "s": 6385, "text": "So how can we think about the case when two transformations are performed one after another; first the rotation, then the reflection? We can approach this in the same way as before — watch what happens to î and ĵ." }, { "code": null, "e": 6996, "s": 6601, "text": "We know from before that the rotation takes î from [1, 0] to [0, 1]. If we then want to apply the reflection to this ‘transformed î’, we simply need to multiply the matrix representing this reflection by the vector representing ‘transformed î’, [0, 1] (recall — we’ve already shown that multiplying a transformation matrix by a vector describes what happens to that vector when transformed)." }, { "code": null, "e": 7076, "s": 6996, "text": "Of course, we now need to observe what happens to ĵ, using the same reasoning." }, { "code": null, "e": 7296, "s": 7076, "text": "Now that we know what happens to î and ĵ after they go through the rotation and reflection transformations one after another, we can put these two vectors together to describe the cumulative effect as a single matrix." }, { "code": null, "e": 7549, "s": 7296, "text": "Which looks an awful lot like a representation of our standard formula for matrix multiplication. Of course, you could try this thought experiment with any sequence of linear transformations. By following what happens to î and ĵ, you can effectively." }, { "code": null, "e": 7827, "s": 7549, "text": "It’s worth noting that, by thinking about matrix multiplication in terms of sequential linear transformations, it becomes quite easy to justify our standard rules of matrix multiplication. For three different matrices A, B, and C, think about why the following properties hold:" }, { "code": null, "e": 7838, "s": 7827, "text": "A*B ≠ B*A" }, { "code": null, "e": 7856, "s": 7838, "text": "A*(B*C) = (A*B)*C" }, { "code": null, "e": 7876, "s": 7856, "text": "A*(B+C) = A*B + A*C" }, { "code": null, "e": 8270, "s": 7876, "text": "Towards the start of the blog, I showed how to mechanically calculate the determinant. I then asked why the formula holds (and, for that matter, what the determinant even is). I cover this in another blog, but, spoiler alert, the determinant of a 2x2 matrix simply represents the scale by which a given area in 2D space increases or decreases following the transformation given by that matrix." }, { "code": null, "e": 8500, "s": 8270, "text": "Not unreasonably, the YouTube comments of Sanderson’s video on the determinant are filled with people who are baffled as to why this isn’t typically mentioned when taught, since it’s such an intuitive concept. I can’t blame them." } ]
MATLAB - Trapezoidal numerical integration without using trapz - GeeksforGeeks
04 Jul, 2021 Trapezoidal rule is utilized to discover the approximation of a definite integral. The main idea in the Trapezoidal rule is to accept the region under the graph of the given function to be a trapezoid rather than a rectangle shape and calculate its region. The formula for numerical integration using trapezoidal rule is: where h = (b-a)/n Now we take an example for calculating the area under the curve using 10 subintervals. Example: Matlab % MATLAB program for calculate the % area under the curve ∫_0^11/(1+x^2) dx % using 10 subintervals specify the variable% x as symbolic ones The syms function creates % a variable dynamically and automatically assigns% to a MATLAB variable with the same namesyms x % Lower Limita=0; % Upper Limitb=1; % Number of segmentsn=10; % Declare the functionf1=1/(1+x^2); % inline creates a function of% string containing in f1f=inline(f1); % h is the segment sizeh=(b - a)/n; % X stores the summation of first% and last segmentX=f(a)+f(b); % variable R stores the summation of% all the terms from 1 to n-1R=0;for i = 1:1:n-1 xi=a+(i*h); R=R+f(xi);end % Formula to calculate numerical integration% using Trapezoidal RuleI=(h/2)*(X+2*R); % Display the outputdisp('Area under the curve 1/(1+x^2) = ');disp(I); Output: Let’s take another example for calculating the area under the curve using 4 subintervals. Example: Matlab % MATLAB program for calculate% the area under the curve∫_0^1x^2 dx % using 4 subintervals.% specify the variable x as symbolic ones syms x % Lower Limita=0; % Upper Limitb=1; % Number of segmentsn=4; % Declare the functionf1=x^2; % inline creates a function of% string containing in f1f=inline(f1); % h is the segment sizeh=(b - a)/n;X=f(a)+f(b); % variable R stores the summation % of all the terms from 1 to n-1R=0;for i = 1:1:n-1 xi=a+(i*h); R=R+f(xi);end % Formula to calculate numerical% integration using Trapezoidal RuleI=(h/2)*(X+2*R); % Display the outputdisp('Area under the curve x^2 = ');disp(I); Output: MATLAB-Maths MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Forward and Inverse Fourier Transform of an Image in MATLAB How to Remove Noise from Digital Image in Frequency Domain Using MATLAB? Boundary Extraction of image using MATLAB How to Solve Histogram Equalization Numerical Problem in MATLAB? How to Normalize a Histogram in MATLAB? Double Integral in MATLAB How to Remove Salt and Pepper Noise from Image Using MATLAB? Classes and Object in MATLAB What are different types of denoising filters in MATLAB? How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?
[ { "code": null, "e": 25761, "s": 25733, "text": "\n04 Jul, 2021" }, { "code": null, "e": 26018, "s": 25761, "text": "Trapezoidal rule is utilized to discover the approximation of a definite integral. The main idea in the Trapezoidal rule is to accept the region under the graph of the given function to be a trapezoid rather than a rectangle shape and calculate its region." }, { "code": null, "e": 26083, "s": 26018, "text": "The formula for numerical integration using trapezoidal rule is:" }, { "code": null, "e": 26101, "s": 26083, "text": "where h = (b-a)/n" }, { "code": null, "e": 26188, "s": 26101, "text": "Now we take an example for calculating the area under the curve using 10 subintervals." }, { "code": null, "e": 26197, "s": 26188, "text": "Example:" }, { "code": null, "e": 26204, "s": 26197, "text": "Matlab" }, { "code": "% MATLAB program for calculate the % area under the curve ∫_0^11/(1+x^2) dx % using 10 subintervals specify the variable% x as symbolic ones The syms function creates % a variable dynamically and automatically assigns% to a MATLAB variable with the same namesyms x % Lower Limita=0; % Upper Limitb=1; % Number of segmentsn=10; % Declare the functionf1=1/(1+x^2); % inline creates a function of% string containing in f1f=inline(f1); % h is the segment sizeh=(b - a)/n; % X stores the summation of first% and last segmentX=f(a)+f(b); % variable R stores the summation of% all the terms from 1 to n-1R=0;for i = 1:1:n-1 xi=a+(i*h); R=R+f(xi);end % Formula to calculate numerical integration% using Trapezoidal RuleI=(h/2)*(X+2*R); % Display the outputdisp('Area under the curve 1/(1+x^2) = ');disp(I);", "e": 27026, "s": 26204, "text": null }, { "code": null, "e": 27034, "s": 27026, "text": "Output:" }, { "code": null, "e": 27125, "s": 27034, "text": "Let’s take another example for calculating the area under the curve using 4 subintervals." }, { "code": null, "e": 27134, "s": 27125, "text": "Example:" }, { "code": null, "e": 27141, "s": 27134, "text": "Matlab" }, { "code": "% MATLAB program for calculate% the area under the curve∫_0^1x^2 dx % using 4 subintervals.% specify the variable x as symbolic ones syms x % Lower Limita=0; % Upper Limitb=1; % Number of segmentsn=4; % Declare the functionf1=x^2; % inline creates a function of% string containing in f1f=inline(f1); % h is the segment sizeh=(b - a)/n;X=f(a)+f(b); % variable R stores the summation % of all the terms from 1 to n-1R=0;for i = 1:1:n-1 xi=a+(i*h); R=R+f(xi);end % Formula to calculate numerical% integration using Trapezoidal RuleI=(h/2)*(X+2*R); % Display the outputdisp('Area under the curve x^2 = ');disp(I);", "e": 27775, "s": 27141, "text": null }, { "code": null, "e": 27783, "s": 27775, "text": "Output:" }, { "code": null, "e": 27796, "s": 27783, "text": "MATLAB-Maths" }, { "code": null, "e": 27803, "s": 27796, "text": "MATLAB" }, { "code": null, "e": 27901, "s": 27803, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27961, "s": 27901, "text": "Forward and Inverse Fourier Transform of an Image in MATLAB" }, { "code": null, "e": 28034, "s": 27961, "text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?" }, { "code": null, "e": 28076, "s": 28034, "text": "Boundary Extraction of image using MATLAB" }, { "code": null, "e": 28141, "s": 28076, "text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?" }, { "code": null, "e": 28181, "s": 28141, "text": "How to Normalize a Histogram in MATLAB?" }, { "code": null, "e": 28207, "s": 28181, "text": "Double Integral in MATLAB" }, { "code": null, "e": 28268, "s": 28207, "text": "How to Remove Salt and Pepper Noise from Image Using MATLAB?" }, { "code": null, "e": 28297, "s": 28268, "text": "Classes and Object in MATLAB" }, { "code": null, "e": 28354, "s": 28297, "text": "What are different types of denoising filters in MATLAB?" } ]
PHP | Unset Session Variable - GeeksforGeeks
20 Jul, 2020 Whenever data are stored using cookies, there is a possibility of a hacker to insert some harmful data in the user’s computer to harm any application. So its always advisable to use PHP sessions to store information on the server than on a computer. Whenever data is needed across many pages of a website or application, PHP Session is used. This session creates a temporary file in a folder that stores registered variables with their values which are made available for the entire website. This Session ends when the user logs out of the site or browser. Every different user is given unique session IDs that are linked to an individual’s posts or emails. <?php session_start(); echo session_id(); ?> Note: The session IDs are randomly generated by the PHP engine which is difficult to make out. Example: The following PHP function unregisters or clears a session variable whenever $_SESSION is used in some code. It is mostly used for destroying a single session variable. Syntax: unset($_SESSION['variable_name']); unset($_SESSION['variable_name']); Program 1 :<!DOCTYPE html><html> <head> <style> body { width: 450px; height: 300px; margin: 10px; float: left; } .height { height: 10px; } </style></head> <body> <h1 style="color:green">GeeksforGeeks</h1> <b> PHP Unset session variables </b> <div class="height"> </div><?php // start a new session session_start(); // Check if the session name exists if( isset($_SESSION['name']) ) { echo 'Session name is set.'.'<br>'; } else { echo 'Please set the session name !'.'<br>'; } echo'<br>'; $_SESSION['name'] = 'John'; //unset($_SESSION['name']); echo "Session Name : ".$_SESSION['name'].'<br>'; ?> </body></html> <!DOCTYPE html><html> <head> <style> body { width: 450px; height: 300px; margin: 10px; float: left; } .height { height: 10px; } </style></head> <body> <h1 style="color:green">GeeksforGeeks</h1> <b> PHP Unset session variables </b> <div class="height"> </div><?php // start a new session session_start(); // Check if the session name exists if( isset($_SESSION['name']) ) { echo 'Session name is set.'.'<br>'; } else { echo 'Please set the session name !'.'<br>'; } echo'<br>'; $_SESSION['name'] = 'John'; //unset($_SESSION['name']); echo "Session Name : ".$_SESSION['name'].'<br>'; ?> </body></html> Output: When we comment on unset($_SESSION[‘name’]), then you get the following output . Note: The PHP session_start() function is always written in the beginning of any code. When we do unset($_SESSION[‘name’]), by un-commenting the required line in the example program, you get the following output. unset($_SESSION['name']); //echo "Session Name : ".$_SESSION['name']; unset($_SESSION['name']); //echo "Session Name : ".$_SESSION['name']; Output: If you want to destroy all the session variables, then use the following PHP function.session_destroy(); session_destroy(); If you want to clear or free up the space occupied by session variables for other use, the following PHP function is used.session_unset(); session_unset(); Program 2:<!DOCTYPE html><html> <head> <title>Unset Session Variable </title></head> <body> <h1 style="color:green">GeeksforGeeks</h1> <b> Unset previous session of user</b> <?php echo '<br>'; echo '<br>'; if(isset($_SESSION["user_name"])) { echo "Welcome "; echo $_SESSION["user_name"]; } ?> <form> Input your name here: <input type="text" id="user_id" name="user_id"> <input type=submit value=Submit> </form> <form action="#"> <input type="submit" name="submit" value="Unset" onclick="UnsetPreviousSession()"> </form> <?php session_start(); if(!isset($_SESSION["user_name"]) && (!empty($_GET['user_id']))) { $_SESSION["user_name"] = $_GET["user_id"]; } else { UnsetPreviousSession(); } function UnsetPreviousSession() { unset($_SESSION['user_name']); } ?></body> </html> <!DOCTYPE html><html> <head> <title>Unset Session Variable </title></head> <body> <h1 style="color:green">GeeksforGeeks</h1> <b> Unset previous session of user</b> <?php echo '<br>'; echo '<br>'; if(isset($_SESSION["user_name"])) { echo "Welcome "; echo $_SESSION["user_name"]; } ?> <form> Input your name here: <input type="text" id="user_id" name="user_id"> <input type=submit value=Submit> </form> <form action="#"> <input type="submit" name="submit" value="Unset" onclick="UnsetPreviousSession()"> </form> <?php session_start(); if(!isset($_SESSION["user_name"]) && (!empty($_GET['user_id']))) { $_SESSION["user_name"] = $_GET["user_id"]; } else { UnsetPreviousSession(); } function UnsetPreviousSession() { unset($_SESSION['user_name']); } ?></body> </html> Output: After clicking the Unset button, the following output screen is visible for re-entry which shows the previous session variable is unset. Akanksha_Rai PHP-Misc Picked PHP Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? PHP | Converting string to Date and DateTime Comparing two dates in PHP How to pass JavaScript variables to PHP ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26693, "s": 26665, "text": "\n20 Jul, 2020" }, { "code": null, "e": 27035, "s": 26693, "text": "Whenever data are stored using cookies, there is a possibility of a hacker to insert some harmful data in the user’s computer to harm any application. So its always advisable to use PHP sessions to store information on the server than on a computer. Whenever data is needed across many pages of a website or application, PHP Session is used." }, { "code": null, "e": 27351, "s": 27035, "text": "This session creates a temporary file in a folder that stores registered variables with their values which are made available for the entire website. This Session ends when the user logs out of the site or browser. Every different user is given unique session IDs that are linked to an individual’s posts or emails." }, { "code": null, "e": 27400, "s": 27351, "text": "<?php\n session_start();\n echo session_id();\n?>" }, { "code": null, "e": 27495, "s": 27400, "text": "Note: The session IDs are randomly generated by the PHP engine which is difficult to make out." }, { "code": null, "e": 27673, "s": 27495, "text": "Example: The following PHP function unregisters or clears a session variable whenever $_SESSION is used in some code. It is mostly used for destroying a single session variable." }, { "code": null, "e": 27718, "s": 27673, "text": "Syntax: unset($_SESSION['variable_name']);\n" }, { "code": null, "e": 27756, "s": 27718, "text": " unset($_SESSION['variable_name']);\n" }, { "code": null, "e": 28512, "s": 27756, "text": "Program 1 :<!DOCTYPE html><html> <head> <style> body { width: 450px; height: 300px; margin: 10px; float: left; } .height { height: 10px; } </style></head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <b> PHP Unset session variables </b> <div class=\"height\"> </div><?php // start a new session session_start(); // Check if the session name exists if( isset($_SESSION['name']) ) { echo 'Session name is set.'.'<br>'; } else { echo 'Please set the session name !'.'<br>'; } echo'<br>'; $_SESSION['name'] = 'John'; //unset($_SESSION['name']); echo \"Session Name : \".$_SESSION['name'].'<br>'; ?> </body></html>" }, { "code": "<!DOCTYPE html><html> <head> <style> body { width: 450px; height: 300px; margin: 10px; float: left; } .height { height: 10px; } </style></head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <b> PHP Unset session variables </b> <div class=\"height\"> </div><?php // start a new session session_start(); // Check if the session name exists if( isset($_SESSION['name']) ) { echo 'Session name is set.'.'<br>'; } else { echo 'Please set the session name !'.'<br>'; } echo'<br>'; $_SESSION['name'] = 'John'; //unset($_SESSION['name']); echo \"Session Name : \".$_SESSION['name'].'<br>'; ?> </body></html>", "e": 29257, "s": 28512, "text": null }, { "code": null, "e": 29346, "s": 29257, "text": "Output: When we comment on unset($_SESSION[‘name’]), then you get the following output ." }, { "code": null, "e": 29433, "s": 29346, "text": "Note: The PHP session_start() function is always written in the beginning of any code." }, { "code": null, "e": 29641, "s": 29433, "text": "When we do unset($_SESSION[‘name’]), by un-commenting the required line in the example program, you get the following output. unset($_SESSION['name']); \n //echo \"Session Name : \".$_SESSION['name']; \n" }, { "code": null, "e": 29724, "s": 29641, "text": " unset($_SESSION['name']); \n //echo \"Session Name : \".$_SESSION['name']; \n" }, { "code": null, "e": 29732, "s": 29724, "text": "Output:" }, { "code": null, "e": 29837, "s": 29732, "text": "If you want to destroy all the session variables, then use the following PHP function.session_destroy();" }, { "code": null, "e": 29856, "s": 29837, "text": "session_destroy();" }, { "code": null, "e": 29995, "s": 29856, "text": "If you want to clear or free up the space occupied by session variables for other use, the following PHP function is used.session_unset();" }, { "code": null, "e": 30012, "s": 29995, "text": "session_unset();" }, { "code": null, "e": 30995, "s": 30012, "text": "Program 2:<!DOCTYPE html><html> <head> <title>Unset Session Variable </title></head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <b> Unset previous session of user</b> <?php echo '<br>'; echo '<br>'; if(isset($_SESSION[\"user_name\"])) { echo \"Welcome \"; echo $_SESSION[\"user_name\"]; } ?> <form> Input your name here: <input type=\"text\" id=\"user_id\" name=\"user_id\"> <input type=submit value=Submit> </form> <form action=\"#\"> <input type=\"submit\" name=\"submit\" value=\"Unset\" onclick=\"UnsetPreviousSession()\"> </form> <?php session_start(); if(!isset($_SESSION[\"user_name\"]) && (!empty($_GET['user_id']))) { $_SESSION[\"user_name\"] = $_GET[\"user_id\"]; } else { UnsetPreviousSession(); } function UnsetPreviousSession() { unset($_SESSION['user_name']); } ?></body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title>Unset Session Variable </title></head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <b> Unset previous session of user</b> <?php echo '<br>'; echo '<br>'; if(isset($_SESSION[\"user_name\"])) { echo \"Welcome \"; echo $_SESSION[\"user_name\"]; } ?> <form> Input your name here: <input type=\"text\" id=\"user_id\" name=\"user_id\"> <input type=submit value=Submit> </form> <form action=\"#\"> <input type=\"submit\" name=\"submit\" value=\"Unset\" onclick=\"UnsetPreviousSession()\"> </form> <?php session_start(); if(!isset($_SESSION[\"user_name\"]) && (!empty($_GET['user_id']))) { $_SESSION[\"user_name\"] = $_GET[\"user_id\"]; } else { UnsetPreviousSession(); } function UnsetPreviousSession() { unset($_SESSION['user_name']); } ?></body> </html>", "e": 31968, "s": 30995, "text": null }, { "code": null, "e": 32113, "s": 31968, "text": "Output: After clicking the Unset button, the following output screen is visible for re-entry which shows the previous session variable is unset." }, { "code": null, "e": 32126, "s": 32113, "text": "Akanksha_Rai" }, { "code": null, "e": 32135, "s": 32126, "text": "PHP-Misc" }, { "code": null, "e": 32142, "s": 32135, "text": "Picked" }, { "code": null, "e": 32146, "s": 32142, "text": "PHP" }, { "code": null, "e": 32163, "s": 32146, "text": "Web Technologies" }, { "code": null, "e": 32190, "s": 32163, "text": "Web technologies Questions" }, { "code": null, "e": 32194, "s": 32190, "text": "PHP" }, { "code": null, "e": 32292, "s": 32194, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32342, "s": 32292, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 32382, "s": 32342, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 32427, "s": 32382, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 32454, "s": 32427, "text": "Comparing two dates in PHP" }, { "code": null, "e": 32496, "s": 32454, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 32536, "s": 32496, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32569, "s": 32536, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32614, "s": 32569, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32657, "s": 32614, "text": "How to fetch data from an API in ReactJS ?" } ]
Python - Install Paramiko on Windows and Linux - GeeksforGeeks
28 Jan, 2022 The high-level python API starts with the creation of a secure connection object. To have more direct control and pass a socket to transport to start remote access. As a client, it’s authenticating using a user credential or private key, and checking the server’s host key. Paramiko is a Python library that makes a connection with a remote device through SSh. Paramiko is using SSH2 as a replacement of SSL to make a secure connection between two devices. It also supports the SFTP client and server model. To install Paramiko on Windows using pip run bellow command on cmd. pip install paramiko Output: To check the installed paramiko run the following: pip list Output: Install paramiko using .whl file offline. To download .whl file https://pypi.org/project/paramiko/#files pip install paramiko-2.7.2-py2.py3-none-any.whl Output : Python paramiko can be installed on Linux in many ways, using pip is one of them. pip install paramiko Output : To check the installed paramiko: pip list --format=json Output: saurabh1990aror how-to-install python-modules Installation Guide Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Install Anaconda on Windows? How to Install and Run Apache Kafka on Windows? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS? Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Taking input in Python
[ { "code": null, "e": 25419, "s": 25391, "text": "\n28 Jan, 2022" }, { "code": null, "e": 25694, "s": 25419, "text": "The high-level python API starts with the creation of a secure connection object. To have more direct control and pass a socket to transport to start remote access. As a client, it’s authenticating using a user credential or private key, and checking the server’s host key. " }, { "code": null, "e": 25928, "s": 25694, "text": "Paramiko is a Python library that makes a connection with a remote device through SSh. Paramiko is using SSH2 as a replacement of SSL to make a secure connection between two devices. It also supports the SFTP client and server model." }, { "code": null, "e": 25996, "s": 25928, "text": "To install Paramiko on Windows using pip run bellow command on cmd." }, { "code": null, "e": 26017, "s": 25996, "text": "pip install paramiko" }, { "code": null, "e": 26025, "s": 26017, "text": "Output:" }, { "code": null, "e": 26076, "s": 26025, "text": "To check the installed paramiko run the following:" }, { "code": null, "e": 26085, "s": 26076, "text": "pip list" }, { "code": null, "e": 26093, "s": 26085, "text": "Output:" }, { "code": null, "e": 26198, "s": 26093, "text": "Install paramiko using .whl file offline. To download .whl file https://pypi.org/project/paramiko/#files" }, { "code": null, "e": 26246, "s": 26198, "text": "pip install paramiko-2.7.2-py2.py3-none-any.whl" }, { "code": null, "e": 26255, "s": 26246, "text": "Output :" }, { "code": null, "e": 26337, "s": 26255, "text": "Python paramiko can be installed on Linux in many ways, using pip is one of them." }, { "code": null, "e": 26358, "s": 26337, "text": "pip install paramiko" }, { "code": null, "e": 26367, "s": 26358, "text": "Output :" }, { "code": null, "e": 26400, "s": 26367, "text": "To check the installed paramiko:" }, { "code": null, "e": 26423, "s": 26400, "text": "pip list --format=json" }, { "code": null, "e": 26431, "s": 26423, "text": "Output:" }, { "code": null, "e": 26447, "s": 26431, "text": "saurabh1990aror" }, { "code": null, "e": 26462, "s": 26447, "text": "how-to-install" }, { "code": null, "e": 26477, "s": 26462, "text": "python-modules" }, { "code": null, "e": 26496, "s": 26477, "text": "Installation Guide" }, { "code": null, "e": 26503, "s": 26496, "text": "Python" }, { "code": null, "e": 26601, "s": 26503, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26635, "s": 26601, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 26671, "s": 26635, "text": "How to Install Anaconda on Windows?" }, { "code": null, "e": 26719, "s": 26671, "text": "How to Install and Run Apache Kafka on Windows?" }, { "code": null, "e": 26777, "s": 26719, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 26819, "s": 26777, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 26847, "s": 26819, "text": "Read JSON file using Python" }, { "code": null, "e": 26897, "s": 26847, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 26919, "s": 26897, "text": "Python map() function" }, { "code": null, "e": 26963, "s": 26919, "text": "How to get column names in Pandas dataframe" } ]
Minimum number of flips with rotation to make binary string alternating - GeeksforGeeks
30 Nov, 2021 Given a binary string S of 0s and 1s. The task is to make the given string a sequence of alternate characters by using the below operations: Remove some prefix from the start and append it to the end. Flip some or every bit in the given string. Print the minimum number of bits to be flipped to make the given string alternating. Examples: Input: S = “001”Output: 0Explanation:No need to flip any element we can get alternating sequence by using left rotation: 010. Input: S = “000001100”Output: 3Explanation:Following steps to find minimum flips to get alternating string:1. After rotating string 6 times towards left we will get: 100000001 2. Now we can apply flip operation as following: 101000001 -> 101010001 -> 101010101Thus, minimum flips to make string alternating is 3. Naive Approach: The naive approach is to take all N possible combinations and calculate the minimum number of bits To flip in each of those strings. Print the minimum count among all such combinations.Time Complexity: O(N2), where N is the length of the string.Auxiliary Space: O(N) Efficient Approach: This can be solved by observing that the final string will be either of type “101010...” or “010101...” such that all 1s will either be at odd positions or at even positions. Follow the below steps to solve the problem: Create a prefix sum array where pref[i] means a number of changes required until index i.Create prefix arrays for both the above patterns.Check for every i, if substring[0, i] is appended at the end how many characters to be flipped required.Print the minimum number of flips among all the substrings in the above steps. Create a prefix sum array where pref[i] means a number of changes required until index i. Create prefix arrays for both the above patterns. Check for every i, if substring[0, i] is appended at the end how many characters to be flipped required. Print the minimum number of flips among all the substrings in the above steps. Why only odd length strings are considered for rotation and why rotation will have no effect on even length string? I’ll try to explain this with the below example, Suppose you have the sequence 011000 which is of even length. Without rotation, you can change it to 010101 or 101010. Now suppose you choose to append 01 at the end. The sequence becomes 100001 which can be changed to 010101 or 101010. If you compare each character, you will see that this is the same case as that of without rotation. 1000 corresponds to either 0101 or 1010 in both cases and 01 to 01 or 10. But now consider an odd length case, 01100. Without rotation, you can change it to 01010 or 10101. Now suppose you choose to append 01 at the end. The sequence becomes 10001 which can be changed to 01010 or 10101. Now if you compare each character, you will see that 100 corresponds to 010 or 101 in both cases but 01 corresponds to 01 when 100 is 010 in case of no rotation and 101 in case of rotation. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that finds the minimum// number of flips to make the// binary string alternating if// left circular rotation is allowedint MinimumFlips(string s, int n){ int a[n]; for(int i = 0; i < n; i++) { a[i] = (s[i] == '1' ? 1 : 0); } // Initialize prefix arrays to store // number of changes required to put // 1s at either even or odd position int oddone[n + 1]; int evenone[n + 1]; oddone[0] = 0; evenone[0] = 0; for(int i = 0; i < n; i++) { // If i is odd if (i % 2 != 0) { // Update the oddone // and evenone count oddone[i + 1] = oddone[i] + (a[i] == 1 ? 1 : 0); evenone[i + 1] = evenone[i] + (a[i] == 0 ? 1 : 0); } // Else i is even else { // Update the oddone // and evenone count oddone[i + 1] = oddone[i] + (a[i] == 0 ? 1 : 0); evenone[i + 1] = evenone[i] + (a[i] == 1 ? 1 : 0); } } // Initialize minimum flips int minimum = min(oddone[n], evenone[n]); // Check if substring[0, i] is // appended at end how many // changes will be required for(int i = 0; i < n; i++) { if (n % 2 != 0) { minimum = min(minimum, oddone[n] - oddone[i + 1] + evenone[i + 1]); minimum = min(minimum, evenone[n] - evenone[i + 1] + oddone[i + 1]); } } // Return minimum flips return minimum;} // Driver Codeint main(){ // Given String string S = "000001100"; // Length of given string int n = S.length(); // Function call cout << (MinimumFlips(S, n));} // This code is contributed by chitranayal // Java program for the above approachimport java.util.*; class GFG { // Function that finds the minimum // number of flips to make the // binary string alternating if // left circular rotation is allowed static int MinimumFlips(String s, int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = (s.charAt(i) == '1' ? 1 : 0); } // Initialize prefix arrays to store // number of changes required to put // 1s at either even or odd position int[] oddone = new int[n + 1]; int[] evenone = new int[n + 1]; oddone[0] = 0; evenone[0] = 0; for (int i = 0; i < n; i++) { // If i is odd if (i % 2 != 0) { // Update the oddone // and evenone count oddone[i + 1] = oddone[i] + (a[i] == 1 ? 1 : 0); evenone[i + 1] = evenone[i] + (a[i] == 0 ? 1 : 0); } // Else i is even else { // Update the oddone // and evenone count oddone[i + 1] = oddone[i] + (a[i] == 0 ? 1 : 0); evenone[i + 1] = evenone[i] + (a[i] == 1 ? 1 : 0); } } // Initialize minimum flips int minimum = Math.min(oddone[n], evenone[n]); // Check if substring[0, i] is // appended at end how many // changes will be required for (int i = 0; i < n; i++) { if (n % 2 != 0) { minimum = Math.min(minimum, oddone[n] - oddone[i + 1] + evenone[i + 1]); minimum = Math.min(minimum, evenone[n] - evenone[i + 1] + oddone[i + 1]); } } // Return minimum flips return minimum; } // Driver Code public static void main(String[] args) { // Given String String S = "000001100"; // Length of given string int n = S.length(); // Function call System.out.print(MinimumFlips(S, n)); }} # Python3 program for the above approach # Function that finds the minimum# number of flips to make the# binary string alternating if# left circular rotation is alloweddef MinimumFlips(s, n): a = [0] * n for i in range(n): a[i] = 1 if s[i] == '1' else 0 # Initialize prefix arrays to store # number of changes required to put # 1s at either even or odd position oddone = [0] * (n + 1) evenone = [0] * (n + 1) for i in range(n): # If i is odd if(i % 2 != 0): # Update the oddone # and evenone count if(a[i] == 1): oddone[i + 1] = oddone[i] + 1 else: oddone[i + 1] = oddone[i] + 0 if(a[i] == 0): evenone[i + 1] = evenone[i] + 1 else: evenone[i + 1] = evenone[i] + 0 # Else i is even else: # Update the oddone # and evenone count if (a[i] == 0): oddone[i + 1] = oddone[i] + 1 else: oddone[i + 1] = oddone[i] + 0 if (a[i] == 1): evenone[i + 1] = evenone[i] + 1 else: evenone[i + 1] = evenone[i] + 0 # Initialize minimum flips minimum = min(oddone[n], evenone[n]) # Check if substring[0, i] is # appended at end how many # changes will be required for i in range(n): if(n % 2 != 0): minimum = min(minimum, oddone[n] - oddone[i + 1] + evenone[i + 1]) minimum = min(minimum, evenone[n] - evenone[i + 1] + oddone[i + 1]) # Return minimum flips return minimum # Driver Code # Given StringS = "000001100" # Length of given stringn = len(S) # Function callprint(MinimumFlips(S, n)) # This code is contributed by Shivam Singh // C# program for the above approachusing System;class GFG{ // Function that finds the minimum // number of flips to make the // binary string alternating if // left circular rotation is allowed static int MinimumFlips(String s, int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = (s[i] == '1' ? 1 : 0); } // Initialize prefix arrays to store // number of changes required to put // 1s at either even or odd position int[] oddone = new int[n + 1]; int[] evenone = new int[n + 1]; oddone[0] = 0; evenone[0] = 0; for (int i = 0; i < n; i++) { // If i is odd if (i % 2 != 0) { // Update the oddone // and evenone count oddone[i + 1] = oddone[i] + (a[i] == 1 ? 1 : 0); evenone[i + 1] = evenone[i] + (a[i] == 0 ? 1 : 0); } // Else i is even else { // Update the oddone // and evenone count oddone[i + 1] = oddone[i] + (a[i] == 0 ? 1 : 0); evenone[i + 1] = evenone[i] + (a[i] == 1 ? 1 : 0); } } // Initialize minimum flips int minimum = Math.Min(oddone[n], evenone[n]); // Check if substring[0, i] is // appended at end how many // changes will be required for (int i = 0; i < n; i++) { if (n % 2 != 0) { minimum = Math.Min(minimum, oddone[n] - oddone[i + 1] + evenone[i + 1]); minimum = Math.Min(minimum, evenone[n] - evenone[i + 1] + oddone[i + 1]); } } // Return minimum flips return minimum; } // Driver Code public static void Main(String[] args) { // Given String String S = "000001100"; // Length of given string int n = S.Length; // Function call Console.Write(MinimumFlips(S, n)); }} // This code is contributed by Rajput-Ji <script>// JavaScript program for the// above approach // Function that finds the minimum // number of flips to make the // binary string alternating if // left circular rotation is allowed function MinimumFlips(s, n) { let a = Array.from({length: n+1}, (_, i) => 0); for (let i = 0; i < n; i++) { a[i] = (s[i] == '1' ? 1 : 0); } // Initialize prefix arrays to store // number of changes required to put // 1s at either even or odd position let oddone = Array.from({length: n+1}, (_, i) => 0); let evenone = Array.from({length: n+1}, (_, i) => 0); oddone[0] = 0; evenone[0] = 0; for (let i = 0; i < n; i++) { // If i is odd if (i % 2 != 0) { // Update the oddone // and evenone count oddone[i + 1] = oddone[i] + (a[i] == 1 ? 1 : 0); evenone[i + 1] = evenone[i] + (a[i] == 0 ? 1 : 0); } // Else i is even else { // Update the oddone // and evenone count oddone[i + 1] = oddone[i] + (a[i] == 0 ? 1 : 0); evenone[i + 1] = evenone[i] + (a[i] == 1 ? 1 : 0); } } // Initialize minimum flips let minimum = Math.min(oddone[n], evenone[n]); // Check if substring[0, i] is // appended at end how many // changes will be required for (let i = 0; i < n; i++) { if (n % 2 != 0) { minimum = Math.min(minimum, oddone[n] - oddone[i + 1] + evenone[i + 1]); minimum = Math.min(minimum, evenone[n] - evenone[i + 1] + oddone[i + 1]); } } // Return minimum flips return minimum; } // Driver Code // Given String let S = "000001100"; // Length of given string let n = S.length; // Function call document.write(MinimumFlips(S, n)); </script> 3 Time Complexity: O(N), where N is the length of the given string.Auxiliary Space: O(N) SHIVAMSINGH67 ukasp Rajput-Ji susmitakundugoaldanga sahil9420 binary-string Google Greedy Mathematical Strings Google Strings Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Huffman Coding | Greedy Algo-3 Coin Change | DP-7 Activity Selection Problem | Greedy Algo-1 Fractional Knapsack Problem Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7 Merge two sorted arrays
[ { "code": null, "e": 26653, "s": 26625, "text": "\n30 Nov, 2021" }, { "code": null, "e": 26794, "s": 26653, "text": "Given a binary string S of 0s and 1s. The task is to make the given string a sequence of alternate characters by using the below operations:" }, { "code": null, "e": 26854, "s": 26794, "text": "Remove some prefix from the start and append it to the end." }, { "code": null, "e": 26898, "s": 26854, "text": "Flip some or every bit in the given string." }, { "code": null, "e": 26983, "s": 26898, "text": "Print the minimum number of bits to be flipped to make the given string alternating." }, { "code": null, "e": 26993, "s": 26983, "text": "Examples:" }, { "code": null, "e": 27119, "s": 26993, "text": "Input: S = “001”Output: 0Explanation:No need to flip any element we can get alternating sequence by using left rotation: 010." }, { "code": null, "e": 27432, "s": 27119, "text": "Input: S = “000001100”Output: 3Explanation:Following steps to find minimum flips to get alternating string:1. After rotating string 6 times towards left we will get: 100000001 2. Now we can apply flip operation as following: 101000001 -> 101010001 -> 101010101Thus, minimum flips to make string alternating is 3." }, { "code": null, "e": 27715, "s": 27432, "text": "Naive Approach: The naive approach is to take all N possible combinations and calculate the minimum number of bits To flip in each of those strings. Print the minimum count among all such combinations.Time Complexity: O(N2), where N is the length of the string.Auxiliary Space: O(N)" }, { "code": null, "e": 27955, "s": 27715, "text": "Efficient Approach: This can be solved by observing that the final string will be either of type “101010...” or “010101...” such that all 1s will either be at odd positions or at even positions. Follow the below steps to solve the problem:" }, { "code": null, "e": 28276, "s": 27955, "text": "Create a prefix sum array where pref[i] means a number of changes required until index i.Create prefix arrays for both the above patterns.Check for every i, if substring[0, i] is appended at the end how many characters to be flipped required.Print the minimum number of flips among all the substrings in the above steps." }, { "code": null, "e": 28366, "s": 28276, "text": "Create a prefix sum array where pref[i] means a number of changes required until index i." }, { "code": null, "e": 28416, "s": 28366, "text": "Create prefix arrays for both the above patterns." }, { "code": null, "e": 28521, "s": 28416, "text": "Check for every i, if substring[0, i] is appended at the end how many characters to be flipped required." }, { "code": null, "e": 28600, "s": 28521, "text": "Print the minimum number of flips among all the substrings in the above steps." }, { "code": null, "e": 28717, "s": 28600, "text": "Why only odd length strings are considered for rotation and why rotation will have no effect on even length string? " }, { "code": null, "e": 28766, "s": 28717, "text": "I’ll try to explain this with the below example," }, { "code": null, "e": 29177, "s": 28766, "text": "Suppose you have the sequence 011000 which is of even length. Without rotation, you can change it to 010101 or 101010. Now suppose you choose to append 01 at the end. The sequence becomes 100001 which can be changed to 010101 or 101010. If you compare each character, you will see that this is the same case as that of without rotation. 1000 corresponds to either 0101 or 1010 in both cases and 01 to 01 or 10." }, { "code": null, "e": 29581, "s": 29177, "text": "But now consider an odd length case, 01100. Without rotation, you can change it to 01010 or 10101. Now suppose you choose to append 01 at the end. The sequence becomes 10001 which can be changed to 01010 or 10101. Now if you compare each character, you will see that 100 corresponds to 010 or 101 in both cases but 01 corresponds to 01 when 100 is 010 in case of no rotation and 101 in case of rotation." }, { "code": null, "e": 29632, "s": 29581, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 29636, "s": 29632, "text": "C++" }, { "code": null, "e": 29641, "s": 29636, "text": "Java" }, { "code": null, "e": 29649, "s": 29641, "text": "Python3" }, { "code": null, "e": 29652, "s": 29649, "text": "C#" }, { "code": null, "e": 29663, "s": 29652, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that finds the minimum// number of flips to make the// binary string alternating if// left circular rotation is allowedint MinimumFlips(string s, int n){ int a[n]; for(int i = 0; i < n; i++) { a[i] = (s[i] == '1' ? 1 : 0); } // Initialize prefix arrays to store // number of changes required to put // 1s at either even or odd position int oddone[n + 1]; int evenone[n + 1]; oddone[0] = 0; evenone[0] = 0; for(int i = 0; i < n; i++) { // If i is odd if (i % 2 != 0) { // Update the oddone // and evenone count oddone[i + 1] = oddone[i] + (a[i] == 1 ? 1 : 0); evenone[i + 1] = evenone[i] + (a[i] == 0 ? 1 : 0); } // Else i is even else { // Update the oddone // and evenone count oddone[i + 1] = oddone[i] + (a[i] == 0 ? 1 : 0); evenone[i + 1] = evenone[i] + (a[i] == 1 ? 1 : 0); } } // Initialize minimum flips int minimum = min(oddone[n], evenone[n]); // Check if substring[0, i] is // appended at end how many // changes will be required for(int i = 0; i < n; i++) { if (n % 2 != 0) { minimum = min(minimum, oddone[n] - oddone[i + 1] + evenone[i + 1]); minimum = min(minimum, evenone[n] - evenone[i + 1] + oddone[i + 1]); } } // Return minimum flips return minimum;} // Driver Codeint main(){ // Given String string S = \"000001100\"; // Length of given string int n = S.length(); // Function call cout << (MinimumFlips(S, n));} // This code is contributed by chitranayal", "e": 31741, "s": 29663, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG { // Function that finds the minimum // number of flips to make the // binary string alternating if // left circular rotation is allowed static int MinimumFlips(String s, int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = (s.charAt(i) == '1' ? 1 : 0); } // Initialize prefix arrays to store // number of changes required to put // 1s at either even or odd position int[] oddone = new int[n + 1]; int[] evenone = new int[n + 1]; oddone[0] = 0; evenone[0] = 0; for (int i = 0; i < n; i++) { // If i is odd if (i % 2 != 0) { // Update the oddone // and evenone count oddone[i + 1] = oddone[i] + (a[i] == 1 ? 1 : 0); evenone[i + 1] = evenone[i] + (a[i] == 0 ? 1 : 0); } // Else i is even else { // Update the oddone // and evenone count oddone[i + 1] = oddone[i] + (a[i] == 0 ? 1 : 0); evenone[i + 1] = evenone[i] + (a[i] == 1 ? 1 : 0); } } // Initialize minimum flips int minimum = Math.min(oddone[n], evenone[n]); // Check if substring[0, i] is // appended at end how many // changes will be required for (int i = 0; i < n; i++) { if (n % 2 != 0) { minimum = Math.min(minimum, oddone[n] - oddone[i + 1] + evenone[i + 1]); minimum = Math.min(minimum, evenone[n] - evenone[i + 1] + oddone[i + 1]); } } // Return minimum flips return minimum; } // Driver Code public static void main(String[] args) { // Given String String S = \"000001100\"; // Length of given string int n = S.length(); // Function call System.out.print(MinimumFlips(S, n)); }}", "e": 34162, "s": 31741, "text": null }, { "code": "# Python3 program for the above approach # Function that finds the minimum# number of flips to make the# binary string alternating if# left circular rotation is alloweddef MinimumFlips(s, n): a = [0] * n for i in range(n): a[i] = 1 if s[i] == '1' else 0 # Initialize prefix arrays to store # number of changes required to put # 1s at either even or odd position oddone = [0] * (n + 1) evenone = [0] * (n + 1) for i in range(n): # If i is odd if(i % 2 != 0): # Update the oddone # and evenone count if(a[i] == 1): oddone[i + 1] = oddone[i] + 1 else: oddone[i + 1] = oddone[i] + 0 if(a[i] == 0): evenone[i + 1] = evenone[i] + 1 else: evenone[i + 1] = evenone[i] + 0 # Else i is even else: # Update the oddone # and evenone count if (a[i] == 0): oddone[i + 1] = oddone[i] + 1 else: oddone[i + 1] = oddone[i] + 0 if (a[i] == 1): evenone[i + 1] = evenone[i] + 1 else: evenone[i + 1] = evenone[i] + 0 # Initialize minimum flips minimum = min(oddone[n], evenone[n]) # Check if substring[0, i] is # appended at end how many # changes will be required for i in range(n): if(n % 2 != 0): minimum = min(minimum, oddone[n] - oddone[i + 1] + evenone[i + 1]) minimum = min(minimum, evenone[n] - evenone[i + 1] + oddone[i + 1]) # Return minimum flips return minimum # Driver Code # Given StringS = \"000001100\" # Length of given stringn = len(S) # Function callprint(MinimumFlips(S, n)) # This code is contributed by Shivam Singh", "e": 36104, "s": 34162, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function that finds the minimum // number of flips to make the // binary string alternating if // left circular rotation is allowed static int MinimumFlips(String s, int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = (s[i] == '1' ? 1 : 0); } // Initialize prefix arrays to store // number of changes required to put // 1s at either even or odd position int[] oddone = new int[n + 1]; int[] evenone = new int[n + 1]; oddone[0] = 0; evenone[0] = 0; for (int i = 0; i < n; i++) { // If i is odd if (i % 2 != 0) { // Update the oddone // and evenone count oddone[i + 1] = oddone[i] + (a[i] == 1 ? 1 : 0); evenone[i + 1] = evenone[i] + (a[i] == 0 ? 1 : 0); } // Else i is even else { // Update the oddone // and evenone count oddone[i + 1] = oddone[i] + (a[i] == 0 ? 1 : 0); evenone[i + 1] = evenone[i] + (a[i] == 1 ? 1 : 0); } } // Initialize minimum flips int minimum = Math.Min(oddone[n], evenone[n]); // Check if substring[0, i] is // appended at end how many // changes will be required for (int i = 0; i < n; i++) { if (n % 2 != 0) { minimum = Math.Min(minimum, oddone[n] - oddone[i + 1] + evenone[i + 1]); minimum = Math.Min(minimum, evenone[n] - evenone[i + 1] + oddone[i + 1]); } } // Return minimum flips return minimum; } // Driver Code public static void Main(String[] args) { // Given String String S = \"000001100\"; // Length of given string int n = S.Length; // Function call Console.Write(MinimumFlips(S, n)); }} // This code is contributed by Rajput-Ji", "e": 38167, "s": 36104, "text": null }, { "code": "<script>// JavaScript program for the// above approach // Function that finds the minimum // number of flips to make the // binary string alternating if // left circular rotation is allowed function MinimumFlips(s, n) { let a = Array.from({length: n+1}, (_, i) => 0); for (let i = 0; i < n; i++) { a[i] = (s[i] == '1' ? 1 : 0); } // Initialize prefix arrays to store // number of changes required to put // 1s at either even or odd position let oddone = Array.from({length: n+1}, (_, i) => 0); let evenone = Array.from({length: n+1}, (_, i) => 0); oddone[0] = 0; evenone[0] = 0; for (let i = 0; i < n; i++) { // If i is odd if (i % 2 != 0) { // Update the oddone // and evenone count oddone[i + 1] = oddone[i] + (a[i] == 1 ? 1 : 0); evenone[i + 1] = evenone[i] + (a[i] == 0 ? 1 : 0); } // Else i is even else { // Update the oddone // and evenone count oddone[i + 1] = oddone[i] + (a[i] == 0 ? 1 : 0); evenone[i + 1] = evenone[i] + (a[i] == 1 ? 1 : 0); } } // Initialize minimum flips let minimum = Math.min(oddone[n], evenone[n]); // Check if substring[0, i] is // appended at end how many // changes will be required for (let i = 0; i < n; i++) { if (n % 2 != 0) { minimum = Math.min(minimum, oddone[n] - oddone[i + 1] + evenone[i + 1]); minimum = Math.min(minimum, evenone[n] - evenone[i + 1] + oddone[i + 1]); } } // Return minimum flips return minimum; } // Driver Code // Given String let S = \"000001100\"; // Length of given string let n = S.length; // Function call document.write(MinimumFlips(S, n)); </script>", "e": 40580, "s": 38167, "text": null }, { "code": null, "e": 40582, "s": 40580, "text": "3" }, { "code": null, "e": 40671, "s": 40584, "text": "Time Complexity: O(N), where N is the length of the given string.Auxiliary Space: O(N)" }, { "code": null, "e": 40685, "s": 40671, "text": "SHIVAMSINGH67" }, { "code": null, "e": 40691, "s": 40685, "text": "ukasp" }, { "code": null, "e": 40701, "s": 40691, "text": "Rajput-Ji" }, { "code": null, "e": 40723, "s": 40701, "text": "susmitakundugoaldanga" }, { "code": null, "e": 40733, "s": 40723, "text": "sahil9420" }, { "code": null, "e": 40747, "s": 40733, "text": "binary-string" }, { "code": null, "e": 40754, "s": 40747, "text": "Google" }, { "code": null, "e": 40761, "s": 40754, "text": "Greedy" }, { "code": null, "e": 40774, "s": 40761, "text": "Mathematical" }, { "code": null, "e": 40782, "s": 40774, "text": "Strings" }, { "code": null, "e": 40789, "s": 40782, "text": "Google" }, { "code": null, "e": 40797, "s": 40789, "text": "Strings" }, { "code": null, "e": 40804, "s": 40797, "text": "Greedy" }, { "code": null, "e": 40817, "s": 40804, "text": "Mathematical" }, { "code": null, "e": 40915, "s": 40817, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40946, "s": 40915, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 40965, "s": 40946, "text": "Coin Change | DP-7" }, { "code": null, "e": 41008, "s": 40965, "text": "Activity Selection Problem | Greedy Algo-1" }, { "code": null, "e": 41036, "s": 41008, "text": "Fractional Knapsack Problem" }, { "code": null, "e": 41117, "s": 41036, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" }, { "code": null, "e": 41147, "s": 41117, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 41162, "s": 41147, "text": "C++ Data Types" }, { "code": null, "e": 41205, "s": 41162, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 41224, "s": 41205, "text": "Coin Change | DP-7" } ]
Flutter - Fetching Data From the Internet - GeeksforGeeks
14 Aug, 2021 In today’s world, most applications heavily rely on fetching information from the servers through the internet. In Flutter, such services are provided by the http package. In this article we will explore the same. To fetch data from the internet follow the below steps: Import the http packageMake a network request using the http packageConvert the response into custom Dart objectDisplay the data in a suitable format Import the http package Make a network request using the http package Convert the response into custom Dart object Display the data in a suitable format To install the http package use the below command in your command prompt: pub get or, if you are using the flutter cmd use the below command: flutter pub get After the installation add the dependency to the pubsec.yml file as shown below: import 'package:http/http.dart' as http; We can use the http.get() method to fetch the sample album data from JSONPlaceholder as shown below: Dart Future<http.Response> fetchAlbum() { return http.get('https://jsonplaceholder.typicode.com/albums/1');} Though making a network request is no big deal, working with the raw response data can be inconvenient. To make your life easier, converting the raw data (ie, http.response) into dart object. Here we will create an Album class that contains the JSON data as shown below: Dart class Album { final int userId; final int id; final String title; Album({this.userId, this.id, this.title}); factory Album.fromJson(Map<String, dynamic> json) { return Album( userId: json['userId'], id: json['id'], title: json['title'], ); }} Now, follow the below steps to update the fetchAlbum() function to return a Future<Album>: Use the dart: convert package to convert the response body into a JSON Map.Use the fromJSON() factory method to convert JSON Map into Album if the server returns an OK response with a status code of 200.Throw an exception if the server doesn’t return an OK response with a status code of 200. Use the dart: convert package to convert the response body into a JSON Map. Use the fromJSON() factory method to convert JSON Map into Album if the server returns an OK response with a status code of 200. Throw an exception if the server doesn’t return an OK response with a status code of 200. Dart Future<Album> fetchAlbum() async { final response = await http.get('https://jsonplaceholder.typicode.com/albums/1'); if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to load album'); }} Now use the fetch() method to fetch the data as shown below: Dart class _MyAppState extends State<MyApp> { Future<Album> futureAlbum; @override void initState() { super.initState(); futureAlbum = fetchAlbum(); } Use the FlutterBuilder widget to display the data on the screen as shown below: Dart FutureBuilder<Album>( future: futureAlbum, builder: (context, snapshot) { if (snapshot.hasData) { return Text(snapshot.data.title); } else if (snapshot.hasError) { return Text("${snapshot.error}"); } // spinner return CircularProgressIndicator(); },); Complete Source Code: Dart import 'dart:async';import 'dart:convert'; import 'package:flutter/material.dart';import 'package:http/http.dart' as http; Future<Album> fetchAlbum() async { final response = await http.get('https://jsonplaceholder.typicode.com/albums/1'); // Appropriate action depending upon the // server response if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to load album'); }} class Album { final int userId; final int id; final String title; Album({this.userId, this.id, this.title}); factory Album.fromJson(Map<String, dynamic> json) { return Album( userId: json['userId'], id: json['id'], title: json['title'], ); }} void main() => runApp(MyApp()); class MyApp extends StatefulWidget { MyApp({Key key}) : super(key: key); @override _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { Future<Album> futureAlbum; @override void initState() { super.initState(); futureAlbum = fetchAlbum(); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Fetching Data', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), ), body: Center( child: FutureBuilder<Album>( future: futureAlbum, builder: (context, snapshot) { if (snapshot.hasData) { return Text(snapshot.data.title); } else if (snapshot.hasError) { return Text("${snapshot.error}"); } return CircularProgressIndicator(); }, ), ), ), ); }} Output: sumitgumber28 android Flutter Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Listview.builder in Flutter Flutter - Asset Image Splash Screen in Flutter Flutter - Custom Bottom Navigation Bar Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget Flutter - Flexible Widget Flutter - BoxShadow Widget
[ { "code": null, "e": 27159, "s": 27131, "text": "\n14 Aug, 2021" }, { "code": null, "e": 27373, "s": 27159, "text": "In today’s world, most applications heavily rely on fetching information from the servers through the internet. In Flutter, such services are provided by the http package. In this article we will explore the same." }, { "code": null, "e": 27429, "s": 27373, "text": "To fetch data from the internet follow the below steps:" }, { "code": null, "e": 27579, "s": 27429, "text": "Import the http packageMake a network request using the http packageConvert the response into custom Dart objectDisplay the data in a suitable format" }, { "code": null, "e": 27603, "s": 27579, "text": "Import the http package" }, { "code": null, "e": 27649, "s": 27603, "text": "Make a network request using the http package" }, { "code": null, "e": 27694, "s": 27649, "text": "Convert the response into custom Dart object" }, { "code": null, "e": 27732, "s": 27694, "text": "Display the data in a suitable format" }, { "code": null, "e": 27806, "s": 27732, "text": "To install the http package use the below command in your command prompt:" }, { "code": null, "e": 27814, "s": 27806, "text": "pub get" }, { "code": null, "e": 27874, "s": 27814, "text": "or, if you are using the flutter cmd use the below command:" }, { "code": null, "e": 27890, "s": 27874, "text": "flutter pub get" }, { "code": null, "e": 27971, "s": 27890, "text": "After the installation add the dependency to the pubsec.yml file as shown below:" }, { "code": null, "e": 28012, "s": 27971, "text": "import 'package:http/http.dart' as http;" }, { "code": null, "e": 28113, "s": 28012, "text": "We can use the http.get() method to fetch the sample album data from JSONPlaceholder as shown below:" }, { "code": null, "e": 28118, "s": 28113, "text": "Dart" }, { "code": "Future<http.Response> fetchAlbum() { return http.get('https://jsonplaceholder.typicode.com/albums/1');}", "e": 28223, "s": 28118, "text": null }, { "code": null, "e": 28494, "s": 28223, "text": "Though making a network request is no big deal, working with the raw response data can be inconvenient. To make your life easier, converting the raw data (ie, http.response) into dart object. Here we will create an Album class that contains the JSON data as shown below:" }, { "code": null, "e": 28499, "s": 28494, "text": "Dart" }, { "code": "class Album { final int userId; final int id; final String title; Album({this.userId, this.id, this.title}); factory Album.fromJson(Map<String, dynamic> json) { return Album( userId: json['userId'], id: json['id'], title: json['title'], ); }}", "e": 28771, "s": 28499, "text": null }, { "code": null, "e": 28862, "s": 28771, "text": "Now, follow the below steps to update the fetchAlbum() function to return a Future<Album>:" }, { "code": null, "e": 29155, "s": 28862, "text": "Use the dart: convert package to convert the response body into a JSON Map.Use the fromJSON() factory method to convert JSON Map into Album if the server returns an OK response with a status code of 200.Throw an exception if the server doesn’t return an OK response with a status code of 200." }, { "code": null, "e": 29231, "s": 29155, "text": "Use the dart: convert package to convert the response body into a JSON Map." }, { "code": null, "e": 29360, "s": 29231, "text": "Use the fromJSON() factory method to convert JSON Map into Album if the server returns an OK response with a status code of 200." }, { "code": null, "e": 29450, "s": 29360, "text": "Throw an exception if the server doesn’t return an OK response with a status code of 200." }, { "code": null, "e": 29455, "s": 29450, "text": "Dart" }, { "code": "Future<Album> fetchAlbum() async { final response = await http.get('https://jsonplaceholder.typicode.com/albums/1'); if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to load album'); }}", "e": 29721, "s": 29455, "text": null }, { "code": null, "e": 29787, "s": 29726, "text": "Now use the fetch() method to fetch the data as shown below:" }, { "code": null, "e": 29794, "s": 29789, "text": "Dart" }, { "code": "class _MyAppState extends State<MyApp> { Future<Album> futureAlbum; @override void initState() { super.initState(); futureAlbum = fetchAlbum(); }", "e": 29951, "s": 29794, "text": null }, { "code": null, "e": 30031, "s": 29951, "text": "Use the FlutterBuilder widget to display the data on the screen as shown below:" }, { "code": null, "e": 30036, "s": 30031, "text": "Dart" }, { "code": "FutureBuilder<Album>( future: futureAlbum, builder: (context, snapshot) { if (snapshot.hasData) { return Text(snapshot.data.title); } else if (snapshot.hasError) { return Text(\"${snapshot.error}\"); } // spinner return CircularProgressIndicator(); },);", "e": 30317, "s": 30036, "text": null }, { "code": null, "e": 30339, "s": 30317, "text": "Complete Source Code:" }, { "code": null, "e": 30344, "s": 30339, "text": "Dart" }, { "code": "import 'dart:async';import 'dart:convert'; import 'package:flutter/material.dart';import 'package:http/http.dart' as http; Future<Album> fetchAlbum() async { final response = await http.get('https://jsonplaceholder.typicode.com/albums/1'); // Appropriate action depending upon the // server response if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to load album'); }} class Album { final int userId; final int id; final String title; Album({this.userId, this.id, this.title}); factory Album.fromJson(Map<String, dynamic> json) { return Album( userId: json['userId'], id: json['id'], title: json['title'], ); }} void main() => runApp(MyApp()); class MyApp extends StatefulWidget { MyApp({Key key}) : super(key: key); @override _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { Future<Album> futureAlbum; @override void initState() { super.initState(); futureAlbum = fetchAlbum(); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Fetching Data', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), ), body: Center( child: FutureBuilder<Album>( future: futureAlbum, builder: (context, snapshot) { if (snapshot.hasData) { return Text(snapshot.data.title); } else if (snapshot.hasError) { return Text(\"${snapshot.error}\"); } return CircularProgressIndicator(); }, ), ), ), ); }}", "e": 32085, "s": 30344, "text": null }, { "code": null, "e": 32093, "s": 32085, "text": "Output:" }, { "code": null, "e": 32107, "s": 32093, "text": "sumitgumber28" }, { "code": null, "e": 32115, "s": 32107, "text": "android" }, { "code": null, "e": 32123, "s": 32115, "text": "Flutter" }, { "code": null, "e": 32128, "s": 32123, "text": "Dart" }, { "code": null, "e": 32136, "s": 32128, "text": "Flutter" }, { "code": null, "e": 32234, "s": 32136, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32266, "s": 32234, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 32294, "s": 32266, "text": "Listview.builder in Flutter" }, { "code": null, "e": 32316, "s": 32294, "text": "Flutter - Asset Image" }, { "code": null, "e": 32341, "s": 32316, "text": "Splash Screen in Flutter" }, { "code": null, "e": 32380, "s": 32341, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 32412, "s": 32380, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 32451, "s": 32412, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 32477, "s": 32451, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 32503, "s": 32477, "text": "Flutter - Flexible Widget" } ]
Automata Theory | Set 5 - GeeksforGeeks
27 Mar, 2017 Following questions have been asked in GATE CS 2009 exam. 1) S –> aSa| bSb| a| b ;The language generated by the above grammar over the alphabet {a,b} is the set of(A) All palindromes.(B) All odd length palindromes.(C) Strings that begin and end with the same symbol(D) All even length palindromes. Answer (B)The strings accepted by language are {a, b, aaa, bbb, aba, bab, ..}. All of these strings are odd length palindromes. 2) Which one of the following languages over the alphabet {0,1} is described by the regular expression: (0+1)*0(0+1)*0(0+1)*?(A) The set of all strings containing the substring 00.(B) The set of all strings containing at most two 0’s.(C) The set of all strings containing at least two 0’s.(D) The set of all strings that begin and end with either 0 or 1. Answer (C)The regular expression has two 0’s surrounded by (0+1)* which means accepted strings must have at least 2 0’s. 3) Which one of the following is FALSE?(A) There is unique minimal DFA for every regular language(B) Every NFA can be converted to an equivalent PDA.(C) Complement of every context-free language is recursive.(D) Every nondeterministic PDA can be converted to an equivalent deterministic PDA. Answer (D)Deterministic PDA cannot handle languages or grammars with ambiguity, but NDPDA can handle languages with ambiguity and any context-free grammar. So every nondeterministic PDA can not be converted to an equivalent deterministic PDA. 4) Match all items in Group 1 with correct options from those given in Group 2. Group 1 Group 2 P. Regular expression 1. Syntax analysis Q. Pushdown automata 2. Code generation R. Dataflow analysis 3. Lexical analysis S. Register allocation 4. Code optimization (A) P-4. Q-1, R-2, S-3(B) P-3, Q-1, R-4, S-2(C) P-3, Q-4, R-1, S-2(D) P-2, Q-1, R-4, S-3 Answer (B) 5) . Let L = L1 ∩ L2, where L1 and L2 are languages as defined below:L1 = {ambmcanbn | m, n >= 0 }L2 = {aibjck | i, j, k >= 0 }Then L is(A) Not recursive(B) Regular(C) Context free but not regular(D) Recursively enumerable but not context free. Answer (C)The language L1 accept strings {c, abc, abcab, aabbcab, aabbcaabb, ...} and L2 accept strings {a, b, c, ab, abc, aabc, aabbc, ... }. Intersection of these two languages is L1 ∩L2 = {akbkc | k >= 0} which is context free, but not regular. Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc. Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. AT GATE-CS-2009 GATE CS MCQ 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 Types of Operating Systems Normal Forms in DBMS Data Structures and Algorithms | Set 25 Operating Systems | Set 1 Practice questions on Height balanced/AVL Tree Computer Networks | Set 2 Computer Networks | Set 1
[ { "code": null, "e": 31081, "s": 31053, "text": "\n27 Mar, 2017" }, { "code": null, "e": 31139, "s": 31081, "text": "Following questions have been asked in GATE CS 2009 exam." }, { "code": null, "e": 31379, "s": 31139, "text": "1) S –> aSa| bSb| a| b ;The language generated by the above grammar over the alphabet {a,b} is the set of(A) All palindromes.(B) All odd length palindromes.(C) Strings that begin and end with the same symbol(D) All even length palindromes." }, { "code": null, "e": 31507, "s": 31379, "text": "Answer (B)The strings accepted by language are {a, b, aaa, bbb, aba, bab, ..}. All of these strings are odd length palindromes." }, { "code": null, "e": 31862, "s": 31507, "text": "2) Which one of the following languages over the alphabet {0,1} is described by the regular expression: (0+1)*0(0+1)*0(0+1)*?(A) The set of all strings containing the substring 00.(B) The set of all strings containing at most two 0’s.(C) The set of all strings containing at least two 0’s.(D) The set of all strings that begin and end with either 0 or 1." }, { "code": null, "e": 31983, "s": 31862, "text": "Answer (C)The regular expression has two 0’s surrounded by (0+1)* which means accepted strings must have at least 2 0’s." }, { "code": null, "e": 32275, "s": 31983, "text": "3) Which one of the following is FALSE?(A) There is unique minimal DFA for every regular language(B) Every NFA can be converted to an equivalent PDA.(C) Complement of every context-free language is recursive.(D) Every nondeterministic PDA can be converted to an equivalent deterministic PDA." }, { "code": null, "e": 32518, "s": 32275, "text": "Answer (D)Deterministic PDA cannot handle languages or grammars with ambiguity, but NDPDA can handle languages with ambiguity and any context-free grammar. So every nondeterministic PDA can not be converted to an equivalent deterministic PDA." }, { "code": null, "e": 32598, "s": 32518, "text": "4) Match all items in Group 1 with correct options from those given in Group 2." }, { "code": null, "e": 32834, "s": 32598, "text": "Group 1 Group 2\nP. Regular expression 1. Syntax analysis\nQ. Pushdown automata 2. Code generation\nR. Dataflow analysis 3. Lexical analysis\nS. Register allocation 4. Code optimization" }, { "code": null, "e": 32923, "s": 32834, "text": "(A) P-4. Q-1, R-2, S-3(B) P-3, Q-1, R-4, S-2(C) P-3, Q-4, R-1, S-2(D) P-2, Q-1, R-4, S-3" }, { "code": null, "e": 32934, "s": 32923, "text": "Answer (B)" }, { "code": null, "e": 33179, "s": 32934, "text": "5) . Let L = L1 ∩ L2, where L1 and L2 are languages as defined below:L1 = {ambmcanbn | m, n >= 0 }L2 = {aibjck | i, j, k >= 0 }Then L is(A) Not recursive(B) Regular(C) Context free but not regular(D) Recursively enumerable but not context free." }, { "code": null, "e": 33427, "s": 33179, "text": "Answer (C)The language L1 accept strings {c, abc, abcab, aabbcab, aabbcaabb, ...} and L2 accept strings {a, b, c, ab, abc, aabc, aabbc, ... }. Intersection of these two languages is L1 ∩L2 = {akbkc | k >= 0} which is context free, but not regular." }, { "code": null, "e": 33541, "s": 33427, "text": "Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc." }, { "code": null, "e": 33690, "s": 33541, "text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above." }, { "code": null, "e": 33693, "s": 33690, "text": "AT" }, { "code": null, "e": 33706, "s": 33693, "text": "GATE-CS-2009" }, { "code": null, "e": 33714, "s": 33706, "text": "GATE CS" }, { "code": null, "e": 33718, "s": 33714, "text": "MCQ" }, { "code": null, "e": 33816, "s": 33718, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33836, "s": 33816, "text": "Layers of OSI Model" }, { "code": null, "e": 33860, "s": 33836, "text": "ACID Properties in DBMS" }, { "code": null, "e": 33873, "s": 33860, "text": "TCP/IP Model" }, { "code": null, "e": 33900, "s": 33873, "text": "Types of Operating Systems" }, { "code": null, "e": 33921, "s": 33900, "text": "Normal Forms in DBMS" }, { "code": null, "e": 33961, "s": 33921, "text": "Data Structures and Algorithms | Set 25" }, { "code": null, "e": 33987, "s": 33961, "text": "Operating Systems | Set 1" }, { "code": null, "e": 34034, "s": 33987, "text": "Practice questions on Height balanced/AVL Tree" }, { "code": null, "e": 34060, "s": 34034, "text": "Computer Networks | Set 2" } ]
How to Apply Conditional Formatting Based On VLookup in Excel? - GeeksforGeeks
06 Jun, 2021 VLOOKUP is an Excel function to lookup data in a table organized vertically. VLOOKUP supports approximate and exact matching, and wildcards (* ?) for partial matches. 1. Using the Vlookup formula to compare values in 2 different tables and highlighting those values which is only present in table 1 using conditional formatting. We have a Table containing old products of any grocery shop in ‘Old Product’ sheet and an updated table having new products in worksheet ‘New’. We want to highlight rows in New table containing those items which are not in Old Product Table. Old Product Select the data from New table except the Headers. (The table in which we want to highlight rows.) Go to Home->Conditional Formatting->New Rule. In the dialog box appeared, Select the rule type – “Use a formula to determine which cells to format;”; Under Edit the rule description enters the following formula: =ISNA(VLOOKUP($A2,'Old Product'!$A$1:$B$8,1,FALSE)) Then click Format. Formula explanation: Inside VLOOKUP, 1st parameter is $A2 which is first name in New table. 2nd parameter is Old Product Table. 3rd parameter is column we want to compare which is 1 as we want to compare item names. 4rd parameter is False i.e. only exact values are matched. So, this formula will return a valid value for those New Table items which are found in Old Table and #NA for those which are not found. Now, if the value is NA we want to Highlight them as they are not in old product table. So, they are new items added. Using ISNA we will achieve this. Finally, we have the required values and we will highlight them. A new dialog box will appear. Go to Fill Tab and select a color to fill. Click OK to close both the dialog boxes. Now, Those value which is present in New table but not in Old Product will be highlighted. 2. Using the Vlookup formula to compare values in 2 different tables and highlighting those values which is greater in table 1 as compared to table 2 using conditional formatting. We have a Table containing the old price of some grocery items in the ‘Old Product’ sheet and a table having a new price of those grocery items in the worksheet ‘New’. We will highlight those rows in the Old Product Table in which a particular item’s cost is greater than that of the New table. Select the data from the old price table except for the Headers. Go to Home->Conditional Formatting->New Rule. In the dialog box that appeared, Select the rule type – “Use a formula to determine which cells to format;” Under Edit the rule description enter the following formula =(VLOOKUP($A2, 'New'!$A$1:$B$8,2,FALSE)<'Old Product'!$B2 And click Format. Formula explanation: Inside VLOOKUP, 1st parameter is $A2 which is first name in Old Product table. 2nd parameter is New Table. 3rd parameter is column we want to compare which is 2 in New Table as we want to compare Price. 4rd parameter is False i.e. only exact values are matched. Now we will compare this with cost value in Old Product table starting from 1st value. If cost is greater than we will highlight. A new dialog box will appear. Go to Fill Tab and select a color to fill. Click OK to close both the dialog boxes. This is how we can apply conditional formatting based on VLookup. Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Use Solver in Excel? How to Find the Last Used Row and Column in Excel VBA? How to Get Length of Array in Excel VBA? Using CHOOSE Function along with VLOOKUP in Excel Macros in Excel Introduction to Excel Spreadsheet How to Remove Duplicates From Array Using VBA in Excel? How to Show Percentages in Stacked Column Chart in Excel? How to Extract the Last Word From a Cell in Excel? How to Sum Values Based on Criteria in Another Column in Excel?
[ { "code": null, "e": 26163, "s": 26135, "text": "\n06 Jun, 2021" }, { "code": null, "e": 26330, "s": 26163, "text": "VLOOKUP is an Excel function to lookup data in a table organized vertically. VLOOKUP supports approximate and exact matching, and wildcards (* ?) for partial matches." }, { "code": null, "e": 26493, "s": 26330, "text": "1. Using the Vlookup formula to compare values in 2 different tables and highlighting those values which is only present in table 1 using conditional formatting. " }, { "code": null, "e": 26735, "s": 26493, "text": "We have a Table containing old products of any grocery shop in ‘Old Product’ sheet and an updated table having new products in worksheet ‘New’. We want to highlight rows in New table containing those items which are not in Old Product Table." }, { "code": null, "e": 26747, "s": 26735, "text": "Old Product" }, { "code": null, "e": 26846, "s": 26747, "text": "Select the data from New table except the Headers. (The table in which we want to highlight rows.)" }, { "code": null, "e": 26892, "s": 26846, "text": "Go to Home->Conditional Formatting->New Rule." }, { "code": null, "e": 26996, "s": 26892, "text": "In the dialog box appeared, Select the rule type – “Use a formula to determine which cells to format;”;" }, { "code": null, "e": 27058, "s": 26996, "text": "Under Edit the rule description enters the following formula:" }, { "code": null, "e": 27111, "s": 27058, "text": " =ISNA(VLOOKUP($A2,'Old Product'!$A$1:$B$8,1,FALSE))" }, { "code": null, "e": 27130, "s": 27111, "text": "Then click Format." }, { "code": null, "e": 27151, "s": 27130, "text": "Formula explanation:" }, { "code": null, "e": 27168, "s": 27151, "text": "Inside VLOOKUP, " }, { "code": null, "e": 27223, "s": 27168, "text": "1st parameter is $A2 which is first name in New table." }, { "code": null, "e": 27259, "s": 27223, "text": "2nd parameter is Old Product Table." }, { "code": null, "e": 27347, "s": 27259, "text": "3rd parameter is column we want to compare which is 1 as we want to compare item names." }, { "code": null, "e": 27406, "s": 27347, "text": "4rd parameter is False i.e. only exact values are matched." }, { "code": null, "e": 27544, "s": 27406, "text": "So, this formula will return a valid value for those New Table items which are found in Old Table and #NA for those which are not found. " }, { "code": null, "e": 27696, "s": 27544, "text": "Now, if the value is NA we want to Highlight them as they are not in old product table. So, they are new items added. Using ISNA we will achieve this. " }, { "code": null, "e": 27761, "s": 27696, "text": "Finally, we have the required values and we will highlight them." }, { "code": null, "e": 27834, "s": 27761, "text": "A new dialog box will appear. Go to Fill Tab and select a color to fill." }, { "code": null, "e": 27875, "s": 27834, "text": "Click OK to close both the dialog boxes." }, { "code": null, "e": 27966, "s": 27875, "text": "Now, Those value which is present in New table but not in Old Product will be highlighted." }, { "code": null, "e": 28147, "s": 27966, "text": " 2. Using the Vlookup formula to compare values in 2 different tables and highlighting those values which is greater in table 1 as compared to table 2 using conditional formatting." }, { "code": null, "e": 28442, "s": 28147, "text": "We have a Table containing the old price of some grocery items in the ‘Old Product’ sheet and a table having a new price of those grocery items in the worksheet ‘New’. We will highlight those rows in the Old Product Table in which a particular item’s cost is greater than that of the New table." }, { "code": null, "e": 28507, "s": 28442, "text": "Select the data from the old price table except for the Headers." }, { "code": null, "e": 28553, "s": 28507, "text": "Go to Home->Conditional Formatting->New Rule." }, { "code": null, "e": 28661, "s": 28553, "text": "In the dialog box that appeared, Select the rule type – “Use a formula to determine which cells to format;”" }, { "code": null, "e": 28722, "s": 28661, "text": "Under Edit the rule description enter the following formula " }, { "code": null, "e": 28782, "s": 28722, "text": " =(VLOOKUP($A2, 'New'!$A$1:$B$8,2,FALSE)<'Old Product'!$B2 " }, { "code": null, "e": 28800, "s": 28782, "text": "And click Format." }, { "code": null, "e": 28821, "s": 28800, "text": "Formula explanation:" }, { "code": null, "e": 28837, "s": 28821, "text": "Inside VLOOKUP," }, { "code": null, "e": 28900, "s": 28837, "text": "1st parameter is $A2 which is first name in Old Product table." }, { "code": null, "e": 28928, "s": 28900, "text": "2nd parameter is New Table." }, { "code": null, "e": 29024, "s": 28928, "text": "3rd parameter is column we want to compare which is 2 in New Table as we want to compare Price." }, { "code": null, "e": 29083, "s": 29024, "text": "4rd parameter is False i.e. only exact values are matched." }, { "code": null, "e": 29213, "s": 29083, "text": "Now we will compare this with cost value in Old Product table starting from 1st value. If cost is greater than we will highlight." }, { "code": null, "e": 29286, "s": 29213, "text": "A new dialog box will appear. Go to Fill Tab and select a color to fill." }, { "code": null, "e": 29327, "s": 29286, "text": "Click OK to close both the dialog boxes." }, { "code": null, "e": 29394, "s": 29327, "text": "This is how we can apply conditional formatting based on VLookup. " }, { "code": null, "e": 29401, "s": 29394, "text": "Picked" }, { "code": null, "e": 29407, "s": 29401, "text": "Excel" }, { "code": null, "e": 29505, "s": 29407, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29533, "s": 29505, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 29588, "s": 29533, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 29629, "s": 29588, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 29679, "s": 29629, "text": "Using CHOOSE Function along with VLOOKUP in Excel" }, { "code": null, "e": 29695, "s": 29679, "text": "Macros in Excel" }, { "code": null, "e": 29729, "s": 29695, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 29785, "s": 29729, "text": "How to Remove Duplicates From Array Using VBA in Excel?" }, { "code": null, "e": 29843, "s": 29785, "text": "How to Show Percentages in Stacked Column Chart in Excel?" }, { "code": null, "e": 29894, "s": 29843, "text": "How to Extract the Last Word From a Cell in Excel?" } ]
Difference between Pipes and Message Queues - GeeksforGeeks
16 Mar, 2020 Pipes:Unix system uses pipes, to establish inter process communication. A pipe provides an unidirectional flow of data. A pipe is created using the pipe() function. Syntax: #include int pipe(int fd); A pipe ()function returns two file descriptors, fd[O] and fd[1]. The fd[0] is open for reading from and fd[1] is open for writing to the pipe. The data flows from one end of the pipe to the other end. The pipe function returns ‘0’ on success or -1 on error. Message Queues:A Message Queues, allow one or more processes to write message to be read by other processes. A message queue is implemented as a linked list of messages, and is stored within the Kernel. Each message queue is identified by a message queue identifier. The Kernel keeps track of all the message queues created in a system. Difference between Pipes and Message Queues: system-programming Difference Between Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Difference between Compile-time and Run-time Polymorphism in Java Types of Operating Systems Banker's Algorithm in Operating System Page Replacement Algorithms in Operating Systems Program for FCFS CPU Scheduling | Set 1 Paging in Operating System
[ { "code": null, "e": 26103, "s": 26075, "text": "\n16 Mar, 2020" }, { "code": null, "e": 26268, "s": 26103, "text": "Pipes:Unix system uses pipes, to establish inter process communication. A pipe provides an unidirectional flow of data. A pipe is created using the pipe() function." }, { "code": null, "e": 26276, "s": 26268, "text": "Syntax:" }, { "code": null, "e": 26305, "s": 26276, "text": "#include int pipe(int fd); " }, { "code": null, "e": 26563, "s": 26305, "text": "A pipe ()function returns two file descriptors, fd[O] and fd[1]. The fd[0] is open for reading from and fd[1] is open for writing to the pipe. The data flows from one end of the pipe to the other end. The pipe function returns ‘0’ on success or -1 on error." }, { "code": null, "e": 26900, "s": 26563, "text": "Message Queues:A Message Queues, allow one or more processes to write message to be read by other processes. A message queue is implemented as a linked list of messages, and is stored within the Kernel. Each message queue is identified by a message queue identifier. The Kernel keeps track of all the message queues created in a system." }, { "code": null, "e": 26945, "s": 26900, "text": "Difference between Pipes and Message Queues:" }, { "code": null, "e": 26964, "s": 26945, "text": "system-programming" }, { "code": null, "e": 26983, "s": 26964, "text": "Difference Between" }, { "code": null, "e": 27001, "s": 26983, "text": "Operating Systems" }, { "code": null, "e": 27019, "s": 27001, "text": "Operating Systems" }, { "code": null, "e": 27117, "s": 27019, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27178, "s": 27117, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27246, "s": 27178, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 27304, "s": 27246, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 27359, "s": 27304, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 27425, "s": 27359, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 27452, "s": 27425, "text": "Types of Operating Systems" }, { "code": null, "e": 27491, "s": 27452, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 27540, "s": 27491, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 27580, "s": 27540, "text": "Program for FCFS CPU Scheduling | Set 1" } ]
Cholesky Decomposition : Matrix Decomposition - GeeksforGeeks
30 Jan, 2022 In linear algebra, a matrix decomposition or matrix factorization is a factorization of a matrix into a product of matrices. There are many different matrix decompositions. One of them is Cholesky Decomposition. The Cholesky decomposition or Cholesky factorization is a decomposition of a Hermitian, positive-definite matrix into the product of a lower triangular matrix and its conjugate transpose. The Cholesky decomposition is roughly twice as efficient as the LU decomposition for solving systems of linear equations. The Cholesky decomposition of a Hermitian positive-definite matrix A is a decomposition of the form A = [L][L]T, where L is a lower triangular matrix with real and positive diagonal entries, and LT denotes the conjugate transpose of L. Every Hermitian positive-definite matrix (and thus also every real-valued symmetric positive-definite matrix) has a unique Cholesky decomposition. Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L LT The following formulas are obtained by solving above lower triangular matrix and its transpose. These are the basis of Cholesky Decomposition Algorithm : Example : Input : Output : Below is the implementation of Cholesky Decomposition. C++ Java Python3 C# PHP Javascript // CPP program to decompose a matrix using// Cholesky Decomposition#include <bits/stdc++.h>using namespace std; const int MAX = 100; void Cholesky_Decomposition(int matrix[][MAX], int n){ int lower[n][n]; memset(lower, 0, sizeof(lower)); // Decomposing a matrix into Lower Triangular for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { int sum = 0; if (j == i) // summation for diagonals { for (int k = 0; k < j; k++) sum += pow(lower[j][k], 2); lower[j][j] = sqrt(matrix[j][j] - sum); } else { // Evaluating L(i, j) using L(j, j) for (int k = 0; k < j; k++) sum += (lower[i][k] * lower[j][k]); lower[i][j] = (matrix[i][j] - sum) / lower[j][j]; } } } // Displaying Lower Triangular and its Transpose cout << setw(6) << " Lower Triangular" << setw(30) << "Transpose" << endl; for (int i = 0; i < n; i++) { // Lower Triangular for (int j = 0; j < n; j++) cout << setw(6) << lower[i][j] << "\t"; cout << "\t"; // Transpose of Lower Triangular for (int j = 0; j < n; j++) cout << setw(6) << lower[j][i] << "\t"; cout << endl; }} // Driver Codeint main(){ int n = 3; int matrix[][MAX] = { { 4, 12, -16 }, { 12, 37, -43 }, { -16, -43, 98 } }; Cholesky_Decomposition(matrix, n); return 0;} // Java program to decompose// a matrix using Cholesky// Decomposition class GFG { // static int MAX = 100; static void Cholesky_Decomposition(int[][] matrix, int n) { int[][] lower = new int[n][n]; // Decomposing a matrix // into Lower Triangular for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { int sum = 0; // summation for diagonals if (j == i) { for (int k = 0; k < j; k++) sum += (int)Math.pow(lower[j][k], 2); lower[j][j] = (int)Math.sqrt( matrix[j][j] - sum); } else { // Evaluating L(i, j) // using L(j, j) for (int k = 0; k < j; k++) sum += (lower[i][k] * lower[j][k]); lower[i][j] = (matrix[i][j] - sum) / lower[j][j]; } } } // Displaying Lower // Triangular and its Transpose System.out.println(" Lower Triangular\t Transpose"); for (int i = 0; i < n; i++) { // Lower Triangular for (int j = 0; j < n; j++) System.out.print(lower[i][j] + "\t"); System.out.print(""); // Transpose of // Lower Triangular for (int j = 0; j < n; j++) System.out.print(lower[j][i] + "\t"); System.out.println(); } } // Driver Code public static void main(String[] args) { int n = 3; int[][] matrix = new int[][] { { 4, 12, -16 }, { 12, 37, -43 }, { -16, -43, 98 } }; Cholesky_Decomposition(matrix, n); }} // This code is contributed by mits # Python3 program to decompose# a matrix using Cholesky# Decompositionimport mathMAX = 100; def Cholesky_Decomposition(matrix, n): lower = [[0 for x in range(n + 1)] for y in range(n + 1)]; # Decomposing a matrix # into Lower Triangular for i in range(n): for j in range(i + 1): sum1 = 0; # summation for diagonals if (j == i): for k in range(j): sum1 += pow(lower[j][k], 2); lower[j][j] = int(math.sqrt(matrix[j][j] - sum1)); else: # Evaluating L(i, j) # using L(j, j) for k in range(j): sum1 += (lower[i][k] *lower[j][k]); if(lower[j][j] > 0): lower[i][j] = int((matrix[i][j] - sum1) / lower[j][j]); # Displaying Lower Triangular # and its Transpose print("Lower Triangular\t\tTranspose"); for i in range(n): # Lower Triangular for j in range(n): print(lower[i][j], end = "\t"); print("", end = "\t"); # Transpose of # Lower Triangular for j in range(n): print(lower[j][i], end = "\t"); print(""); # Driver Coden = 3;matrix = [[4, 12, -16], [12, 37, -43], [-16, -43, 98]];Cholesky_Decomposition(matrix, n); # This code is contributed by mits // C# program to decompose// a matrix using Cholesky// Decompositionusing System; class GFG { // static int MAX = 100; static void Cholesky_Decomposition(int[, ] matrix, int n) { int[, ] lower = new int[n, n]; // Decomposing a matrix // into Lower Triangular for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { int sum = 0; // summation for diagonals if (j == i) { for (int k = 0; k < j; k++) sum += (int)Math.Pow(lower[j, k], 2); lower[j, j] = (int)Math.Sqrt( matrix[j, j] - sum); } else { // Evaluating L(i, j) // using L(j, j) for (int k = 0; k < j; k++) sum += (lower[i, k] * lower[j, k]); lower[i, j] = (matrix[i, j] - sum) / lower[j, j]; } } } // Displaying Lower // Triangular and its Transpose Console.WriteLine( " Lower Triangular\t Transpose"); for (int i = 0; i < n; i++) { // Lower Triangular for (int j = 0; j < n; j++) Console.Write(lower[i, j] + "\t"); Console.Write(""); // Transpose of // Lower Triangular for (int j = 0; j < n; j++) Console.Write(lower[j, i] + "\t"); Console.WriteLine(); } } // Driver Code static int Main() { int n = 3; int[, ] matrix = { { 4, 12, -16 }, { 12, 37, -43 }, { -16, -43, 98 } }; Cholesky_Decomposition(matrix, n); return 0; }} // This code is contributed by mits <?php// PHP program to decompose// a matrix using Cholesky// Decomposition$MAX = 100; function Cholesky_Decomposition($matrix, $n){ $lower; for ($i = 0; $i <= $n; $i++) for ($j = 0; $j <= $n; $j++) $lower[$i][$j] = 0; // Decomposing a matrix // into Lower Triangular for ($i = 0; $i < $n; $i++) { for ($j = 0; $j <= $i; $j++) { $sum = 0; // summation for diagonals if ($j == $i) { for ($k = 0; $k < $j; $k++) $sum += pow($lower[$j][$k], 2); $lower[$j][$j] = sqrt($matrix[$j][$j] - $sum); } else { // Evaluating L(i, j) // using L(j, j) for ($k = 0; $k < $j; $k++) $sum += ($lower[$i][$k] * $lower[$j][$k]); $lower[$i][$j] = ($matrix[$i][$j] - $sum) / $lower[$j][$j]; } } } // Displaying Lower Triangular // and its Transpose echo " Lower Triangular" . str_pad("Transpose", 30, " ", STR_PAD_BOTH) . "\n"; for ($i = 0; $i < $n; $i++) { // Lower Triangular for ($j = 0; $j < $n; $j++) echo str_pad($lower[$i][$j], 6, " ", STR_PAD_BOTH)."\t"; echo "\t"; // Transpose of // Lower Triangular for ($j = 0; $j < $n; $j++) echo str_pad($lower[$j][$i], 6, " ", STR_PAD_BOTH)."\t"; echo "\n"; }} // Driver Code$n = 3;$matrix = array(array(4, 12, -16), array(12, 37, -43), array(-16, -43, 98));Cholesky_Decomposition($matrix, $n); // This code is contributed by vt_m.?> <script>// javascript program to decompose// a matrix using Cholesky// Decomposition // function MAX = 100;function Cholesky_Decomposition(matrix,n){ var lower = Array(n).fill(0).map(x => Array(n).fill(0)); // Decomposing a matrix // into Lower Triangular for (var i = 0; i < n; i++) { for (var j = 0; j <= i; j++) { var sum = 0; // summation for diagonals if (j == i) { for (var k = 0; k < j; k++) sum += parseInt(Math.pow(lower[j][k], 2)); lower[j][j] = parseInt(Math.sqrt( matrix[j][j] - sum)); } else { // Evaluating L(i, j) // using L(j, j) for (var k = 0; k < j; k++) sum += (lower[i][k] * lower[j][k]); lower[i][j] = (matrix[i][j] - sum) / lower[j][j]; } } } // Displaying Lower // Triangular and its Transpose document.write(" Lower Triangular Transpose<br>"); for (var i = 0; i < n; i++) { // Lower Triangular for (var j = 0; j < n; j++) document.write(lower[i][j] + " "); // Transpose of // Lower Triangular for (var j = 0; j < n; j++) document.write(lower[j][i] + " "); document.write('<br>'); }} // Driver Codevar n = 3;var matrix = [[ 4, 12, -16 ], [ 12, 37, -43 ], [ -16, -43, 98 ] ]; Cholesky_Decomposition(matrix, n); // This code contributed by Princi Singh</script> Output: Lower Triangular Transpose 2 0 0 2 6 -8 6 1 0 0 1 5 -8 5 3 0 0 3 Time Complexity: O(n^3) Auxiliary Space: O(n^2) References: Wikipedia – Cholesky decomposition This article is contributed by Shubham Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar tobia princi singh gabaa406 ruhelaa48 prophet1999 Mathematical Matrix Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Modular multiplicative inverse Fizz Buzz Implementation Check if a number is Palindrome Generate all permutation of a set in Python Matrix Chain Multiplication | DP-8 Program to find largest element in an array Print a given matrix in spiral form Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7
[ { "code": null, "e": 25963, "s": 25935, "text": "\n30 Jan, 2022" }, { "code": null, "e": 26175, "s": 25963, "text": "In linear algebra, a matrix decomposition or matrix factorization is a factorization of a matrix into a product of matrices. There are many different matrix decompositions. One of them is Cholesky Decomposition." }, { "code": null, "e": 26485, "s": 26175, "text": "The Cholesky decomposition or Cholesky factorization is a decomposition of a Hermitian, positive-definite matrix into the product of a lower triangular matrix and its conjugate transpose. The Cholesky decomposition is roughly twice as efficient as the LU decomposition for solving systems of linear equations." }, { "code": null, "e": 26868, "s": 26485, "text": "The Cholesky decomposition of a Hermitian positive-definite matrix A is a decomposition of the form A = [L][L]T, where L is a lower triangular matrix with real and positive diagonal entries, and LT denotes the conjugate transpose of L. Every Hermitian positive-definite matrix (and thus also every real-valued symmetric positive-definite matrix) has a unique Cholesky decomposition." }, { "code": null, "e": 27014, "s": 26870, "text": "Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L LT " }, { "code": null, "e": 27169, "s": 27014, "text": "The following formulas are obtained by solving above lower triangular matrix and its transpose. These are the basis of Cholesky Decomposition Algorithm : " }, { "code": null, "e": 27182, "s": 27171, "text": "Example : " }, { "code": null, "e": 27191, "s": 27182, "text": "Input : " }, { "code": null, "e": 27200, "s": 27191, "text": "Output :" }, { "code": null, "e": 27257, "s": 27200, "text": "Below is the implementation of Cholesky Decomposition. " }, { "code": null, "e": 27261, "s": 27257, "text": "C++" }, { "code": null, "e": 27266, "s": 27261, "text": "Java" }, { "code": null, "e": 27274, "s": 27266, "text": "Python3" }, { "code": null, "e": 27277, "s": 27274, "text": "C#" }, { "code": null, "e": 27281, "s": 27277, "text": "PHP" }, { "code": null, "e": 27292, "s": 27281, "text": "Javascript" }, { "code": "// CPP program to decompose a matrix using// Cholesky Decomposition#include <bits/stdc++.h>using namespace std; const int MAX = 100; void Cholesky_Decomposition(int matrix[][MAX], int n){ int lower[n][n]; memset(lower, 0, sizeof(lower)); // Decomposing a matrix into Lower Triangular for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { int sum = 0; if (j == i) // summation for diagonals { for (int k = 0; k < j; k++) sum += pow(lower[j][k], 2); lower[j][j] = sqrt(matrix[j][j] - sum); } else { // Evaluating L(i, j) using L(j, j) for (int k = 0; k < j; k++) sum += (lower[i][k] * lower[j][k]); lower[i][j] = (matrix[i][j] - sum) / lower[j][j]; } } } // Displaying Lower Triangular and its Transpose cout << setw(6) << \" Lower Triangular\" << setw(30) << \"Transpose\" << endl; for (int i = 0; i < n; i++) { // Lower Triangular for (int j = 0; j < n; j++) cout << setw(6) << lower[i][j] << \"\\t\"; cout << \"\\t\"; // Transpose of Lower Triangular for (int j = 0; j < n; j++) cout << setw(6) << lower[j][i] << \"\\t\"; cout << endl; }} // Driver Codeint main(){ int n = 3; int matrix[][MAX] = { { 4, 12, -16 }, { 12, 37, -43 }, { -16, -43, 98 } }; Cholesky_Decomposition(matrix, n); return 0;}", "e": 28959, "s": 27292, "text": null }, { "code": "// Java program to decompose// a matrix using Cholesky// Decomposition class GFG { // static int MAX = 100; static void Cholesky_Decomposition(int[][] matrix, int n) { int[][] lower = new int[n][n]; // Decomposing a matrix // into Lower Triangular for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { int sum = 0; // summation for diagonals if (j == i) { for (int k = 0; k < j; k++) sum += (int)Math.pow(lower[j][k], 2); lower[j][j] = (int)Math.sqrt( matrix[j][j] - sum); } else { // Evaluating L(i, j) // using L(j, j) for (int k = 0; k < j; k++) sum += (lower[i][k] * lower[j][k]); lower[i][j] = (matrix[i][j] - sum) / lower[j][j]; } } } // Displaying Lower // Triangular and its Transpose System.out.println(\" Lower Triangular\\t Transpose\"); for (int i = 0; i < n; i++) { // Lower Triangular for (int j = 0; j < n; j++) System.out.print(lower[i][j] + \"\\t\"); System.out.print(\"\"); // Transpose of // Lower Triangular for (int j = 0; j < n; j++) System.out.print(lower[j][i] + \"\\t\"); System.out.println(); } } // Driver Code public static void main(String[] args) { int n = 3; int[][] matrix = new int[][] { { 4, 12, -16 }, { 12, 37, -43 }, { -16, -43, 98 } }; Cholesky_Decomposition(matrix, n); }} // This code is contributed by mits", "e": 30921, "s": 28959, "text": null }, { "code": "# Python3 program to decompose# a matrix using Cholesky# Decompositionimport mathMAX = 100; def Cholesky_Decomposition(matrix, n): lower = [[0 for x in range(n + 1)] for y in range(n + 1)]; # Decomposing a matrix # into Lower Triangular for i in range(n): for j in range(i + 1): sum1 = 0; # summation for diagonals if (j == i): for k in range(j): sum1 += pow(lower[j][k], 2); lower[j][j] = int(math.sqrt(matrix[j][j] - sum1)); else: # Evaluating L(i, j) # using L(j, j) for k in range(j): sum1 += (lower[i][k] *lower[j][k]); if(lower[j][j] > 0): lower[i][j] = int((matrix[i][j] - sum1) / lower[j][j]); # Displaying Lower Triangular # and its Transpose print(\"Lower Triangular\\t\\tTranspose\"); for i in range(n): # Lower Triangular for j in range(n): print(lower[i][j], end = \"\\t\"); print(\"\", end = \"\\t\"); # Transpose of # Lower Triangular for j in range(n): print(lower[j][i], end = \"\\t\"); print(\"\"); # Driver Coden = 3;matrix = [[4, 12, -16], [12, 37, -43], [-16, -43, 98]];Cholesky_Decomposition(matrix, n); # This code is contributed by mits", "e": 32376, "s": 30921, "text": null }, { "code": "// C# program to decompose// a matrix using Cholesky// Decompositionusing System; class GFG { // static int MAX = 100; static void Cholesky_Decomposition(int[, ] matrix, int n) { int[, ] lower = new int[n, n]; // Decomposing a matrix // into Lower Triangular for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { int sum = 0; // summation for diagonals if (j == i) { for (int k = 0; k < j; k++) sum += (int)Math.Pow(lower[j, k], 2); lower[j, j] = (int)Math.Sqrt( matrix[j, j] - sum); } else { // Evaluating L(i, j) // using L(j, j) for (int k = 0; k < j; k++) sum += (lower[i, k] * lower[j, k]); lower[i, j] = (matrix[i, j] - sum) / lower[j, j]; } } } // Displaying Lower // Triangular and its Transpose Console.WriteLine( \" Lower Triangular\\t Transpose\"); for (int i = 0; i < n; i++) { // Lower Triangular for (int j = 0; j < n; j++) Console.Write(lower[i, j] + \"\\t\"); Console.Write(\"\"); // Transpose of // Lower Triangular for (int j = 0; j < n; j++) Console.Write(lower[j, i] + \"\\t\"); Console.WriteLine(); } } // Driver Code static int Main() { int n = 3; int[, ] matrix = { { 4, 12, -16 }, { 12, 37, -43 }, { -16, -43, 98 } }; Cholesky_Decomposition(matrix, n); return 0; }} // This code is contributed by mits", "e": 34313, "s": 32376, "text": null }, { "code": "<?php// PHP program to decompose// a matrix using Cholesky// Decomposition$MAX = 100; function Cholesky_Decomposition($matrix, $n){ $lower; for ($i = 0; $i <= $n; $i++) for ($j = 0; $j <= $n; $j++) $lower[$i][$j] = 0; // Decomposing a matrix // into Lower Triangular for ($i = 0; $i < $n; $i++) { for ($j = 0; $j <= $i; $j++) { $sum = 0; // summation for diagonals if ($j == $i) { for ($k = 0; $k < $j; $k++) $sum += pow($lower[$j][$k], 2); $lower[$j][$j] = sqrt($matrix[$j][$j] - $sum); } else { // Evaluating L(i, j) // using L(j, j) for ($k = 0; $k < $j; $k++) $sum += ($lower[$i][$k] * $lower[$j][$k]); $lower[$i][$j] = ($matrix[$i][$j] - $sum) / $lower[$j][$j]; } } } // Displaying Lower Triangular // and its Transpose echo \" Lower Triangular\" . str_pad(\"Transpose\", 30, \" \", STR_PAD_BOTH) . \"\\n\"; for ($i = 0; $i < $n; $i++) { // Lower Triangular for ($j = 0; $j < $n; $j++) echo str_pad($lower[$i][$j], 6, \" \", STR_PAD_BOTH).\"\\t\"; echo \"\\t\"; // Transpose of // Lower Triangular for ($j = 0; $j < $n; $j++) echo str_pad($lower[$j][$i], 6, \" \", STR_PAD_BOTH).\"\\t\"; echo \"\\n\"; }} // Driver Code$n = 3;$matrix = array(array(4, 12, -16), array(12, 37, -43), array(-16, -43, 98));Cholesky_Decomposition($matrix, $n); // This code is contributed by vt_m.?>", "e": 36153, "s": 34313, "text": null }, { "code": "<script>// javascript program to decompose// a matrix using Cholesky// Decomposition // function MAX = 100;function Cholesky_Decomposition(matrix,n){ var lower = Array(n).fill(0).map(x => Array(n).fill(0)); // Decomposing a matrix // into Lower Triangular for (var i = 0; i < n; i++) { for (var j = 0; j <= i; j++) { var sum = 0; // summation for diagonals if (j == i) { for (var k = 0; k < j; k++) sum += parseInt(Math.pow(lower[j][k], 2)); lower[j][j] = parseInt(Math.sqrt( matrix[j][j] - sum)); } else { // Evaluating L(i, j) // using L(j, j) for (var k = 0; k < j; k++) sum += (lower[i][k] * lower[j][k]); lower[i][j] = (matrix[i][j] - sum) / lower[j][j]; } } } // Displaying Lower // Triangular and its Transpose document.write(\" Lower Triangular Transpose<br>\"); for (var i = 0; i < n; i++) { // Lower Triangular for (var j = 0; j < n; j++) document.write(lower[i][j] + \" \"); // Transpose of // Lower Triangular for (var j = 0; j < n; j++) document.write(lower[j][i] + \" \"); document.write('<br>'); }} // Driver Codevar n = 3;var matrix = [[ 4, 12, -16 ], [ 12, 37, -43 ], [ -16, -43, 98 ] ]; Cholesky_Decomposition(matrix, n); // This code contributed by Princi Singh</script>", "e": 37823, "s": 36153, "text": null }, { "code": null, "e": 37832, "s": 37823, "text": "Output: " }, { "code": null, "e": 37965, "s": 37832, "text": "Lower Triangular Transpose\n2 0 0 2 6 -8 \n6 1 0 0 1 5 \n-8 5 3 0 0 3 " }, { "code": null, "e": 37989, "s": 37965, "text": "Time Complexity: O(n^3)" }, { "code": null, "e": 38013, "s": 37989, "text": "Auxiliary Space: O(n^2)" }, { "code": null, "e": 38061, "s": 38013, "text": "References: Wikipedia – Cholesky decomposition " }, { "code": null, "e": 38482, "s": 38061, "text": "This article is contributed by Shubham Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 38495, "s": 38482, "text": "Mithun Kumar" }, { "code": null, "e": 38501, "s": 38495, "text": "tobia" }, { "code": null, "e": 38514, "s": 38501, "text": "princi singh" }, { "code": null, "e": 38523, "s": 38514, "text": "gabaa406" }, { "code": null, "e": 38533, "s": 38523, "text": "ruhelaa48" }, { "code": null, "e": 38545, "s": 38533, "text": "prophet1999" }, { "code": null, "e": 38558, "s": 38545, "text": "Mathematical" }, { "code": null, "e": 38565, "s": 38558, "text": "Matrix" }, { "code": null, "e": 38578, "s": 38565, "text": "Mathematical" }, { "code": null, "e": 38585, "s": 38578, "text": "Matrix" }, { "code": null, "e": 38683, "s": 38585, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38727, "s": 38683, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 38758, "s": 38727, "text": "Modular multiplicative inverse" }, { "code": null, "e": 38783, "s": 38758, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 38815, "s": 38783, "text": "Check if a number is Palindrome" }, { "code": null, "e": 38859, "s": 38815, "text": "Generate all permutation of a set in Python" }, { "code": null, "e": 38894, "s": 38859, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 38938, "s": 38894, "text": "Program to find largest element in an array" }, { "code": null, "e": 38974, "s": 38938, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 39005, "s": 38974, "text": "Rat in a Maze | Backtracking-2" } ]
How to make the cursor to hand when a user hovers over a list item using CSS? - GeeksforGeeks
06 Dec, 2018 Use CSS property to create cursor to hand when user hovers over the list of items. First create list of items using HTML <ul> and <li> tag and then use CSS property :hover to cursor:grab; to make cursor to hand hover the list of items. Syntax: element:hover { cursor:grab/pointer; } Example 1: <!DOCTYPE html><html> <head> <title>make cursor to hand</title> <style> body { width:70%; } h1 { color:green; text-align:center; } li:hover{ cursor:grab; } </style> </head> <body> <h1>GeeksforGeeks</h1> <div class = "sub">Computer Science Subject Lists:</div> <ul> <li>Data Structure</li> <li>Algorithm</li> <li>Operating System</li> <li>Computer Networks</li> <li>C Programming</li> <li>Java</li> <li>DBMS</li> </ul> </body></html> Output: Example 2: This example contains CSS property to change cursor pointer alternate. In this example, use nth-child(2n+1) as cursor:grab; and use nth-child(2n+2) as cursor:pointer;. <!DOCTYPE html><html> <head> <title>make cursor to hand</title> <style> body { width:60%; } h1 { color:green; text-align:center; } li { font-size:20px; } li:nth-child(2n+1) { background: green; cursor:grab; width:50%; padding:5px; } li:nth-child(2n+2) { background: #CCC; cursor:pointer; width:50%; padding:5px; } </style> </head> <body> <h1>GeeksforGeeks</h1> <div class = "sub">Computer Science Subject Lists:</div> <ul> <li>Data Structure</li> <li>Algorithm</li> <li>Operating System</li> <li>Computer Networks</li> <li>C Programming</li> <li>Java</li> <li>DBMS</li> </ul> </body></html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. Picked Technical Scripter 2018 CSS HTML Technical Scripter Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property
[ { "code": null, "e": 25435, "s": 25407, "text": "\n06 Dec, 2018" }, { "code": null, "e": 25671, "s": 25435, "text": "Use CSS property to create cursor to hand when user hovers over the list of items. First create list of items using HTML <ul> and <li> tag and then use CSS property :hover to cursor:grab; to make cursor to hand hover the list of items." }, { "code": null, "e": 25679, "s": 25671, "text": "Syntax:" }, { "code": null, "e": 25722, "s": 25679, "text": "element:hover {\n cursor:grab/pointer;\n}" }, { "code": null, "e": 25733, "s": 25722, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <title>make cursor to hand</title> <style> body { width:70%; } h1 { color:green; text-align:center; } li:hover{ cursor:grab; } </style> </head> <body> <h1>GeeksforGeeks</h1> <div class = \"sub\">Computer Science Subject Lists:</div> <ul> <li>Data Structure</li> <li>Algorithm</li> <li>Operating System</li> <li>Computer Networks</li> <li>C Programming</li> <li>Java</li> <li>DBMS</li> </ul> </body></html>", "e": 26438, "s": 25733, "text": null }, { "code": null, "e": 26446, "s": 26438, "text": "Output:" }, { "code": null, "e": 26625, "s": 26446, "text": "Example 2: This example contains CSS property to change cursor pointer alternate. In this example, use nth-child(2n+1) as cursor:grab; and use nth-child(2n+2) as cursor:pointer;." }, { "code": "<!DOCTYPE html><html> <head> <title>make cursor to hand</title> <style> body { width:60%; } h1 { color:green; text-align:center; } li { font-size:20px; } li:nth-child(2n+1) { background: green; cursor:grab; width:50%; padding:5px; } li:nth-child(2n+2) { background: #CCC; cursor:pointer; width:50%; padding:5px; } </style> </head> <body> <h1>GeeksforGeeks</h1> <div class = \"sub\">Computer Science Subject Lists:</div> <ul> <li>Data Structure</li> <li>Algorithm</li> <li>Operating System</li> <li>Computer Networks</li> <li>C Programming</li> <li>Java</li> <li>DBMS</li> </ul> </body></html>", "e": 27652, "s": 26625, "text": null }, { "code": null, "e": 27660, "s": 27652, "text": "Output:" }, { "code": null, "e": 27797, "s": 27660, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27804, "s": 27797, "text": "Picked" }, { "code": null, "e": 27828, "s": 27804, "text": "Technical Scripter 2018" }, { "code": null, "e": 27832, "s": 27828, "text": "CSS" }, { "code": null, "e": 27837, "s": 27832, "text": "HTML" }, { "code": null, "e": 27856, "s": 27837, "text": "Technical Scripter" }, { "code": null, "e": 27873, "s": 27856, "text": "Web Technologies" }, { "code": null, "e": 27900, "s": 27873, "text": "Web technologies Questions" }, { "code": null, "e": 27905, "s": 27900, "text": "HTML" }, { "code": null, "e": 28003, "s": 27905, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28053, "s": 28003, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 28115, "s": 28053, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28163, "s": 28115, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28221, "s": 28163, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28276, "s": 28221, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 28326, "s": 28276, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 28388, "s": 28326, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28436, "s": 28388, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28496, "s": 28436, "text": "How to set the default value for an HTML <select> element ?" } ]
Get the index of minimum value in DataFrame column - GeeksforGeeks
18 Dec, 2018 Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let’s see how can we get the index of minimum value in DataFrame column. Observe this dataset first. We’ll use ‘Weight’ and ‘Salary’ columns of this data in order to get the index of minimum values from a particular column in Pandas DataFrame. # importing pandas module import pandas as pd # making data frame df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") df.head(10) Code #1: Check the index at which minimum weight value is present. # importing pandas module import pandas as pd # making data frame df = pd.read_csv("nba.csv") # Returns index of minimum weightdf[['Weight']].idxmin() Output: We can verify whether the minimum value is present in index or not. # importing pandas module import pandas as pd # making data frame df = pd.read_csv("nba.csv") # from index 140 to 154df.iloc[140:155] Output: Code #2: Let’s insert a new row at index 0, having minimum salary and then print the minimum salary. # importing pandas module import pandas as pd # making data frame df = pd.read_csv("nba.csv") new_row = pd.DataFrame({'Name':'Geeks', 'Team':'Boston', 'Number':3, 'Position':'PG', 'Age':33, 'Height':'6-2', 'Weight':189, 'College':'MIT', 'Salary':99} , index=[0]) df = pd.concat([new_row, df]).reset_index(drop=True)df.head(5) Output: Now, let’s check if the minimum salary is present at index 0 or not. # Returns index of minimum salarydf[['Salary']].idxmin() Output: 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. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26373, "s": 26345, "text": "\n18 Dec, 2018" }, { "code": null, "e": 26510, "s": 26373, "text": "Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns)." }, { "code": null, "e": 26583, "s": 26510, "text": "Let’s see how can we get the index of minimum value in DataFrame column." }, { "code": null, "e": 26754, "s": 26583, "text": "Observe this dataset first. We’ll use ‘Weight’ and ‘Salary’ columns of this data in order to get the index of minimum values from a particular column in Pandas DataFrame." }, { "code": "# importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") df.head(10)", "e": 26917, "s": 26754, "text": null }, { "code": null, "e": 26984, "s": 26917, "text": "Code #1: Check the index at which minimum weight value is present." }, { "code": "# importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"nba.csv\") # Returns index of minimum weightdf[['Weight']].idxmin()", "e": 27140, "s": 26984, "text": null }, { "code": null, "e": 27148, "s": 27140, "text": "Output:" }, { "code": null, "e": 27216, "s": 27148, "text": "We can verify whether the minimum value is present in index or not." }, { "code": " # importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"nba.csv\") # from index 140 to 154df.iloc[140:155]", "e": 27360, "s": 27216, "text": null }, { "code": null, "e": 27368, "s": 27360, "text": "Output:" }, { "code": null, "e": 27470, "s": 27368, "text": " Code #2: Let’s insert a new row at index 0, having minimum salary and then print the minimum salary." }, { "code": "# importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"nba.csv\") new_row = pd.DataFrame({'Name':'Geeks', 'Team':'Boston', 'Number':3, 'Position':'PG', 'Age':33, 'Height':'6-2', 'Weight':189, 'College':'MIT', 'Salary':99} , index=[0]) df = pd.concat([new_row, df]).reset_index(drop=True)df.head(5)", "e": 27875, "s": 27470, "text": null }, { "code": null, "e": 27883, "s": 27875, "text": "Output:" }, { "code": null, "e": 27952, "s": 27883, "text": "Now, let’s check if the minimum salary is present at index 0 or not." }, { "code": "# Returns index of minimum salarydf[['Salary']].idxmin()", "e": 28009, "s": 27952, "text": null }, { "code": null, "e": 28017, "s": 28009, "text": "Output:" }, { "code": null, "e": 28042, "s": 28017, "text": "pandas-dataframe-program" }, { "code": null, "e": 28066, "s": 28042, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28080, "s": 28066, "text": "Python-pandas" }, { "code": null, "e": 28087, "s": 28080, "text": "Python" }, { "code": null, "e": 28185, "s": 28087, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28203, "s": 28185, "text": "Python Dictionary" }, { "code": null, "e": 28238, "s": 28203, "text": "Read a file line by line in Python" }, { "code": null, "e": 28270, "s": 28238, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28292, "s": 28270, "text": "Enumerate() in Python" }, { "code": null, "e": 28334, "s": 28292, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28364, "s": 28334, "text": "Iterate over a list in Python" }, { "code": null, "e": 28390, "s": 28364, "text": "Python String | replace()" }, { "code": null, "e": 28419, "s": 28390, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28463, "s": 28419, "text": "Reading and Writing to text files in Python" } ]
Evaluating Classification Models. A Guided Walkthrough Using Sci-Kit... | by Ishaan Dey | Towards Data Science
Authors: Ishaan Dey, Evan Heitman, & Jagerynn T. Verano A doctor wants to know if his patient has a disease. A credit card company is interested in determining if a certain transaction is a fraud. A graduate school candidate is interested if whether or not it’s likely that she gets accepted into her program. Many applied models are interested in predicting the outcome of a binary event, which is any event that can be answered by a simple yes or no question. This is called a binary classification problem, and is distinct from multi-class classification, where we would be interested in predicting which disease an individual would have, or which product a customer would purchase from a selection. Overview Regression models will often report familiar metrics, such as R2, to show goodness-of-fit, or how well the model can adhere to the data. With discrete outcomes, we cannot apply the same formulas, so in this post, we will examine how to evaluate a classifier model’s performance, by breaking down the types of error a model can mistake and quantitative measures that can summarize a model’s ability to perform as we expect it to. Throughout this post, we use a credit card transaction dataset, with targets labelling a fraudulent transaction (a binary outcome, with 1 indicating fraud). Given the low occurrence of fraud, the dataset was under-sampled to create a new distribution of 90:10 non-fraud to fraud observations. That data was further split into a 70:30 train to test split. We fitted a logistic regression model, and used a threshold of 0.5 to predict values as a fraud. You can follow along using the interactive python notebook linked below. https://github.com/ishaandey/Classification_Evaluation_Walkthrough For any dataset containing binary outcomes, we can label all observations with a 1 (indicating the occurrence of an event) or 0 (the absence of an event). We can fit a model to the feature variables and make a prediction for each observation given the set of feature variables. Values that are correctly classified by the model are labelled true (T), while incorrect predictions are false (F). Positive (P) and negative (N) refer to the model’s prediction, as opposed to the actual value of the observation. For example, a negative value incorrectly classified as positive is called a false positive. As an aside, many readers will be familiar with false positives and false negatives as α and β, respectively. False positives are denoted by alpha (α) while false negatives are denoted by beta (β). Thus, when we suggest a probability of a statistic is less than α of 0.05, we say that the probability of incorrectly labelling that outcome as significant is 0.05. Our model, produced with the function below, produced the following confusion matrix. confusion_matrix(y_test, y_pred) Say we come across a diagnostic tool for detecting cancer that says it can correctly predict outcomes with a 99.8% accuracy. Is that really that impressive though? According to CDC estimates, the cancer mortality rate among the general population is about 0.16%. If we were to make a dummy model, and say that regardless of the feature information available to us, each and every outcome should be classified as a negative case, we’d be performing at a 99.84% accuracy, simply because 99.84% of the observations in our sample are negative. We’d have missed diagnosing every single one of the patients with cancer, but we can still truthfully report that our model operates with a 99.84% accuracy. Clearly, a good model should be able to distinguish between what is and isn’t a positive case. In a more technical sense, the value for accuracy can be obtained from the confusion matrix quite easily, as the number of true positives and true negatives divided by the total number of observations tested on. In simpler terms, it’s the proportion of observations correctly classified. Accuracy = (TP + TN) / (TP + TN + FP + FN) Going back our fraud detection data, our logistic regression model predicts with an accuracy of 97.7%. But how much better does this work than a dummy classifier? Let’s look at the actual distribution of outcome. sns.countplot(x=fraud['Class']) Here, the class imbalance, or the skewed distribution of outcomes is obvious. A quick check using the .value_counts() function shows that we have 137 counts of fraud cases in our data, and 1339 counts of non-fraud cases, meaning that 9.3% of our test cases are fraudulent. If we were to apply a dummy model that blindly predicts all observations to be a non-fraud case, as can be done with the sklearn.dummy package, we can see that our reported accuracy of 90.7% matches that of our frequency distribution (90.7:9.3). So, even though our dummy model is quite useless, we can still report that it performs at a 90% accuracy. The confusion matrix below shows this inability to distinguish in further detail. y_test.value_counts() / len(y_test)dum = DummyClassifier(strategy='most_frequent') The biggest perk of using the confusion matrix is that we can easily pull out various other values that reflect how well our model runs relative what we’d expect from a dummy model. Sensitivity (or Recall, or True Positive Rate) As we saw with the above example, a good model should successfully detect close to all of the actual fraudulent cases, given how much higher a cost of not catching a fraud case is relative to putting a non-fraudulent transaction under scrutiny by incorrectly suggesting that it was a fraud case. Sensitivity, also known as recall, quantifies that intuition, and reflects the ratio of correctly classified positives to actual positive cases. Sensitivity = TP / (TP + FN) Interpretation of sensitivity is fairly straightforward. All values range between 0 and 1, where a value of 1 indicates that the model detected every single case of fraud, while a value of 0 indicates that all the actual cases of fraud were not detected. With our logistic regression model, we have a sensitivity of 108 / 137 = 0.788. Specificity Specificity helps us determine how many were correctly classified as non-fraud out of total true non-fraud cases. The false positive rate, or the false alarm rate, is the opposite of specificity. In our fraud detection model, we have a specificity of 1334/1339 = 0.996 Specificity = TN / (TN + FP) False-positive rate= 1 — Specificity In this particular case, specificity is a less relevant metric as the cost of classifying a non-fraud case as a fraud case is lower than missing a fraud case entirely. But there are cases where false alarms are equally undesirable, such as in disease detection, where misdiagnosis would lead to unnecessary follow-up procedures. Precision On the other hand, we may want to test the certainty of our predictions, for example, we may in interested how many of the fraud cases that our model says it picked up were truly fraudulent. Precision does just that, by providing the proportion of true positives relative to the number of predicted positives. Intuitively, a low precision would mean that we’re giving a lot of customers headaches, in that we’re classifying more fraudulent transactions than what’s actually fraudulent. With the logistic regression model, our precision is 108/113 = 0.956 Precision = TP / (TP + FP) In our fraud dataset, it’s more important that we minimize the number of fraud cases that go undetected, even if it comes at a cost of incorrectly classifying non-fraud cases as fraudulent, simply because the cost to the firm is far higher for the former case (potentially thousands of dollars in lost revenue or a few minutes of a customer’s time to verify their transaction). In other words, we would rather commit a type I error than a type II error. Although we would prefer a model that maximizes both sensitivity and specificity, we would prefer a model with a maximum sensitivity, as it minimizes the occurrences of a type II error. F1 Score Last but not least, the F1 score summarizes both precision and recall and can be understood as the harmonic mean of the two measures. An F1 score of 1 indicates perfect precision and recall, therefore the higher the F1 score, the better the model. Our logistic model shows a F1 score of 0.864. F1 = 2 * (Precision * Sensitivity) / (Precision + Sensitivity) How exactly are we coming up with our predictions? From our logistic regression, we compute a predicted probability of a given observation being fraudulent that falls between 0 to 1. We say that all probabilities greater than 0.5 should indicate a prediction of a fraud, while all values less than 0.5 return a prediction of a legitimate transaction. But given how much more willing we are to make a Type I error, wouldn’t it be better to classify a case as fraudulent even if there’s only a slight probability that it is? In other words, what if we lower our threshold for discriminating between a fraud and non-fraud, such that we catch more frauds, from shifting it down from the orange to green line? From the definitions we discussed previously, the specificity of the model would increase, as we’ve now classified more positives, but at the same time, we increase the likelihood that we’re incorrectly labelling a non-fraudulent case as a fraud, thus dropping the sensitivity as the number of false negatives is increasing. It’s a constant trade-off, and the rate at which the sensitivity increases from dropping specificity is an attribute specific to each model. Thus far, we’ve been reporting our metrics from a confusion matrix calculated at a threshold of 0.5 (the orange line), but if we were to lower the discrimination threshold to 0.1 (the green line), the sensitivity increases from .788 to .883, while the specificity drops from .996 to .823. classification_report(y_test, y_pred) ROC Curve We can see the change in these values at all thresholds using a Receiver Operating Characteristic, or ROC Curve, which plots the true positive rate against the false positive rate, or the sensitivity against 1-specificity for each threshold. We can see here the ROC curve for our logistic classifier, in which the different thresholds are applied to the predicted probabilities to produce different true positive and false positive rates. Our dummy model is a point at (0,0) on the blue curve where the discrimination threshold is such that any probability <1.0 is predicted as a non-fraud case. This indicates that though the we correctly classified all of the non-fraud cases, we incorrectly classified all non-fraud cases. A perfectly discriminating model, on the other hand, would have a point on curve at (0,1), which would indicate our model perfectly classifying all fraud cases as well as non-fraud cases. The lines for both of these model would be generated as a function of the threshold level. fpr, tpr, thresholds = roc_curve(y_test, y_pred_prob[:,1]) The diagonal line shows where true positive rate is the same as false positive rate, where there is an equal chance of correctly detecting a fraud case and detecting a non-fraud case as fraudulent. This means that any ROC curve above the diagonal does better than random chance of predicting outcomes, assuming a 50/50 class balance. Thus, all ROC curves that we’ll encounter in the field will be drawn above the y=x line, and below the line going vertically up to (0,1), then horizontally across to (1,1). We can quantify the degree to which a ROC curve performs by looking at the area under the curve, or AUC ROC. This value will adopt values between 0.5 (of the diagonal line) and 1.0 (for a perfect model). Our fraud detection model performs with an AUC ROC of 0.934, not bad for an out-of-box model. from sklearn.metrics import aucauc = roc_auc_score(y_test,logis_pred_prob[:,1]) PRC Curve Going back to the logit model, what happens to precision and recall when we shift our discrimination threshold from the orange to green? As we move from a threshold of 0.5 to 0.1, the recall increases from 0.788 to 0.883, since the proportion of correctly detected frauds over the actual number of frauds increases, while the precision drops from 0.956 to 0.338, as the proportion of true fraud cases over the predicted number of fraud cases decreases. Just as we did with the ROC curve, we can plot the trade-off between precision and recall as a function of the thresholds, and obtain a Precision-Recall Curve, or PRC. precision, recall, thresholds = precision_recall_curve(y_test, y_pred_prob[:,1]) Typically, PRCs are better suited for models trained on highly imbalanced datasets, as the high true negative value used in the formulation of the ROC curve’s false positive rate can ‘inflate’ the perception of how well the model performs. PRC curves avoid this value, and can thus reflect a less biased metric for the model’s performance. We can summarize this curve succinctly using an average precision value or average F1 score (averaged across each threshold), with an ideal value close to 1. from sklearn.metrics import f1_scorefrom sklearn.metrics import average_precision_scoref1 = f1_score(y_test, y_pred_prob)ap = average_precision_score(y_test, y_pred_prob) Quick review of formulas: In this post, we discussed how to move past accuracy as a measure of performance for a binary classifier. We discussed sensitivity, specificity, precision and recall. We looked at what happens when we change our decision threshold, and how we can visualize the trade-off between sensitivity and specificity, as well as between precision and recall. As a reminder, all the visualizations and model produced can be found on the interactive python notebook, linked below. https://github.com/ishaandey/Classification_Evaluation_Walkthrough That’s it for this post. Let us know if you have any questions!
[ { "code": null, "e": 228, "s": 172, "text": "Authors: Ishaan Dey, Evan Heitman, & Jagerynn T. Verano" }, { "code": null, "e": 875, "s": 228, "text": "A doctor wants to know if his patient has a disease. A credit card company is interested in determining if a certain transaction is a fraud. A graduate school candidate is interested if whether or not it’s likely that she gets accepted into her program. Many applied models are interested in predicting the outcome of a binary event, which is any event that can be answered by a simple yes or no question. This is called a binary classification problem, and is distinct from multi-class classification, where we would be interested in predicting which disease an individual would have, or which product a customer would purchase from a selection." }, { "code": null, "e": 884, "s": 875, "text": "Overview" }, { "code": null, "e": 1313, "s": 884, "text": "Regression models will often report familiar metrics, such as R2, to show goodness-of-fit, or how well the model can adhere to the data. With discrete outcomes, we cannot apply the same formulas, so in this post, we will examine how to evaluate a classifier model’s performance, by breaking down the types of error a model can mistake and quantitative measures that can summarize a model’s ability to perform as we expect it to." }, { "code": null, "e": 1838, "s": 1313, "text": "Throughout this post, we use a credit card transaction dataset, with targets labelling a fraudulent transaction (a binary outcome, with 1 indicating fraud). Given the low occurrence of fraud, the dataset was under-sampled to create a new distribution of 90:10 non-fraud to fraud observations. That data was further split into a 70:30 train to test split. We fitted a logistic regression model, and used a threshold of 0.5 to predict values as a fraud. You can follow along using the interactive python notebook linked below." }, { "code": null, "e": 1905, "s": 1838, "text": "https://github.com/ishaandey/Classification_Evaluation_Walkthrough" }, { "code": null, "e": 2506, "s": 1905, "text": "For any dataset containing binary outcomes, we can label all observations with a 1 (indicating the occurrence of an event) or 0 (the absence of an event). We can fit a model to the feature variables and make a prediction for each observation given the set of feature variables. Values that are correctly classified by the model are labelled true (T), while incorrect predictions are false (F). Positive (P) and negative (N) refer to the model’s prediction, as opposed to the actual value of the observation. For example, a negative value incorrectly classified as positive is called a false positive." }, { "code": null, "e": 2869, "s": 2506, "text": "As an aside, many readers will be familiar with false positives and false negatives as α and β, respectively. False positives are denoted by alpha (α) while false negatives are denoted by beta (β). Thus, when we suggest a probability of a statistic is less than α of 0.05, we say that the probability of incorrectly labelling that outcome as significant is 0.05." }, { "code": null, "e": 2955, "s": 2869, "text": "Our model, produced with the function below, produced the following confusion matrix." }, { "code": null, "e": 2988, "s": 2955, "text": "confusion_matrix(y_test, y_pred)" }, { "code": null, "e": 3780, "s": 2988, "text": "Say we come across a diagnostic tool for detecting cancer that says it can correctly predict outcomes with a 99.8% accuracy. Is that really that impressive though? According to CDC estimates, the cancer mortality rate among the general population is about 0.16%. If we were to make a dummy model, and say that regardless of the feature information available to us, each and every outcome should be classified as a negative case, we’d be performing at a 99.84% accuracy, simply because 99.84% of the observations in our sample are negative. We’d have missed diagnosing every single one of the patients with cancer, but we can still truthfully report that our model operates with a 99.84% accuracy. Clearly, a good model should be able to distinguish between what is and isn’t a positive case." }, { "code": null, "e": 4068, "s": 3780, "text": "In a more technical sense, the value for accuracy can be obtained from the confusion matrix quite easily, as the number of true positives and true negatives divided by the total number of observations tested on. In simpler terms, it’s the proportion of observations correctly classified." }, { "code": null, "e": 4111, "s": 4068, "text": "Accuracy = (TP + TN) / (TP + TN + FP + FN)" }, { "code": null, "e": 4324, "s": 4111, "text": "Going back our fraud detection data, our logistic regression model predicts with an accuracy of 97.7%. But how much better does this work than a dummy classifier? Let’s look at the actual distribution of outcome." }, { "code": null, "e": 4356, "s": 4324, "text": "sns.countplot(x=fraud['Class'])" }, { "code": null, "e": 5063, "s": 4356, "text": "Here, the class imbalance, or the skewed distribution of outcomes is obvious. A quick check using the .value_counts() function shows that we have 137 counts of fraud cases in our data, and 1339 counts of non-fraud cases, meaning that 9.3% of our test cases are fraudulent. If we were to apply a dummy model that blindly predicts all observations to be a non-fraud case, as can be done with the sklearn.dummy package, we can see that our reported accuracy of 90.7% matches that of our frequency distribution (90.7:9.3). So, even though our dummy model is quite useless, we can still report that it performs at a 90% accuracy. The confusion matrix below shows this inability to distinguish in further detail." }, { "code": null, "e": 5146, "s": 5063, "text": "y_test.value_counts() / len(y_test)dum = DummyClassifier(strategy='most_frequent')" }, { "code": null, "e": 5328, "s": 5146, "text": "The biggest perk of using the confusion matrix is that we can easily pull out various other values that reflect how well our model runs relative what we’d expect from a dummy model." }, { "code": null, "e": 5375, "s": 5328, "text": "Sensitivity (or Recall, or True Positive Rate)" }, { "code": null, "e": 5816, "s": 5375, "text": "As we saw with the above example, a good model should successfully detect close to all of the actual fraudulent cases, given how much higher a cost of not catching a fraud case is relative to putting a non-fraudulent transaction under scrutiny by incorrectly suggesting that it was a fraud case. Sensitivity, also known as recall, quantifies that intuition, and reflects the ratio of correctly classified positives to actual positive cases." }, { "code": null, "e": 5845, "s": 5816, "text": "Sensitivity = TP / (TP + FN)" }, { "code": null, "e": 6180, "s": 5845, "text": "Interpretation of sensitivity is fairly straightforward. All values range between 0 and 1, where a value of 1 indicates that the model detected every single case of fraud, while a value of 0 indicates that all the actual cases of fraud were not detected. With our logistic regression model, we have a sensitivity of 108 / 137 = 0.788." }, { "code": null, "e": 6192, "s": 6180, "text": "Specificity" }, { "code": null, "e": 6461, "s": 6192, "text": "Specificity helps us determine how many were correctly classified as non-fraud out of total true non-fraud cases. The false positive rate, or the false alarm rate, is the opposite of specificity. In our fraud detection model, we have a specificity of 1334/1339 = 0.996" }, { "code": null, "e": 6490, "s": 6461, "text": "Specificity = TN / (TN + FP)" }, { "code": null, "e": 6527, "s": 6490, "text": "False-positive rate= 1 — Specificity" }, { "code": null, "e": 6856, "s": 6527, "text": "In this particular case, specificity is a less relevant metric as the cost of classifying a non-fraud case as a fraud case is lower than missing a fraud case entirely. But there are cases where false alarms are equally undesirable, such as in disease detection, where misdiagnosis would lead to unnecessary follow-up procedures." }, { "code": null, "e": 6866, "s": 6856, "text": "Precision" }, { "code": null, "e": 7421, "s": 6866, "text": "On the other hand, we may want to test the certainty of our predictions, for example, we may in interested how many of the fraud cases that our model says it picked up were truly fraudulent. Precision does just that, by providing the proportion of true positives relative to the number of predicted positives. Intuitively, a low precision would mean that we’re giving a lot of customers headaches, in that we’re classifying more fraudulent transactions than what’s actually fraudulent. With the logistic regression model, our precision is 108/113 = 0.956" }, { "code": null, "e": 7448, "s": 7421, "text": "Precision = TP / (TP + FP)" }, { "code": null, "e": 8088, "s": 7448, "text": "In our fraud dataset, it’s more important that we minimize the number of fraud cases that go undetected, even if it comes at a cost of incorrectly classifying non-fraud cases as fraudulent, simply because the cost to the firm is far higher for the former case (potentially thousands of dollars in lost revenue or a few minutes of a customer’s time to verify their transaction). In other words, we would rather commit a type I error than a type II error. Although we would prefer a model that maximizes both sensitivity and specificity, we would prefer a model with a maximum sensitivity, as it minimizes the occurrences of a type II error." }, { "code": null, "e": 8097, "s": 8088, "text": "F1 Score" }, { "code": null, "e": 8391, "s": 8097, "text": "Last but not least, the F1 score summarizes both precision and recall and can be understood as the harmonic mean of the two measures. An F1 score of 1 indicates perfect precision and recall, therefore the higher the F1 score, the better the model. Our logistic model shows a F1 score of 0.864." }, { "code": null, "e": 8454, "s": 8391, "text": "F1 = 2 * (Precision * Sensitivity) / (Precision + Sensitivity)" }, { "code": null, "e": 8805, "s": 8454, "text": "How exactly are we coming up with our predictions? From our logistic regression, we compute a predicted probability of a given observation being fraudulent that falls between 0 to 1. We say that all probabilities greater than 0.5 should indicate a prediction of a fraud, while all values less than 0.5 return a prediction of a legitimate transaction." }, { "code": null, "e": 9159, "s": 8805, "text": "But given how much more willing we are to make a Type I error, wouldn’t it be better to classify a case as fraudulent even if there’s only a slight probability that it is? In other words, what if we lower our threshold for discriminating between a fraud and non-fraud, such that we catch more frauds, from shifting it down from the orange to green line?" }, { "code": null, "e": 9625, "s": 9159, "text": "From the definitions we discussed previously, the specificity of the model would increase, as we’ve now classified more positives, but at the same time, we increase the likelihood that we’re incorrectly labelling a non-fraudulent case as a fraud, thus dropping the sensitivity as the number of false negatives is increasing. It’s a constant trade-off, and the rate at which the sensitivity increases from dropping specificity is an attribute specific to each model." }, { "code": null, "e": 9914, "s": 9625, "text": "Thus far, we’ve been reporting our metrics from a confusion matrix calculated at a threshold of 0.5 (the orange line), but if we were to lower the discrimination threshold to 0.1 (the green line), the sensitivity increases from .788 to .883, while the specificity drops from .996 to .823." }, { "code": null, "e": 9952, "s": 9914, "text": "classification_report(y_test, y_pred)" }, { "code": null, "e": 9962, "s": 9952, "text": "ROC Curve" }, { "code": null, "e": 10401, "s": 9962, "text": "We can see the change in these values at all thresholds using a Receiver Operating Characteristic, or ROC Curve, which plots the true positive rate against the false positive rate, or the sensitivity against 1-specificity for each threshold. We can see here the ROC curve for our logistic classifier, in which the different thresholds are applied to the predicted probabilities to produce different true positive and false positive rates." }, { "code": null, "e": 10967, "s": 10401, "text": "Our dummy model is a point at (0,0) on the blue curve where the discrimination threshold is such that any probability <1.0 is predicted as a non-fraud case. This indicates that though the we correctly classified all of the non-fraud cases, we incorrectly classified all non-fraud cases. A perfectly discriminating model, on the other hand, would have a point on curve at (0,1), which would indicate our model perfectly classifying all fraud cases as well as non-fraud cases. The lines for both of these model would be generated as a function of the threshold level." }, { "code": null, "e": 11026, "s": 10967, "text": "fpr, tpr, thresholds = roc_curve(y_test, y_pred_prob[:,1])" }, { "code": null, "e": 11360, "s": 11026, "text": "The diagonal line shows where true positive rate is the same as false positive rate, where there is an equal chance of correctly detecting a fraud case and detecting a non-fraud case as fraudulent. This means that any ROC curve above the diagonal does better than random chance of predicting outcomes, assuming a 50/50 class balance." }, { "code": null, "e": 11831, "s": 11360, "text": "Thus, all ROC curves that we’ll encounter in the field will be drawn above the y=x line, and below the line going vertically up to (0,1), then horizontally across to (1,1). We can quantify the degree to which a ROC curve performs by looking at the area under the curve, or AUC ROC. This value will adopt values between 0.5 (of the diagonal line) and 1.0 (for a perfect model). Our fraud detection model performs with an AUC ROC of 0.934, not bad for an out-of-box model." }, { "code": null, "e": 11911, "s": 11831, "text": "from sklearn.metrics import aucauc = roc_auc_score(y_test,logis_pred_prob[:,1])" }, { "code": null, "e": 11921, "s": 11911, "text": "PRC Curve" }, { "code": null, "e": 12542, "s": 11921, "text": "Going back to the logit model, what happens to precision and recall when we shift our discrimination threshold from the orange to green? As we move from a threshold of 0.5 to 0.1, the recall increases from 0.788 to 0.883, since the proportion of correctly detected frauds over the actual number of frauds increases, while the precision drops from 0.956 to 0.338, as the proportion of true fraud cases over the predicted number of fraud cases decreases. Just as we did with the ROC curve, we can plot the trade-off between precision and recall as a function of the thresholds, and obtain a Precision-Recall Curve, or PRC." }, { "code": null, "e": 12623, "s": 12542, "text": "precision, recall, thresholds = precision_recall_curve(y_test, y_pred_prob[:,1])" }, { "code": null, "e": 12963, "s": 12623, "text": "Typically, PRCs are better suited for models trained on highly imbalanced datasets, as the high true negative value used in the formulation of the ROC curve’s false positive rate can ‘inflate’ the perception of how well the model performs. PRC curves avoid this value, and can thus reflect a less biased metric for the model’s performance." }, { "code": null, "e": 13121, "s": 12963, "text": "We can summarize this curve succinctly using an average precision value or average F1 score (averaged across each threshold), with an ideal value close to 1." }, { "code": null, "e": 13292, "s": 13121, "text": "from sklearn.metrics import f1_scorefrom sklearn.metrics import average_precision_scoref1 = f1_score(y_test, y_pred_prob)ap = average_precision_score(y_test, y_pred_prob)" }, { "code": null, "e": 13318, "s": 13292, "text": "Quick review of formulas:" }, { "code": null, "e": 13787, "s": 13318, "text": "In this post, we discussed how to move past accuracy as a measure of performance for a binary classifier. We discussed sensitivity, specificity, precision and recall. We looked at what happens when we change our decision threshold, and how we can visualize the trade-off between sensitivity and specificity, as well as between precision and recall. As a reminder, all the visualizations and model produced can be found on the interactive python notebook, linked below." }, { "code": null, "e": 13854, "s": 13787, "text": "https://github.com/ishaandey/Classification_Evaluation_Walkthrough" } ]
How to implement an instance method reference using a class name in Java?
Method reference is a simplified form of the lambda expression. It can specify a class name or instance name followed by the method name. The "::" symbol can separate a method name from the name of an object or class. An instance method reference refers to an instance method of any class. In the below example, we can implement an instance methods reference using the class name. <Class-Name>::<Instance-Method-Name> import java.util.*;; import java.util.function.*; public class ClassNameRefInstanceMethodTest { public static void main(String args[]) { List<Employee> empList = Arrays.asList( new Employee("Raja", 15000), new Employee("Adithya", 12000), new Employee("Jai", 9000), new Employee("Ravi", 19000), new Employee("Surya", 8500), new Employee("Chaitanya", 7500), new Employee("Vamsi", 14000) ); Function<Employee, String> getEmployeeNameFunction = new Function<Employee, String>() { @Override public String apply(Employee e) { return e.getName(); } }; System.out.println("The list of employees whose salary greater than 10000:"); empList.stream() .filter(e -> e.getSalary() > 10000) .map(Employee::getName) // instance method reference "getName" using class name "Employee" .forEach(e -> System.out.println(e)); } } // Employee class class Employee { private String name; private int salary; public Employee(String name, int salary){ this.name = name; this.salary = salary; } public String getName() { return name; } public int getSalary() { return salary; } } The list of employees whose salary greater than 10000: Raja Adithya Ravi Vamsi
[ { "code": null, "e": 1280, "s": 1062, "text": "Method reference is a simplified form of the lambda expression. It can specify a class name or instance name followed by the method name. The \"::\" symbol can separate a method name from the name of an object or class." }, { "code": null, "e": 1443, "s": 1280, "text": "An instance method reference refers to an instance method of any class. In the below example, we can implement an instance methods reference using the class name." }, { "code": null, "e": 1480, "s": 1443, "text": "<Class-Name>::<Instance-Method-Name>" }, { "code": null, "e": 2747, "s": 1480, "text": "import java.util.*;;\nimport java.util.function.*;\n\npublic class ClassNameRefInstanceMethodTest {\n public static void main(String args[]) {\n List<Employee> empList = Arrays.asList(\n new Employee(\"Raja\", 15000),\n new Employee(\"Adithya\", 12000),\n new Employee(\"Jai\", 9000),\n new Employee(\"Ravi\", 19000),\n new Employee(\"Surya\", 8500),\n new Employee(\"Chaitanya\", 7500),\n new Employee(\"Vamsi\", 14000)\n );\n Function<Employee, String> getEmployeeNameFunction = new Function<Employee, String>() {\n @Override\n public String apply(Employee e) {\n return e.getName();\n }\n };\n System.out.println(\"The list of employees whose salary greater than 10000:\");\n empList.stream()\n .filter(e -> e.getSalary() > 10000)\n .map(Employee::getName) // instance method reference \"getName\" using class name \"Employee\"\n .forEach(e -> System.out.println(e));\n }\n}\n\n// Employee class\nclass Employee {\n private String name;\n private int salary;\n public Employee(String name, int salary){\n this.name = name;\n this.salary = salary;\n }\n public String getName() {\n return name;\n }\n public int getSalary() {\n return salary;\n }\n}" }, { "code": null, "e": 2826, "s": 2747, "text": "The list of employees whose salary greater than 10000:\nRaja\nAdithya\nRavi\nVamsi" } ]
Evaluating Classifier Model Performance | by Andrew Hetherington | Towards Data Science
It’s 4am and you’re on your seventh coffee. You’ve trawled the forums to find the most sophisticated model you can. You’ve set up your preprocessing pipeline and you’ve picked your hyperparameters. Now, time to evaluate your model’s performance. You’re shaking with excitement (or it could be the caffeine overdose). This is it — your big debut onto the Kaggle world stage. As your predictions are being submitted, your thoughts turn to what you’re going to do with the prize money. A Lamborghini or a Ferrari? And in what colour? The red goes best with cream upholstery, but at the same time... The leader board pops up on your screen as if to announce something. Your model performance has gotten worse. You sit in silence for what seems like an age. Eventually, you sigh, close your laptop lid, and go to bed. If you’ve tried building a model before, you’ll know that it’s an iterative process. Progress isn’t linear — there can be long periods where it seems like you’re getting no closer to your objective, or even going backwards — until that breakthrough occurs and you surge forward... and right into the next problem. Monitoring model performance on a validation set is an excellent way to get feedback on whether what you’re doing is working. It’s also a great tool for comparing two different models — ultimately, our aim is to build better, more accurate models that will help us make better decisions in real world applications. When we’re trying to communicate the value of a model to a stakeholder in a particular situation, they’re going to want to know why they should care: what’s in it for them? How is it going to make their life easier? We need to be able to compare what we’ve built to the systems that are already in place. Evaluating model performance can tell us if our approach is working — this turns out to be helpful. We can continue to explore and see how far we can push our existing conceptualisation of the problem we’re working on. It can also tell us if our approach isn’t working — this turns out to be even more helpful because if our adjustments are making the model worse at what it’s supposed to be doing, then it indicates that we may have misunderstood our data or the situation being modelled. So evaluation of model performance is useful — but how exactly do you do it? For the moment, we are going to concentrate on a particular class of model — classifiers. These models are used to put unseen instances of data into a particular class — for example, we could set up a binary classifier (two classes) to distinguish whether a given image is of a dog or a cat. More practically, a binary classifier could be used to decide whether an incoming email should classified as spam, whether a particular financial transaction is fraudulent, or whether a promotional email should be sent to a particular customer of an online store based on their shopping history. The techniques and metrics used to assess the performance of a classifier will be different from those used for a regressor, which is a type of model that attempts to predict a value from a continuous range. Both types of model are common, but for now, let’s limit our analysis to classifiers. To illustrate some of the important concepts, we’ll set up a simple classifier that predicts whether an image of a particular image is a seven or not. Let’s use the famous NMIST dataset to train and test our model. (If you want to see the full Python code or follow along at home, check out the notebook used to produce this work on GitHub!) Below, we use Scikit-Learn to download our data and to build our classifier. First, import NumPy for maths and Matplotlib for plotting: # Import modules for maths and plottingimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.style as stylestyle.use(‘seaborn’) Then, use scikit-learn’s built-in helper function to download the data. The data comes as a dictionary — we can use the “data” key to access instances of training and test data (the images of the digits) and the “target” key to access the labels (what the digits have been hand-labelled as). # Fetch and load datafrom sklearn.datasets import fetch_openmlmnist = fetch_openml(“mnist_784”, version=1)mnist.keys()# dict_keys(['data', 'target', 'frame', 'categories', 'feature_names', 'target_names', 'DESCR', 'details', 'url']) The full dataset contains a whopping 70,000 images — let’s take a subset of 10% of the data to make it easier to quickly train and test our model. # Extract features and labelsdata, labels = mnist[“data”], mnist[“target”].astype(np.uint8)# Split into train and test datasetstrain_data, test_data, train_labels, test_labels = data[:6000], data[60000:61000], labels[:6000], labels[60000:61000] Now, let’s briefly inspect the first few digits in our training data. Each digit is actually represented by 784 values from 0 to 255, which represent how dark each pixel in a 28 by 28 grid should be. We can easily reshape the data into a grid and plot the data using matplotlib’s imshow() function: # Plot a selection of digits from the datasetexample_digits = train_data[9:18]# Set up plotting areafig = plt.figure(figsize=(6,6))# Set up subplots for each digit — we’ll plot each one side by side to illustrate the variationax1, ax2, ax3 = fig.add_subplot(331), fig.add_subplot(332), fig.add_subplot(333)ax4, ax5, ax6 = fig.add_subplot(334), fig.add_subplot(335), fig.add_subplot(336)ax7, ax8, ax9 = fig.add_subplot(337), fig.add_subplot(338), fig.add_subplot(339)axs = [ax1, ax2, ax3, ax4, ax5, ax6, ax7, ax8, ax9]# Plot the digitsfor i in range(9): ax = axs[i] ax.imshow(example_digits[i].reshape(28, 28), cmap=”binary”) ax.set_xticks([], []) ax.set_yticks([], []) Now, let’s create a new set of labels — we are only interested at the moment in whether an image of a seven or not. Once that’s done, we can train a model to hopefully pick up the characteristics that make a digit “seven-y”: # Create new labels based on whether a digit is a 7 or nottrain_labels_7 = (train_labels == 7) test_labels_7 = (test_labels == 7)# Import, instantiate and fit modelfrom sklearn.linear_model import SGDClassifiersgd_clf_7 = SGDClassifier(random_state=0) sgd_clf_7.fit(train_data, train_labels_7)# Make predictions using our model for the nine digits shown abovesgd_clf_7.predict(example_digits)# array([False, False, False, False, False, False, True, False, False]) For our model, we’ve used an SGD (or Stochastic Gradient Descent) classifier. And for our array of nine example digits, it looks like our model is doing the right kind of thing — it has correctly identified the one seven from the eight other not-sevens. Let’s make predictions on our data using 3-fold cross-validation: from sklearn.model_selection import cross_val_predict# Use 3-fold cross-validation to make “clean” predictions on our training datatrain_data_predictions = cross_val_predict(sgd_clf_7, train_data, train_labels_7, cv=3)train_data_predictions# array([False, False, False, ..., False, False, False]) Ok — now we have a set of predictions for each instance in our training set. It may sound strange that we are making predictions on our training data, but we avoid making predictions on data the model has already been trained on by using cross-validation — follow the link to learn more. At this point, let’s take a step back and think about the different situations we might find ourselves in for a given model prediction. The model may predict a 7, and the image is actually a 7 (true positive); The model may predict a 7, and the image is actually not a 7 (false positive); The model may predict a not-7, and the image is actually a 7 (false negative); and The model may predict a not-7, and the image is actually not a 7 (true negative). We use the terms true/false positive (TP/FP) and true/false negative (TN/FN) to describe each of the four possible outcomes listed above. The true/false part refers to whether the model was correct or not. The positive/negative part refers to whether the instance being classified actually was or was not the instance we wanted to identify. A good model will have a high level of true positive and true negatives, because these results indicate where the model has got the right answer. A good model will also have a low level of false positives and false negatives, which indicate where the model has made mistakes. These four numbers can tell us a lot about how the model is doing and what we can do to help. Often, it’s helpful to represent them as a confusion matrix. We can use sklearn to easily extract the confusion matrix: from sklearn.metrics import confusion_matrix# Show confusion matrix for our SGD classifier’s predictionsconfusion_matrix(train_labels_7, train_data_predictions)# array([[5232, 117], [ 72, 579]], dtype=int64) The columns of this matrix represent what our model has predicted — not-7 on the left and 7 on the right. The rows represent what each instance that the model predicted actually was — not-7 on the top and 7 on the bottom. The number in each position tells us the number of each situation that was observed when comparing our predictions to the actual results. So in summary, out of 6,000 test cases, we observed (considering a “positive” result as being a 7 and a “negative” one being some other digit): 579 predicted 7s that were actually 7s (TPs); 72 predicted not-7s that were actually 7s (FNs); 117 predicted 7s that were actually not-7s (FPs); and 5,232 predicted not-7s that were actually not-7s (TNs). You may have noticed that ideally our confusion matrix would be diagonal — that is, only consisting of true positives and true negatives. The fact that our classifier seems to be struggling more with false positives than false negatives gives us useful information when deciding how we should proceed to improve our model further. We can use the information encoded in the confusion matrix to calculate some further useful quantities. Precision is defined as the number of true positives as a proportion of all (true and false) positives. Effectively, this number represents how many of the model’s positive predictions actually turned out to be right. For our model above, the precision is 579 / (579 + 117) = 83.2%. This means that out of all the digits we predicted to be 7s in our dataset, only 83.2% were actually 7s. However, precision must also be considered in tandem with recall. Recall is defined as the number of true positives as a proportion of both true positives and false negatives. Remember that both true positives and false negatives relate to cases where the digit being considered actually was a 7. So in summary, recall represents how good the model is at correctly identifying positive instances. For our model above, the recall is 579 / (579 + 72) = 88.9%. In other words, our model only caught 88.9% of the digits that were actually 7s. We can also save ourselves from having to calculate these quantities manually by getting them directly from our model: from sklearn.metrics import precision_score, recall_score# Calculate and print precision and recall as percentagesprint(“Precision: “ + str(round(precision_score(train_labels_7, train_data_predictions)*100,1))+”%”)print(“Recall: “ + str(round(recall_score(train_labels_7, train_data_predictions)*100,1))+”%”)# Precision: 83.2%# Recall: 88.9% We can set a desired level of precision or recall by playing about with the threshold of the model. In the background, our SGD classifier has come up with a decision score for each digit in the data which corresponds to how “seven-y” a digit is. Digits that appear to be very seven-y will have a higher score. Digits that the model doesn’t think look like sevens at all will have a low score. Ambiguous cases (perhaps poorly drawn sevens that look a bit like ones) will be somewhere in the middle. All digits with a decision score above the model’s threshold will be predicted to be 7s, and all those with scores below the threshold will be predicted as not-7s. Hence, if we want to increase our recall (and increase the number of 7s that we successfully identify) we can lower the threshold. By doing this, we are effectively saying to the model, “Lower your standards for identifying sevens a bit”. We will then catch more of the ambiguous sevens, the proportion of the actual 7s in the data that we correctly identify will increase, and our recall will go up. In addition to increasing the number of TPs, we will also lower the number of FNs — 7s that were previously mistakenly identified as not-7s will start to be correctly identified. You may have noticed, however, that in reducing the threshold, we are likely to now misclassify more not-7s. That one which was drawn to look a bit like a seven may now be predicted incorrectly to be a 7. Hence, we will start to get an increasing number of false positive results and our precision will trend downwards as our recall increases. This is the precision–recall trade-off. You can’t have your cake and eat it too. The best models will be able to strike a good balance between the two so that both precision and recall are at an acceptable level. What level of precision and recall constitutes “acceptable”? That depends on how the model is going to be applied. If the consequences of failing to identify a positive instance are severe, for example, if you were a doctor aiming to detect the presence a life-threatening disease, you may be willing to suffer a few more false positives (and send some people who don’t have the disease for some unnecessary further tests) to reduce false negatives (a circumstance under which someone would not receive the life-saving treatment they need). Similarly, if you had a situation in which it was necessary to be very confident in your positive predictions, for example, if you were choosing a property to purchase or picking a location for a new oil well, you may be happy to pass up a few opportunities (ie have your model predict a few more false negatives) if it means that you are less likely to invest time and money as a result of a false positive. We can observe how precision and recall vary with the decision threshold (for the calculation of our metrics above, scikit-learn has used a threshold of zero): # Use cross_val_predict to get our model’s decision scores for each digit it has predictedtrain_data_decision_scores = cross_val_predict(sgd_clf_7, train_data, train_labels_7, cv=3, method=”decision_function”)from sklearn.metrics import precision_recall_curve# Obtain possible combinations of precisions, recalls, and thresholdsprecisions, recalls, thresholds = precision_recall_curve(train_labels_7, train_data_decision_scores)# Set up plotting areafig, ax = plt.subplots(figsize=(12,9))# Plot decision and recall curvesax.plot(thresholds, precisions[:-1], label=”Precision”)ax.plot(thresholds, recalls[:-1], label=”Recall”)[...] # Plot formatting As you can see, precision and recall are two sides of the same coin. Generally (that is, in the absence of a specific reason to seek out more of one at the possible expense of the other) we will want to tune our model so that our decision threshold is set in the region where both precision and recall are high. We can also plot precision and recall directly against each other as the decision threshold is varied: # Set up plotting areafig, ax = plt.subplots(figsize=(12,9))# Plot pairs of precision and recall for differing thresholdsax.plot(recalls, precisions, linewidth=2)[...] # Plot formatting We’ve also included the point along the curve where our current model (with a decision threshold of zero) lies. In an ideal world, we would have a model that could achieve both 100% precision and 100% recall — that is, we would want a precision–recall curve that passes through the top right-hand corner of our plot above. Hence, any adjustments that we make to our model that push our curve outwards and towards the upper right can be regarded as improvements. For applications where precision and recall are of similar importance, it is often convenient to combine them into a single quantity called the F1 score. The F1 score is defined as being the harmonic mean of the precision and recall scores. It’s a bit harder to intuitively interpret the F1 score than it is for precision and recall individually, but it may be desirable to summarise the two quantities into one, easy-to-compare metric. To obtain a high F1 score, a model needs to have both high precision and recall. This is because the F1 score is dragged down quite significantly when taking the harmonic mean if one of precision or recall is low. from sklearn.metrics import f1_score# Obtain and print F1 score as a percentageprint(“F1 score: “ + str(round(f1_score(train_labels_7, train_data_predictions)*100,1))+”%”)# F1 score: 86.0% Another common way of assessing (and visualising) model performance is by using the ROC curve. Historically, it has its origins in signal detection theory and was first used in the context of detecting enemy aircraft in World War II, where the ability of a radar receiver operator to detect and make decisions based on incoming signals was referred to as Receiver Operating Characteristic. Although the precise context in which it is generally used today has changed, the name has stuck. The ROC curve plots how the True Positive rate and the False Positive rate change as the model threshold is varied. The true positive rate is simply the percentage of positive instances that were correctly identified (ie the number of 7s we correctly predicted). The false positive rate is, correspondingly, the number of negative instances that were incorrectly identified as being positive (ie the number of not-7s that were incorrectly predicted to be 7s). You may have noticed that the definition for the true positive rate is equivalent to that of recall. And you’d be correct — these are simply different names for the same metric. To get a bit of an intuition about what a good and a bad ROC curve would look like (as it’s often a bit tricky to think about what these more abstract quantities actually mean), let’s consider the extreme cases — the best and worst possible classifiers we could possibly have. The worst possible classifier will essentially make a random, 50/50 guess as to whether a given digit is a 7 or not a 7 — it has made no attempt to learn what distinguishes the two classes. The decision scores for each instance will essentially be randomly distributed. Say we initially set the decision threshold at a very high value so that all instances are classified as negative. We will have identified no positive instances — true or false — so both the true positive and false positive rates are zero. As we decrease the decision threshold, we will gradually start classifying equal numbers of positive and negative instances as being positive, so that the true and false positive rates increase at the same pace. This continues until our threshold is at some very low value where we have the reverse of the situation we started with — correctly classifying all positive instances (so true positive rate is equal to one) but also incorrectly classifying all negative instances (false positive rate also one). Hence, the ROC curve for a random, 50/50 classifier is a diagonal line from (0,0) to (1,1). (You may think it’s possible to have an even worse classifier than this — perhaps a classifier that gets every digit wrong by predicting the opposite every time. But in that case, then the classifier would essentially be a perfect classifier — to be so wrong, the model would have needed to learn the classification perfectly and then just switch around the outputs before making a prediction!) The best possible classifier will be able to correctly predict every given instance as positive or negative with 100% accuracy. The decision scores for all positive instances will be some high value, to represent the fact that the model is supremely confident in its predictions, and equally so for every digit it has been given. All negative instances will have some low decision score, since the model is, again, supremely and equally confident that all these instances are negative. If we start the decision threshold at a very high value so that all instances are classified as negative, we have the same situation as described for the 50/50 classifier — both true and false positive rates are zero because we have not predicted any positive instances. In the same way, when the decision threshold is very low, we will predict all instances to be positive and so will have a value of one for both true and false positive rates. Hence, the ROC curve will start at (0,0) and end at (1,1), as for the 50/50 classifier. However, when the decision threshold is set at any level between the high and low decision scores that identify positive and negative instances, the classifier will operate perfectly with a 100% true positive rate and a 0% false positive rate. Amazing! The consequences of the above is that the ROC curve for our perfect classifier is the curve that joins up (0,0), (0,1) and (1,1) — a curve that hugs the upper left-hand corner of the plot. Most real-world classifiers will be somewhere between these two extremes. Ideally, we will want our classifier’s ROC curve to be closer to looking like a perfect classifier than one that guesses randomly — so a ROC curve that lies closer to the upper left-hand corner of the plot (closer to the behaviour of a perfect classifier) represents a superior model. Armed with this new knowledge, let’s plot some ROC curves. from sklearn.metrics import roc_curve# Set up plotting areafig, ax = plt.subplots(figsize=(9,9))# Obtain possible combinations of true/false positive rates and thresholdsfpr, tpr, thresholds = roc_curve(train_labels_7, train_data_decision_scores)# Plot random guess, 50/50 classifierax.plot([0,1], [0,1], “k — “, alpha=0.5, label=”Randomly guessing”)# Plot perfect, omniscient classifierax.plot([0.002,0.002], [0,0.998], “slateblue”, label=”Perfect classifier”)ax.plot([0.001,1], [0.998,0.998], “slateblue”)# Plot our SGD classifier with threshold of zeroax.plot(fpr, tpr, label=”Our SGD classifier”)[...] # Plot formatting It’s clear that our SGD classifier is doing better than one that guesses randomly! All that work was worth it after all. Instead of relying on the vague statement that “closer to the upper left corner is better”, we can quantify model performance by calculating the Area Under a model’s ROC Curve — referred to as the AUC. If you remember your formulae for calculating the area of a triangle, you should be able to see that the AUC for the random classifier is 0.5. You should also be able to see that the AUC for the perfect classifier is 1. Hence, a higher AUC is better and we will want to aim for an AUC as close to 1 as possible. Our SGD classifier’s AUC can be obtained as follows: from sklearn.metrics import roc_auc_score# Obtain and print AUCprint(“Area Under Curve (AUC): “ + str(round(roc_auc_score(train_labels_7, train_data_predictions),3)))# Area Under Curve (AUC): 0.934 In isolation, it’s hard to tell exactly what our AUC of 0.934 means. As with the metrics was saw earlier based on precision and recall, these are standard comparative tools. We should use them purposefully to develop and tune our current model, and to compare our model to other algorithms to seek out the best possible performance at our particular task. We covered a lot of ground today, so congratulations if you made it all the way through! When first taking on a problem, it’s easy to become overwhelmed by the sheer range of algorithms, methods and parameters that could be used as part of an approach to solving it. Model performance metrics can act as the compass that guides us through this wilderness — as long as we break a problem down, decide on an initial approach (we can change later if needed), and use sensible tools like those explained above to evaluate whether we are making progress, we will be moving towards where we need to go. And as heart-breaking as it is to not see hours of research and tinkering with a model reflected in an improvement in a particular performance metric, it’s always better to know whether we are moving forwards or backwards. So get stuck in — and don’t get too invested in a particular method if the numbers show that it’s not working out. Review and compare models and approaches dispassionately. If you can manage that, you’ll be sitting in that Ferrari with the cream upholstery in no time at all. Andrew Hetherington is an actuary-in-training and data enthusiast based in London, UK. Check out my website. Connect with me on LinkedIn. See what I’m tinkering with on GitHub. The notebook used to produce the work in this article can be found here. Code chunks in this work have been adapted from A. Géron’s 2019 book, Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow, 2nd Edition, by Aurélien Géron (O’Reilly). Copyright 2019 Kiwisoft S.A.S., 978–1–492–03264–9. Photos by AbsolutVision, Markus Spiske and Marat Gilyadzinov.
[ { "code": null, "e": 417, "s": 171, "text": "It’s 4am and you’re on your seventh coffee. You’ve trawled the forums to find the most sophisticated model you can. You’ve set up your preprocessing pipeline and you’ve picked your hyperparameters. Now, time to evaluate your model’s performance." }, { "code": null, "e": 767, "s": 417, "text": "You’re shaking with excitement (or it could be the caffeine overdose). This is it — your big debut onto the Kaggle world stage. As your predictions are being submitted, your thoughts turn to what you’re going to do with the prize money. A Lamborghini or a Ferrari? And in what colour? The red goes best with cream upholstery, but at the same time..." }, { "code": null, "e": 836, "s": 767, "text": "The leader board pops up on your screen as if to announce something." }, { "code": null, "e": 924, "s": 836, "text": "Your model performance has gotten worse. You sit in silence for what seems like an age." }, { "code": null, "e": 984, "s": 924, "text": "Eventually, you sigh, close your laptop lid, and go to bed." }, { "code": null, "e": 1298, "s": 984, "text": "If you’ve tried building a model before, you’ll know that it’s an iterative process. Progress isn’t linear — there can be long periods where it seems like you’re getting no closer to your objective, or even going backwards — until that breakthrough occurs and you surge forward... and right into the next problem." }, { "code": null, "e": 1918, "s": 1298, "text": "Monitoring model performance on a validation set is an excellent way to get feedback on whether what you’re doing is working. It’s also a great tool for comparing two different models — ultimately, our aim is to build better, more accurate models that will help us make better decisions in real world applications. When we’re trying to communicate the value of a model to a stakeholder in a particular situation, they’re going to want to know why they should care: what’s in it for them? How is it going to make their life easier? We need to be able to compare what we’ve built to the systems that are already in place." }, { "code": null, "e": 2408, "s": 1918, "text": "Evaluating model performance can tell us if our approach is working — this turns out to be helpful. We can continue to explore and see how far we can push our existing conceptualisation of the problem we’re working on. It can also tell us if our approach isn’t working — this turns out to be even more helpful because if our adjustments are making the model worse at what it’s supposed to be doing, then it indicates that we may have misunderstood our data or the situation being modelled." }, { "code": null, "e": 2485, "s": 2408, "text": "So evaluation of model performance is useful — but how exactly do you do it?" }, { "code": null, "e": 3073, "s": 2485, "text": "For the moment, we are going to concentrate on a particular class of model — classifiers. These models are used to put unseen instances of data into a particular class — for example, we could set up a binary classifier (two classes) to distinguish whether a given image is of a dog or a cat. More practically, a binary classifier could be used to decide whether an incoming email should classified as spam, whether a particular financial transaction is fraudulent, or whether a promotional email should be sent to a particular customer of an online store based on their shopping history." }, { "code": null, "e": 3367, "s": 3073, "text": "The techniques and metrics used to assess the performance of a classifier will be different from those used for a regressor, which is a type of model that attempts to predict a value from a continuous range. Both types of model are common, but for now, let’s limit our analysis to classifiers." }, { "code": null, "e": 3582, "s": 3367, "text": "To illustrate some of the important concepts, we’ll set up a simple classifier that predicts whether an image of a particular image is a seven or not. Let’s use the famous NMIST dataset to train and test our model." }, { "code": null, "e": 3709, "s": 3582, "text": "(If you want to see the full Python code or follow along at home, check out the notebook used to produce this work on GitHub!)" }, { "code": null, "e": 3845, "s": 3709, "text": "Below, we use Scikit-Learn to download our data and to build our classifier. First, import NumPy for maths and Matplotlib for plotting:" }, { "code": null, "e": 3986, "s": 3845, "text": "# Import modules for maths and plottingimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.style as stylestyle.use(‘seaborn’)" }, { "code": null, "e": 4278, "s": 3986, "text": "Then, use scikit-learn’s built-in helper function to download the data. The data comes as a dictionary — we can use the “data” key to access instances of training and test data (the images of the digits) and the “target” key to access the labels (what the digits have been hand-labelled as)." }, { "code": null, "e": 4511, "s": 4278, "text": "# Fetch and load datafrom sklearn.datasets import fetch_openmlmnist = fetch_openml(“mnist_784”, version=1)mnist.keys()# dict_keys(['data', 'target', 'frame', 'categories', 'feature_names', 'target_names', 'DESCR', 'details', 'url'])" }, { "code": null, "e": 4658, "s": 4511, "text": "The full dataset contains a whopping 70,000 images — let’s take a subset of 10% of the data to make it easier to quickly train and test our model." }, { "code": null, "e": 4903, "s": 4658, "text": "# Extract features and labelsdata, labels = mnist[“data”], mnist[“target”].astype(np.uint8)# Split into train and test datasetstrain_data, test_data, train_labels, test_labels = data[:6000], data[60000:61000], labels[:6000], labels[60000:61000]" }, { "code": null, "e": 5202, "s": 4903, "text": "Now, let’s briefly inspect the first few digits in our training data. Each digit is actually represented by 784 values from 0 to 255, which represent how dark each pixel in a 28 by 28 grid should be. We can easily reshape the data into a grid and plot the data using matplotlib’s imshow() function:" }, { "code": null, "e": 5873, "s": 5202, "text": "# Plot a selection of digits from the datasetexample_digits = train_data[9:18]# Set up plotting areafig = plt.figure(figsize=(6,6))# Set up subplots for each digit — we’ll plot each one side by side to illustrate the variationax1, ax2, ax3 = fig.add_subplot(331), fig.add_subplot(332), fig.add_subplot(333)ax4, ax5, ax6 = fig.add_subplot(334), fig.add_subplot(335), fig.add_subplot(336)ax7, ax8, ax9 = fig.add_subplot(337), fig.add_subplot(338), fig.add_subplot(339)axs = [ax1, ax2, ax3, ax4, ax5, ax6, ax7, ax8, ax9]# Plot the digitsfor i in range(9): ax = axs[i] ax.imshow(example_digits[i].reshape(28, 28), cmap=”binary”) ax.set_xticks([], []) ax.set_yticks([], [])" }, { "code": null, "e": 6098, "s": 5873, "text": "Now, let’s create a new set of labels — we are only interested at the moment in whether an image of a seven or not. Once that’s done, we can train a model to hopefully pick up the characteristics that make a digit “seven-y”:" }, { "code": null, "e": 6563, "s": 6098, "text": "# Create new labels based on whether a digit is a 7 or nottrain_labels_7 = (train_labels == 7) test_labels_7 = (test_labels == 7)# Import, instantiate and fit modelfrom sklearn.linear_model import SGDClassifiersgd_clf_7 = SGDClassifier(random_state=0) sgd_clf_7.fit(train_data, train_labels_7)# Make predictions using our model for the nine digits shown abovesgd_clf_7.predict(example_digits)# array([False, False, False, False, False, False, True, False, False])" }, { "code": null, "e": 6883, "s": 6563, "text": "For our model, we’ve used an SGD (or Stochastic Gradient Descent) classifier. And for our array of nine example digits, it looks like our model is doing the right kind of thing — it has correctly identified the one seven from the eight other not-sevens. Let’s make predictions on our data using 3-fold cross-validation:" }, { "code": null, "e": 7180, "s": 6883, "text": "from sklearn.model_selection import cross_val_predict# Use 3-fold cross-validation to make “clean” predictions on our training datatrain_data_predictions = cross_val_predict(sgd_clf_7, train_data, train_labels_7, cv=3)train_data_predictions# array([False, False, False, ..., False, False, False])" }, { "code": null, "e": 7468, "s": 7180, "text": "Ok — now we have a set of predictions for each instance in our training set. It may sound strange that we are making predictions on our training data, but we avoid making predictions on data the model has already been trained on by using cross-validation — follow the link to learn more." }, { "code": null, "e": 7604, "s": 7468, "text": "At this point, let’s take a step back and think about the different situations we might find ourselves in for a given model prediction." }, { "code": null, "e": 7678, "s": 7604, "text": "The model may predict a 7, and the image is actually a 7 (true positive);" }, { "code": null, "e": 7757, "s": 7678, "text": "The model may predict a 7, and the image is actually not a 7 (false positive);" }, { "code": null, "e": 7840, "s": 7757, "text": "The model may predict a not-7, and the image is actually a 7 (false negative); and" }, { "code": null, "e": 7922, "s": 7840, "text": "The model may predict a not-7, and the image is actually not a 7 (true negative)." }, { "code": null, "e": 8263, "s": 7922, "text": "We use the terms true/false positive (TP/FP) and true/false negative (TN/FN) to describe each of the four possible outcomes listed above. The true/false part refers to whether the model was correct or not. The positive/negative part refers to whether the instance being classified actually was or was not the instance we wanted to identify." }, { "code": null, "e": 8539, "s": 8263, "text": "A good model will have a high level of true positive and true negatives, because these results indicate where the model has got the right answer. A good model will also have a low level of false positives and false negatives, which indicate where the model has made mistakes." }, { "code": null, "e": 8694, "s": 8539, "text": "These four numbers can tell us a lot about how the model is doing and what we can do to help. Often, it’s helpful to represent them as a confusion matrix." }, { "code": null, "e": 8753, "s": 8694, "text": "We can use sklearn to easily extract the confusion matrix:" }, { "code": null, "e": 8972, "s": 8753, "text": "from sklearn.metrics import confusion_matrix# Show confusion matrix for our SGD classifier’s predictionsconfusion_matrix(train_labels_7, train_data_predictions)# array([[5232, 117], [ 72, 579]], dtype=int64)" }, { "code": null, "e": 9332, "s": 8972, "text": "The columns of this matrix represent what our model has predicted — not-7 on the left and 7 on the right. The rows represent what each instance that the model predicted actually was — not-7 on the top and 7 on the bottom. The number in each position tells us the number of each situation that was observed when comparing our predictions to the actual results." }, { "code": null, "e": 9476, "s": 9332, "text": "So in summary, out of 6,000 test cases, we observed (considering a “positive” result as being a 7 and a “negative” one being some other digit):" }, { "code": null, "e": 9522, "s": 9476, "text": "579 predicted 7s that were actually 7s (TPs);" }, { "code": null, "e": 9571, "s": 9522, "text": "72 predicted not-7s that were actually 7s (FNs);" }, { "code": null, "e": 9625, "s": 9571, "text": "117 predicted 7s that were actually not-7s (FPs); and" }, { "code": null, "e": 9681, "s": 9625, "text": "5,232 predicted not-7s that were actually not-7s (TNs)." }, { "code": null, "e": 10012, "s": 9681, "text": "You may have noticed that ideally our confusion matrix would be diagonal — that is, only consisting of true positives and true negatives. The fact that our classifier seems to be struggling more with false positives than false negatives gives us useful information when deciding how we should proceed to improve our model further." }, { "code": null, "e": 10334, "s": 10012, "text": "We can use the information encoded in the confusion matrix to calculate some further useful quantities. Precision is defined as the number of true positives as a proportion of all (true and false) positives. Effectively, this number represents how many of the model’s positive predictions actually turned out to be right." }, { "code": null, "e": 10504, "s": 10334, "text": "For our model above, the precision is 579 / (579 + 117) = 83.2%. This means that out of all the digits we predicted to be 7s in our dataset, only 83.2% were actually 7s." }, { "code": null, "e": 10901, "s": 10504, "text": "However, precision must also be considered in tandem with recall. Recall is defined as the number of true positives as a proportion of both true positives and false negatives. Remember that both true positives and false negatives relate to cases where the digit being considered actually was a 7. So in summary, recall represents how good the model is at correctly identifying positive instances." }, { "code": null, "e": 11043, "s": 10901, "text": "For our model above, the recall is 579 / (579 + 72) = 88.9%. In other words, our model only caught 88.9% of the digits that were actually 7s." }, { "code": null, "e": 11162, "s": 11043, "text": "We can also save ourselves from having to calculate these quantities manually by getting them directly from our model:" }, { "code": null, "e": 11504, "s": 11162, "text": "from sklearn.metrics import precision_score, recall_score# Calculate and print precision and recall as percentagesprint(“Precision: “ + str(round(precision_score(train_labels_7, train_data_predictions)*100,1))+”%”)print(“Recall: “ + str(round(recall_score(train_labels_7, train_data_predictions)*100,1))+”%”)# Precision: 83.2%# Recall: 88.9%" }, { "code": null, "e": 12746, "s": 11504, "text": "We can set a desired level of precision or recall by playing about with the threshold of the model. In the background, our SGD classifier has come up with a decision score for each digit in the data which corresponds to how “seven-y” a digit is. Digits that appear to be very seven-y will have a higher score. Digits that the model doesn’t think look like sevens at all will have a low score. Ambiguous cases (perhaps poorly drawn sevens that look a bit like ones) will be somewhere in the middle. All digits with a decision score above the model’s threshold will be predicted to be 7s, and all those with scores below the threshold will be predicted as not-7s. Hence, if we want to increase our recall (and increase the number of 7s that we successfully identify) we can lower the threshold. By doing this, we are effectively saying to the model, “Lower your standards for identifying sevens a bit”. We will then catch more of the ambiguous sevens, the proportion of the actual 7s in the data that we correctly identify will increase, and our recall will go up. In addition to increasing the number of TPs, we will also lower the number of FNs — 7s that were previously mistakenly identified as not-7s will start to be correctly identified." }, { "code": null, "e": 13303, "s": 12746, "text": "You may have noticed, however, that in reducing the threshold, we are likely to now misclassify more not-7s. That one which was drawn to look a bit like a seven may now be predicted incorrectly to be a 7. Hence, we will start to get an increasing number of false positive results and our precision will trend downwards as our recall increases. This is the precision–recall trade-off. You can’t have your cake and eat it too. The best models will be able to strike a good balance between the two so that both precision and recall are at an acceptable level." }, { "code": null, "e": 14253, "s": 13303, "text": "What level of precision and recall constitutes “acceptable”? That depends on how the model is going to be applied. If the consequences of failing to identify a positive instance are severe, for example, if you were a doctor aiming to detect the presence a life-threatening disease, you may be willing to suffer a few more false positives (and send some people who don’t have the disease for some unnecessary further tests) to reduce false negatives (a circumstance under which someone would not receive the life-saving treatment they need). Similarly, if you had a situation in which it was necessary to be very confident in your positive predictions, for example, if you were choosing a property to purchase or picking a location for a new oil well, you may be happy to pass up a few opportunities (ie have your model predict a few more false negatives) if it means that you are less likely to invest time and money as a result of a false positive." }, { "code": null, "e": 14413, "s": 14253, "text": "We can observe how precision and recall vary with the decision threshold (for the calculation of our metrics above, scikit-learn has used a threshold of zero):" }, { "code": null, "e": 15062, "s": 14413, "text": "# Use cross_val_predict to get our model’s decision scores for each digit it has predictedtrain_data_decision_scores = cross_val_predict(sgd_clf_7, train_data, train_labels_7, cv=3, method=”decision_function”)from sklearn.metrics import precision_recall_curve# Obtain possible combinations of precisions, recalls, and thresholdsprecisions, recalls, thresholds = precision_recall_curve(train_labels_7, train_data_decision_scores)# Set up plotting areafig, ax = plt.subplots(figsize=(12,9))# Plot decision and recall curvesax.plot(thresholds, precisions[:-1], label=”Precision”)ax.plot(thresholds, recalls[:-1], label=”Recall”)[...] # Plot formatting" }, { "code": null, "e": 15374, "s": 15062, "text": "As you can see, precision and recall are two sides of the same coin. Generally (that is, in the absence of a specific reason to seek out more of one at the possible expense of the other) we will want to tune our model so that our decision threshold is set in the region where both precision and recall are high." }, { "code": null, "e": 15477, "s": 15374, "text": "We can also plot precision and recall directly against each other as the decision threshold is varied:" }, { "code": null, "e": 15663, "s": 15477, "text": "# Set up plotting areafig, ax = plt.subplots(figsize=(12,9))# Plot pairs of precision and recall for differing thresholdsax.plot(recalls, precisions, linewidth=2)[...] # Plot formatting" }, { "code": null, "e": 16125, "s": 15663, "text": "We’ve also included the point along the curve where our current model (with a decision threshold of zero) lies. In an ideal world, we would have a model that could achieve both 100% precision and 100% recall — that is, we would want a precision–recall curve that passes through the top right-hand corner of our plot above. Hence, any adjustments that we make to our model that push our curve outwards and towards the upper right can be regarded as improvements." }, { "code": null, "e": 16562, "s": 16125, "text": "For applications where precision and recall are of similar importance, it is often convenient to combine them into a single quantity called the F1 score. The F1 score is defined as being the harmonic mean of the precision and recall scores. It’s a bit harder to intuitively interpret the F1 score than it is for precision and recall individually, but it may be desirable to summarise the two quantities into one, easy-to-compare metric." }, { "code": null, "e": 16776, "s": 16562, "text": "To obtain a high F1 score, a model needs to have both high precision and recall. This is because the F1 score is dragged down quite significantly when taking the harmonic mean if one of precision or recall is low." }, { "code": null, "e": 16965, "s": 16776, "text": "from sklearn.metrics import f1_score# Obtain and print F1 score as a percentageprint(“F1 score: “ + str(round(f1_score(train_labels_7, train_data_predictions)*100,1))+”%”)# F1 score: 86.0%" }, { "code": null, "e": 17453, "s": 16965, "text": "Another common way of assessing (and visualising) model performance is by using the ROC curve. Historically, it has its origins in signal detection theory and was first used in the context of detecting enemy aircraft in World War II, where the ability of a radar receiver operator to detect and make decisions based on incoming signals was referred to as Receiver Operating Characteristic. Although the precise context in which it is generally used today has changed, the name has stuck." }, { "code": null, "e": 18091, "s": 17453, "text": "The ROC curve plots how the True Positive rate and the False Positive rate change as the model threshold is varied. The true positive rate is simply the percentage of positive instances that were correctly identified (ie the number of 7s we correctly predicted). The false positive rate is, correspondingly, the number of negative instances that were incorrectly identified as being positive (ie the number of not-7s that were incorrectly predicted to be 7s). You may have noticed that the definition for the true positive rate is equivalent to that of recall. And you’d be correct — these are simply different names for the same metric." }, { "code": null, "e": 18368, "s": 18091, "text": "To get a bit of an intuition about what a good and a bad ROC curve would look like (as it’s often a bit tricky to think about what these more abstract quantities actually mean), let’s consider the extreme cases — the best and worst possible classifiers we could possibly have." }, { "code": null, "e": 19477, "s": 18368, "text": "The worst possible classifier will essentially make a random, 50/50 guess as to whether a given digit is a 7 or not a 7 — it has made no attempt to learn what distinguishes the two classes. The decision scores for each instance will essentially be randomly distributed. Say we initially set the decision threshold at a very high value so that all instances are classified as negative. We will have identified no positive instances — true or false — so both the true positive and false positive rates are zero. As we decrease the decision threshold, we will gradually start classifying equal numbers of positive and negative instances as being positive, so that the true and false positive rates increase at the same pace. This continues until our threshold is at some very low value where we have the reverse of the situation we started with — correctly classifying all positive instances (so true positive rate is equal to one) but also incorrectly classifying all negative instances (false positive rate also one). Hence, the ROC curve for a random, 50/50 classifier is a diagonal line from (0,0) to (1,1)." }, { "code": null, "e": 19872, "s": 19477, "text": "(You may think it’s possible to have an even worse classifier than this — perhaps a classifier that gets every digit wrong by predicting the opposite every time. But in that case, then the classifier would essentially be a perfect classifier — to be so wrong, the model would have needed to learn the classification perfectly and then just switch around the outputs before making a prediction!)" }, { "code": null, "e": 21334, "s": 19872, "text": "The best possible classifier will be able to correctly predict every given instance as positive or negative with 100% accuracy. The decision scores for all positive instances will be some high value, to represent the fact that the model is supremely confident in its predictions, and equally so for every digit it has been given. All negative instances will have some low decision score, since the model is, again, supremely and equally confident that all these instances are negative. If we start the decision threshold at a very high value so that all instances are classified as negative, we have the same situation as described for the 50/50 classifier — both true and false positive rates are zero because we have not predicted any positive instances. In the same way, when the decision threshold is very low, we will predict all instances to be positive and so will have a value of one for both true and false positive rates. Hence, the ROC curve will start at (0,0) and end at (1,1), as for the 50/50 classifier. However, when the decision threshold is set at any level between the high and low decision scores that identify positive and negative instances, the classifier will operate perfectly with a 100% true positive rate and a 0% false positive rate. Amazing! The consequences of the above is that the ROC curve for our perfect classifier is the curve that joins up (0,0), (0,1) and (1,1) — a curve that hugs the upper left-hand corner of the plot." }, { "code": null, "e": 21693, "s": 21334, "text": "Most real-world classifiers will be somewhere between these two extremes. Ideally, we will want our classifier’s ROC curve to be closer to looking like a perfect classifier than one that guesses randomly — so a ROC curve that lies closer to the upper left-hand corner of the plot (closer to the behaviour of a perfect classifier) represents a superior model." }, { "code": null, "e": 21752, "s": 21693, "text": "Armed with this new knowledge, let’s plot some ROC curves." }, { "code": null, "e": 22376, "s": 21752, "text": "from sklearn.metrics import roc_curve# Set up plotting areafig, ax = plt.subplots(figsize=(9,9))# Obtain possible combinations of true/false positive rates and thresholdsfpr, tpr, thresholds = roc_curve(train_labels_7, train_data_decision_scores)# Plot random guess, 50/50 classifierax.plot([0,1], [0,1], “k — “, alpha=0.5, label=”Randomly guessing”)# Plot perfect, omniscient classifierax.plot([0.002,0.002], [0,0.998], “slateblue”, label=”Perfect classifier”)ax.plot([0.001,1], [0.998,0.998], “slateblue”)# Plot our SGD classifier with threshold of zeroax.plot(fpr, tpr, label=”Our SGD classifier”)[...] # Plot formatting" }, { "code": null, "e": 22699, "s": 22376, "text": "It’s clear that our SGD classifier is doing better than one that guesses randomly! All that work was worth it after all. Instead of relying on the vague statement that “closer to the upper left corner is better”, we can quantify model performance by calculating the Area Under a model’s ROC Curve — referred to as the AUC." }, { "code": null, "e": 23064, "s": 22699, "text": "If you remember your formulae for calculating the area of a triangle, you should be able to see that the AUC for the random classifier is 0.5. You should also be able to see that the AUC for the perfect classifier is 1. Hence, a higher AUC is better and we will want to aim for an AUC as close to 1 as possible. Our SGD classifier’s AUC can be obtained as follows:" }, { "code": null, "e": 23262, "s": 23064, "text": "from sklearn.metrics import roc_auc_score# Obtain and print AUCprint(“Area Under Curve (AUC): “ + str(round(roc_auc_score(train_labels_7, train_data_predictions),3)))# Area Under Curve (AUC): 0.934" }, { "code": null, "e": 23618, "s": 23262, "text": "In isolation, it’s hard to tell exactly what our AUC of 0.934 means. As with the metrics was saw earlier based on precision and recall, these are standard comparative tools. We should use them purposefully to develop and tune our current model, and to compare our model to other algorithms to seek out the best possible performance at our particular task." }, { "code": null, "e": 24438, "s": 23618, "text": "We covered a lot of ground today, so congratulations if you made it all the way through! When first taking on a problem, it’s easy to become overwhelmed by the sheer range of algorithms, methods and parameters that could be used as part of an approach to solving it. Model performance metrics can act as the compass that guides us through this wilderness — as long as we break a problem down, decide on an initial approach (we can change later if needed), and use sensible tools like those explained above to evaluate whether we are making progress, we will be moving towards where we need to go. And as heart-breaking as it is to not see hours of research and tinkering with a model reflected in an improvement in a particular performance metric, it’s always better to know whether we are moving forwards or backwards." }, { "code": null, "e": 24714, "s": 24438, "text": "So get stuck in — and don’t get too invested in a particular method if the numbers show that it’s not working out. Review and compare models and approaches dispassionately. If you can manage that, you’ll be sitting in that Ferrari with the cream upholstery in no time at all." }, { "code": null, "e": 24801, "s": 24714, "text": "Andrew Hetherington is an actuary-in-training and data enthusiast based in London, UK." }, { "code": null, "e": 24823, "s": 24801, "text": "Check out my website." }, { "code": null, "e": 24852, "s": 24823, "text": "Connect with me on LinkedIn." }, { "code": null, "e": 24891, "s": 24852, "text": "See what I’m tinkering with on GitHub." }, { "code": null, "e": 24964, "s": 24891, "text": "The notebook used to produce the work in this article can be found here." }, { "code": null, "e": 25199, "s": 24964, "text": "Code chunks in this work have been adapted from A. Géron’s 2019 book, Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow, 2nd Edition, by Aurélien Géron (O’Reilly). Copyright 2019 Kiwisoft S.A.S., 978–1–492–03264–9." } ]
Build a Movie Recommendation API using Scikit-Learn, Flask and Heroku | by Deepak Das | Towards Data Science
Recommendation systems are everywhere. Some of the best examples are YouTube, Netflix, Spotify. Netflix and YouTube rely heavily on their recommendation systems to retain users on their platform for a longer time. Spotify recommends a curated list of songs to the user according to their interests. There are many more examples where recommendation systems play a pivotal role. In short a recommendation system is an algorithm aimed at suggesting relevant data to a user based on past preferences or ratings given by the user or suggesting relevant data to a user based on the item’s attributes. To know more about recommendation systems go through the link mentioned below :- About Recommendation Systems Build a basic Content-Based Movie Recommendation System and make an API using Flask and deploy it to Heroku. We will discuss Content-Based Recommendation System, API and Heroku in detail as we move further in this article. Now, let’s look into the contents of this article. Data set DescriptionBuild a Content-Based Recommendation SystemBuild a REST API using FlaskTest it on local host — 127.0.0.1Deploy to Heroku — API goes online Data set Description Build a Content-Based Recommendation System Build a REST API using Flask Test it on local host — 127.0.0.1 Deploy to Heroku — API goes online We will cover the topics step by step and in the end, we will build a Movie Recommendation API that can be used by anyone to provide relevant movie suggestions to their users in an app or a website. The first thing we require is data. Data about movies like the genre, cast, plot to name a few. For this task, I have taken data from Kaggle. We have two sources of data. TMDB 5000 Movies Data set The Indian Movie Database Now as we wanted a very basic recommendation system to see how it looks when the API is used in an app or website so we combine and modify the dataset according to our needs. The pruning and preprocessing part of the dataset was done separately in one of my Jupyter Notebooks and that is a discussion for some other time. However, if you still want to know about the steps involved in pruning the dataset follow the link below. Jupyter Notebook preprocessing. The notebook may be a little untidy because it was never meant to go online. So, apologies if it is a little hard for anyone to follow. Below is the link to the dataset that will be used to build our Content-Based Recommendation System. Download this dataset and we are good to go. Combined and preprocessed movie dataset So, we have 6477 movies in our dataset with the following attributes:- cast: Top 3 actors/actresses of the movies genres: Top 3 genres of the movies movie_id: TMDb and IMDb IDs for Hollywood and Bollywood movies original_title: Title of the movies plot: Basic overview of the movie We have our dataset ready. Let’s move on to the next part i.e. Building a Content-Based Recommendation System. Content-Based recommendation works on the principle that if a user likes a certain item then we recommend the user a similar item based on the item’s features or attributes. So in our case, if a user likes a movie of a particular genre or an actor then we recommend a movie on similar lines to our user. So, if a user has watched the movie Joker then our recommendation system would predict movies similar to Joker or with the same cast as that of Joker if we consider the movie’s cast. Now that we have a basic idea of what is a Content-Based Recommendation System and how it works let’s code it out. There are 5 functions present in recommendation.py. Let’s discuss about all of them one by one. get_data() is used to fetch the data about the movies and return the dataset with it’s attributes as the result for further preprocessing. Line 2: we read the movie_data.csv.zip file using pandas.read_csv(). Line 3: Convert the title of all the movies to lowercase letters. Line 4: Return the dataset as the function’s result. Return value of get_data() :- combine_data() drops the columns not required for feature extraction and then combines the cast and genres column, finally returning the combine column as the result of this function. Line 2: Drop the attributes not required for feature extraction. Line 3: Combine the two columns cast and genres into one single column. Line 5: We have a combined column with cast and genres values present in it so we remove the cast and genres columns existing separately from our dataset. Line 6: Return the dataset with the combine column. Return value of combine_data() :- Note : Before proceeding any further do go through the topics with their links mentioned below. It will be helpful for you to have a basic understanding of these topics before we move on to the next part i.e. transform_data(). Sparse Matrix Bag of Words Tf-Idf Vectorizer Cosine similarity transform_data() takes the value returned by combine_data() and the plot column from get_data() and applies CountVectorizer and TfidfVectorizer respectively and calculates the Cosine values. Line 2: Make an object for CountVectorizer and initiate to remove English stopwords using the stop_words parameter. Line 3: Fit the CountVectorizer object count onto the value returned by combine_data() i.e. combined column values of cast and genres. After this, we get a sparse matrix as shown in our discussion about Bag-of-Words with the count values of each word. Line 5: Make an object for TfidfVectorizer and initiate to remove English stopwords using the stop_words parameter. Line 6: Fit the TfidfVectorizer object tfdif onto the column plot that we get from get_data(). After this, we get a sparse matrix as shown in our discussion about Tf-Idf Vectorizer with values of each word. Line 8: We combine the two sparse matrices we get by CountVectorizer and TfidfVectorizer into a single sparse matrix. Line 10: We now apply Cosine Similarity on our combined sparse matrix. Line 12: Return the cosine similarity matrix generated as the result of transform_data() Return value of transform_data() :- We use TfidfVectorizer for the plot column because Tf-Idf assigns lower value to words having a higher frequency and higher value to words having a lower frequency in a particular document. For example After Thanos, an intergalactic warlord, disintegrates half of the universe, the Avengers must reunite and assemble again to reinvigorate their trounced allies and restore balance. In this movie plot from Avengers: Endgame we will have higher values assigned to words such as Thanos and Avengers because they appear less number of times but have a higher significance in determining the main theme of the movie. recommend_movies() takes four parameters. title : Name of the movie data : Return value of get_data() combine : Return value of combine_data() transform : Return value of transform_data() Line 3: Create a Pandas Series with indices of all the movies present in our dataset. Line 4: Get the index of the input movie that is passed onto our recommend_movies() function in the title parameter. For example, we pass the movie Logan as our input movie. This line gives us the index of the movie Logan in the pandas series. Line 6: Here we store the Cosine Values of each movie with respect to our input movie. For example our input movie is The Dark Knight. What this line does is it calculates the Cosine Values of all the movies with respect to our input movie. Line 7: After getting the cosine values we sort them in reverse order. As we have read from our brief introduction to the cosine similarity topic closer the document is to the source higher the cosine value. In the above image we see all the cosine values with respect to our input movie. The input movie will be most similar to itself so it’s value is 0.99. After that we see for index 3 our cosine value is 0.530. Now if you compare it with the pandas series output we had The Dark Knight Rises is at index 3 and as expected it is the most similar movie to The Dark Knight. Line 8: We need the top 20 movies with respect to our input movie. So, we store the 20 most similar movies with respect to our input movie Line 10: We store the top 20 movies sorted according to our cosine values in a list. Line 12–14: In these lines, we store the movie indices with their respective columns. Line 16: We create a Pandas DataFrame with Movie_Id, Name, Genres as the columns. Line 18 — 20: We store all the 20 movies similar to our input movie i.e The Dark Knight in the Pandas DataFrame we just created. Line 22: Return the Pandas DataFrame with the top 20 movie recommendations. Return value of recommend_movies() for The Dark Knight:- result() takes a movie’s title as input and returns the top 20 recommendations. Line 2: convert the movie_name to lower case as all the movies is in lower case in our dataset. We do this as a precautionary measure. If a user types a movie name in lower case and upper case letters together then it won’t be a problem as our function will still return the results. For example: If the input is logan or Logan or lOgAn we still get our recommendations. Line 4–6: We store the values returned by get_data(), combine_data() and transform_data(). Line 8–9: Check whether the input movie is present in our dataset. If not found in our dataset then we return that the movie is not found. Line 11–12: If our movie is present in the dataset then we call our recommend_movies() function and pass the return values of get_data(), combine_data() and transform_data() along with the movie name as the function’s parameter. Line 13: We return the movie results in Python dictionary format. Return value of results() :- Now that our recommendation system is ready let’s move on to the next part i.e. Build a REST API using Flask. To understand this part of the article I suggest you have a basic idea about Flask. For our task, we just need to know about some beginner level functionalities. To install Flask on your system head over to the terminal/Command Prompt and type pip install Flask. That’s it, Flask is now installed on your system. To know the basics about a simple Flask application head on to the link below. Flask Hello World If you prefer video lectures do go through the brief explanation provided about Flask from this video. Flask Hello World — Video lecture Now, that we have a basic idea about Flask let’s move on to the next topic i.e. REST APIs. I highly recommend you all have a basic understanding of APIs and one of the design principles of an API i.e. REST API. Go through the link mentioned below. It will provide you with a basic overview of APIs and REST APIs. Understanding And Using REST APIs If you prefer video lectures do go through the brief explanation provided by Telusko about APIs and REST APIs. What is REST API? To know how a REST API can be created it’s highly useful if we first code some basic application and get to know more about the GET method and it’s working. Below mentioned link builds a REST API using Flask with the GET method to display data to the client. Code this out and understand the basics and then move on to the code in our app.py file. Creating a RESTful API With Flask — GET Requests In this file, we will code our Flask application and use the recommendation system we built before. Line 1: We import the Flask class then the request library to send HTTPS requests and finally we import jsonify to return our results in a JSON format. Line 2: We import the flask_cors to enable cross-origin requests for our API. What is a cross-origin request? Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. To know more about the CORS policy do go through the below-mentioned link. It explains all you need to know about CORS policy. What is CORS? Line 3: we import our recommendation.py file as a module to use it in our app.py file. Line 1: we create an instance of this class. The first argument is the name of the application’s module or package. Line 2: We use the CORS() method to enable the CORS policy on our API. Line 4: We then use the route() decorator to tell Flask what URL should trigger our function. In this case, we use the /movie endpoint with the base URL. Line 5: Now, we define a function named recommend_movies() which will be used to return the top 20 recommendations. Line 6: In this line, we call the results() function from our recommendation.py file and store the recommendations in a variable named res. The movie name is passed as a query string to our results() function using the request.args.get() and the parameter name is title. Line 7: Lastly we return the results received from recommendation.py in a dictionary format to app.py and convert them to JSON format and return the results. Line 9: This line indicates that if we call our app.py file directly from the terminal/command prompt then it will execute what follows after. Line 10: We run the app after our app.py file is called directly in the terminal/command prompt. We set our port number to 5000 when running on localhost and we set debug=True to trace back any errors that occurs whilst running our application. Now, that we are done with the coding part let’s test our application on localhost and see if it’s working. If you want to use Postman for testing our API then download it from the below link. Download Postman You can use your browser for testing as well if you prefer that over Postman. We will test on both of them and you will get to see the results. Step — 1: Open up your command prompt if in Windows or terminal if you are using Linux. Step — 2: Navigate to the folder where you have stored the dataset, recommendation.py file and app.py file using command line. We store our files in a folder named Recommendation 2.0. Below is our directory structure. All the files and the dataset should be present in a single folder for ease of use when developing the application. Step — 3: When we are in our Recommendation 2.0 folder type the following commands in the command line. set FLASK_APP=app.py for running the application:- flask run After executing both the commands we will see our application running on localhost. Step — 4: Test our API on localhost using Postman or any browser. Let’s see our results when we pass a movie to our API. We are done with testing our API on localhost and it works perfectly. Let’s move onto the last part i.e. deploying our API to Heroku. Before we move on to the deployment part we need to have a basic understanding about GitHub. You should be able to make a new repository, add files, delete files and create folders in the repository if necessary. Step — 1: Create a repository with any name you like. I have named my repository BioScope, the reason is me and my friends thought it was a cool name. Step — 2: Create Procfile Heroku apps include a Procfile that specifies the commands that are executed by the app on startup. You can use a Procfile to declare a variety of process types, including: Your app’s web server. To create one, open up a new file named Procfile (no extension) in the working directory and paste the following. web: gunicorn app:app --max-requests 2 We add max requests to ensure our server restarts after every 2nd request to our API. This is done to ensure that we do not exceed our RAM limit of 512 MB allotted by Heroku when using the API. Step — 3: Create requirements.txt The requirements.txt file will contain all of the dependencies for the flask app. If you’re not working from a new environment, this file will contain all requirements from your current environment. At the bare minimum for this project, your requirements.txt should contain: Flask==1.1.2 Flask-Cors==3.0.8 Flask-RESTful==0.3.7 gunicorn==20.0.4 joblib==0.13.2 jsonschema==2.6.0 pandas==0.25.1 pickleshare==0.7.5requests==2.23.0 requests-file==1.4.3 scikit-learn==0.22.2 scipy==1.4.1 wcwidth==0.1.7 webencodings==0.5.1Werkzeug==1.0.1 Copy paste the above in your requirements.txt file and commit it to the repository. Step — 4: Commit recommendation.py, app.py. Step — 5: Make a folder named dataset/ in your repository and commit the movie_data.csv.zip file. Our repository structure should look something like this:- The Jupyter Notebook contains the preprocessing part involved to make our movie_data.csv.zip file. So, this folder is optional. Apart from that all the other files and folders are necessary. recommendation.py app.py requirements.txt Procfile Note: All of the above files should be at the working directory level and not in another folder. We can deploy our app using either Heroku CLI or GitHub. In this article we will discuss how we can deploy our app using GitHub. Step — 1: Create a free account at www.heroku.com. Step — 2: Create a new app simply by choosing a name and clicking “create app”. This name doesn’t matter but it does have to be unique. Step — 3: Connect your GitHub account by clicking the GitHub icon below. Step — 4: Search for the correct repository and click connect. Step — 5: Scroll to the bottom of the page and click “Deploy Branch”. If something went wrong, check your requirements.txt, delete the dependencies that are giving you problems, and try again. Notice the link through which we send the GET request. Anyone with the Heroku link can now access the movie recommendation API and show movie suggestions to their users. So, we have reached the end of this article. I hope you have learned something new and I surely want you all to use the API or build something similar to this. We just built a basic Content-Based Recommendation System. Much more can be done than this like building a Collaborative Recommendation System or even building a Hybrid Recommendation System. We will discuss about that in detail but that’s a story for another blog post. BioScope Movie Recommendation API
[ { "code": null, "e": 550, "s": 172, "text": "Recommendation systems are everywhere. Some of the best examples are YouTube, Netflix, Spotify. Netflix and YouTube rely heavily on their recommendation systems to retain users on their platform for a longer time. Spotify recommends a curated list of songs to the user according to their interests. There are many more examples where recommendation systems play a pivotal role." }, { "code": null, "e": 768, "s": 550, "text": "In short a recommendation system is an algorithm aimed at suggesting relevant data to a user based on past preferences or ratings given by the user or suggesting relevant data to a user based on the item’s attributes." }, { "code": null, "e": 849, "s": 768, "text": "To know more about recommendation systems go through the link mentioned below :-" }, { "code": null, "e": 878, "s": 849, "text": "About Recommendation Systems" }, { "code": null, "e": 987, "s": 878, "text": "Build a basic Content-Based Movie Recommendation System and make an API using Flask and deploy it to Heroku." }, { "code": null, "e": 1101, "s": 987, "text": "We will discuss Content-Based Recommendation System, API and Heroku in detail as we move further in this article." }, { "code": null, "e": 1152, "s": 1101, "text": "Now, let’s look into the contents of this article." }, { "code": null, "e": 1311, "s": 1152, "text": "Data set DescriptionBuild a Content-Based Recommendation SystemBuild a REST API using FlaskTest it on local host — 127.0.0.1Deploy to Heroku — API goes online" }, { "code": null, "e": 1332, "s": 1311, "text": "Data set Description" }, { "code": null, "e": 1376, "s": 1332, "text": "Build a Content-Based Recommendation System" }, { "code": null, "e": 1405, "s": 1376, "text": "Build a REST API using Flask" }, { "code": null, "e": 1439, "s": 1405, "text": "Test it on local host — 127.0.0.1" }, { "code": null, "e": 1474, "s": 1439, "text": "Deploy to Heroku — API goes online" }, { "code": null, "e": 1673, "s": 1474, "text": "We will cover the topics step by step and in the end, we will build a Movie Recommendation API that can be used by anyone to provide relevant movie suggestions to their users in an app or a website." }, { "code": null, "e": 1844, "s": 1673, "text": "The first thing we require is data. Data about movies like the genre, cast, plot to name a few. For this task, I have taken data from Kaggle. We have two sources of data." }, { "code": null, "e": 1870, "s": 1844, "text": "TMDB 5000 Movies Data set" }, { "code": null, "e": 1896, "s": 1870, "text": "The Indian Movie Database" }, { "code": null, "e": 2071, "s": 1896, "text": "Now as we wanted a very basic recommendation system to see how it looks when the API is used in an app or website so we combine and modify the dataset according to our needs." }, { "code": null, "e": 2324, "s": 2071, "text": "The pruning and preprocessing part of the dataset was done separately in one of my Jupyter Notebooks and that is a discussion for some other time. However, if you still want to know about the steps involved in pruning the dataset follow the link below." }, { "code": null, "e": 2356, "s": 2324, "text": "Jupyter Notebook preprocessing." }, { "code": null, "e": 2492, "s": 2356, "text": "The notebook may be a little untidy because it was never meant to go online. So, apologies if it is a little hard for anyone to follow." }, { "code": null, "e": 2638, "s": 2492, "text": "Below is the link to the dataset that will be used to build our Content-Based Recommendation System. Download this dataset and we are good to go." }, { "code": null, "e": 2678, "s": 2638, "text": "Combined and preprocessed movie dataset" }, { "code": null, "e": 2749, "s": 2678, "text": "So, we have 6477 movies in our dataset with the following attributes:-" }, { "code": null, "e": 2792, "s": 2749, "text": "cast: Top 3 actors/actresses of the movies" }, { "code": null, "e": 2827, "s": 2792, "text": "genres: Top 3 genres of the movies" }, { "code": null, "e": 2890, "s": 2827, "text": "movie_id: TMDb and IMDb IDs for Hollywood and Bollywood movies" }, { "code": null, "e": 2926, "s": 2890, "text": "original_title: Title of the movies" }, { "code": null, "e": 2960, "s": 2926, "text": "plot: Basic overview of the movie" }, { "code": null, "e": 3071, "s": 2960, "text": "We have our dataset ready. Let’s move on to the next part i.e. Building a Content-Based Recommendation System." }, { "code": null, "e": 3558, "s": 3071, "text": "Content-Based recommendation works on the principle that if a user likes a certain item then we recommend the user a similar item based on the item’s features or attributes. So in our case, if a user likes a movie of a particular genre or an actor then we recommend a movie on similar lines to our user. So, if a user has watched the movie Joker then our recommendation system would predict movies similar to Joker or with the same cast as that of Joker if we consider the movie’s cast." }, { "code": null, "e": 3673, "s": 3558, "text": "Now that we have a basic idea of what is a Content-Based Recommendation System and how it works let’s code it out." }, { "code": null, "e": 3769, "s": 3673, "text": "There are 5 functions present in recommendation.py. Let’s discuss about all of them one by one." }, { "code": null, "e": 3908, "s": 3769, "text": "get_data() is used to fetch the data about the movies and return the dataset with it’s attributes as the result for further preprocessing." }, { "code": null, "e": 3977, "s": 3908, "text": "Line 2: we read the movie_data.csv.zip file using pandas.read_csv()." }, { "code": null, "e": 4043, "s": 3977, "text": "Line 3: Convert the title of all the movies to lowercase letters." }, { "code": null, "e": 4096, "s": 4043, "text": "Line 4: Return the dataset as the function’s result." }, { "code": null, "e": 4126, "s": 4096, "text": "Return value of get_data() :-" }, { "code": null, "e": 4310, "s": 4126, "text": "combine_data() drops the columns not required for feature extraction and then combines the cast and genres column, finally returning the combine column as the result of this function." }, { "code": null, "e": 4375, "s": 4310, "text": "Line 2: Drop the attributes not required for feature extraction." }, { "code": null, "e": 4447, "s": 4375, "text": "Line 3: Combine the two columns cast and genres into one single column." }, { "code": null, "e": 4602, "s": 4447, "text": "Line 5: We have a combined column with cast and genres values present in it so we remove the cast and genres columns existing separately from our dataset." }, { "code": null, "e": 4654, "s": 4602, "text": "Line 6: Return the dataset with the combine column." }, { "code": null, "e": 4688, "s": 4654, "text": "Return value of combine_data() :-" }, { "code": null, "e": 4915, "s": 4688, "text": "Note : Before proceeding any further do go through the topics with their links mentioned below. It will be helpful for you to have a basic understanding of these topics before we move on to the next part i.e. transform_data()." }, { "code": null, "e": 4929, "s": 4915, "text": "Sparse Matrix" }, { "code": null, "e": 4942, "s": 4929, "text": "Bag of Words" }, { "code": null, "e": 4960, "s": 4942, "text": "Tf-Idf Vectorizer" }, { "code": null, "e": 4978, "s": 4960, "text": "Cosine similarity" }, { "code": null, "e": 5169, "s": 4978, "text": "transform_data() takes the value returned by combine_data() and the plot column from get_data() and applies CountVectorizer and TfidfVectorizer respectively and calculates the Cosine values." }, { "code": null, "e": 5285, "s": 5169, "text": "Line 2: Make an object for CountVectorizer and initiate to remove English stopwords using the stop_words parameter." }, { "code": null, "e": 5537, "s": 5285, "text": "Line 3: Fit the CountVectorizer object count onto the value returned by combine_data() i.e. combined column values of cast and genres. After this, we get a sparse matrix as shown in our discussion about Bag-of-Words with the count values of each word." }, { "code": null, "e": 5653, "s": 5537, "text": "Line 5: Make an object for TfidfVectorizer and initiate to remove English stopwords using the stop_words parameter." }, { "code": null, "e": 5860, "s": 5653, "text": "Line 6: Fit the TfidfVectorizer object tfdif onto the column plot that we get from get_data(). After this, we get a sparse matrix as shown in our discussion about Tf-Idf Vectorizer with values of each word." }, { "code": null, "e": 5978, "s": 5860, "text": "Line 8: We combine the two sparse matrices we get by CountVectorizer and TfidfVectorizer into a single sparse matrix." }, { "code": null, "e": 6049, "s": 5978, "text": "Line 10: We now apply Cosine Similarity on our combined sparse matrix." }, { "code": null, "e": 6138, "s": 6049, "text": "Line 12: Return the cosine similarity matrix generated as the result of transform_data()" }, { "code": null, "e": 6174, "s": 6138, "text": "Return value of transform_data() :-" }, { "code": null, "e": 6364, "s": 6174, "text": "We use TfidfVectorizer for the plot column because Tf-Idf assigns lower value to words having a higher frequency and higher value to words having a lower frequency in a particular document." }, { "code": null, "e": 6376, "s": 6364, "text": "For example" }, { "code": null, "e": 6556, "s": 6376, "text": "After Thanos, an intergalactic warlord, disintegrates half of the universe, the Avengers must reunite and assemble again to reinvigorate their trounced allies and restore balance." }, { "code": null, "e": 6787, "s": 6556, "text": "In this movie plot from Avengers: Endgame we will have higher values assigned to words such as Thanos and Avengers because they appear less number of times but have a higher significance in determining the main theme of the movie." }, { "code": null, "e": 6829, "s": 6787, "text": "recommend_movies() takes four parameters." }, { "code": null, "e": 6855, "s": 6829, "text": "title : Name of the movie" }, { "code": null, "e": 6889, "s": 6855, "text": "data : Return value of get_data()" }, { "code": null, "e": 6930, "s": 6889, "text": "combine : Return value of combine_data()" }, { "code": null, "e": 6975, "s": 6930, "text": "transform : Return value of transform_data()" }, { "code": null, "e": 7061, "s": 6975, "text": "Line 3: Create a Pandas Series with indices of all the movies present in our dataset." }, { "code": null, "e": 7178, "s": 7061, "text": "Line 4: Get the index of the input movie that is passed onto our recommend_movies() function in the title parameter." }, { "code": null, "e": 7305, "s": 7178, "text": "For example, we pass the movie Logan as our input movie. This line gives us the index of the movie Logan in the pandas series." }, { "code": null, "e": 7392, "s": 7305, "text": "Line 6: Here we store the Cosine Values of each movie with respect to our input movie." }, { "code": null, "e": 7546, "s": 7392, "text": "For example our input movie is The Dark Knight. What this line does is it calculates the Cosine Values of all the movies with respect to our input movie." }, { "code": null, "e": 7754, "s": 7546, "text": "Line 7: After getting the cosine values we sort them in reverse order. As we have read from our brief introduction to the cosine similarity topic closer the document is to the source higher the cosine value." }, { "code": null, "e": 8122, "s": 7754, "text": "In the above image we see all the cosine values with respect to our input movie. The input movie will be most similar to itself so it’s value is 0.99. After that we see for index 3 our cosine value is 0.530. Now if you compare it with the pandas series output we had The Dark Knight Rises is at index 3 and as expected it is the most similar movie to The Dark Knight." }, { "code": null, "e": 8261, "s": 8122, "text": "Line 8: We need the top 20 movies with respect to our input movie. So, we store the 20 most similar movies with respect to our input movie" }, { "code": null, "e": 8346, "s": 8261, "text": "Line 10: We store the top 20 movies sorted according to our cosine values in a list." }, { "code": null, "e": 8432, "s": 8346, "text": "Line 12–14: In these lines, we store the movie indices with their respective columns." }, { "code": null, "e": 8514, "s": 8432, "text": "Line 16: We create a Pandas DataFrame with Movie_Id, Name, Genres as the columns." }, { "code": null, "e": 8643, "s": 8514, "text": "Line 18 — 20: We store all the 20 movies similar to our input movie i.e The Dark Knight in the Pandas DataFrame we just created." }, { "code": null, "e": 8719, "s": 8643, "text": "Line 22: Return the Pandas DataFrame with the top 20 movie recommendations." }, { "code": null, "e": 8776, "s": 8719, "text": "Return value of recommend_movies() for The Dark Knight:-" }, { "code": null, "e": 8856, "s": 8776, "text": "result() takes a movie’s title as input and returns the top 20 recommendations." }, { "code": null, "e": 9140, "s": 8856, "text": "Line 2: convert the movie_name to lower case as all the movies is in lower case in our dataset. We do this as a precautionary measure. If a user types a movie name in lower case and upper case letters together then it won’t be a problem as our function will still return the results." }, { "code": null, "e": 9227, "s": 9140, "text": "For example: If the input is logan or Logan or lOgAn we still get our recommendations." }, { "code": null, "e": 9318, "s": 9227, "text": "Line 4–6: We store the values returned by get_data(), combine_data() and transform_data()." }, { "code": null, "e": 9457, "s": 9318, "text": "Line 8–9: Check whether the input movie is present in our dataset. If not found in our dataset then we return that the movie is not found." }, { "code": null, "e": 9686, "s": 9457, "text": "Line 11–12: If our movie is present in the dataset then we call our recommend_movies() function and pass the return values of get_data(), combine_data() and transform_data() along with the movie name as the function’s parameter." }, { "code": null, "e": 9752, "s": 9686, "text": "Line 13: We return the movie results in Python dictionary format." }, { "code": null, "e": 9781, "s": 9752, "text": "Return value of results() :-" }, { "code": null, "e": 9891, "s": 9781, "text": "Now that our recommendation system is ready let’s move on to the next part i.e. Build a REST API using Flask." }, { "code": null, "e": 10053, "s": 9891, "text": "To understand this part of the article I suggest you have a basic idea about Flask. For our task, we just need to know about some beginner level functionalities." }, { "code": null, "e": 10204, "s": 10053, "text": "To install Flask on your system head over to the terminal/Command Prompt and type pip install Flask. That’s it, Flask is now installed on your system." }, { "code": null, "e": 10283, "s": 10204, "text": "To know the basics about a simple Flask application head on to the link below." }, { "code": null, "e": 10301, "s": 10283, "text": "Flask Hello World" }, { "code": null, "e": 10404, "s": 10301, "text": "If you prefer video lectures do go through the brief explanation provided about Flask from this video." }, { "code": null, "e": 10438, "s": 10404, "text": "Flask Hello World — Video lecture" }, { "code": null, "e": 10529, "s": 10438, "text": "Now, that we have a basic idea about Flask let’s move on to the next topic i.e. REST APIs." }, { "code": null, "e": 10649, "s": 10529, "text": "I highly recommend you all have a basic understanding of APIs and one of the design principles of an API i.e. REST API." }, { "code": null, "e": 10751, "s": 10649, "text": "Go through the link mentioned below. It will provide you with a basic overview of APIs and REST APIs." }, { "code": null, "e": 10785, "s": 10751, "text": "Understanding And Using REST APIs" }, { "code": null, "e": 10896, "s": 10785, "text": "If you prefer video lectures do go through the brief explanation provided by Telusko about APIs and REST APIs." }, { "code": null, "e": 10914, "s": 10896, "text": "What is REST API?" }, { "code": null, "e": 11071, "s": 10914, "text": "To know how a REST API can be created it’s highly useful if we first code some basic application and get to know more about the GET method and it’s working." }, { "code": null, "e": 11262, "s": 11071, "text": "Below mentioned link builds a REST API using Flask with the GET method to display data to the client. Code this out and understand the basics and then move on to the code in our app.py file." }, { "code": null, "e": 11311, "s": 11262, "text": "Creating a RESTful API With Flask — GET Requests" }, { "code": null, "e": 11411, "s": 11311, "text": "In this file, we will code our Flask application and use the recommendation system we built before." }, { "code": null, "e": 11563, "s": 11411, "text": "Line 1: We import the Flask class then the request library to send HTTPS requests and finally we import jsonify to return our results in a JSON format." }, { "code": null, "e": 11641, "s": 11563, "text": "Line 2: We import the flask_cors to enable cross-origin requests for our API." }, { "code": null, "e": 11673, "s": 11641, "text": "What is a cross-origin request?" }, { "code": null, "e": 11869, "s": 11673, "text": "Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served." }, { "code": null, "e": 11996, "s": 11869, "text": "To know more about the CORS policy do go through the below-mentioned link. It explains all you need to know about CORS policy." }, { "code": null, "e": 12010, "s": 11996, "text": "What is CORS?" }, { "code": null, "e": 12097, "s": 12010, "text": "Line 3: we import our recommendation.py file as a module to use it in our app.py file." }, { "code": null, "e": 12213, "s": 12097, "text": "Line 1: we create an instance of this class. The first argument is the name of the application’s module or package." }, { "code": null, "e": 12284, "s": 12213, "text": "Line 2: We use the CORS() method to enable the CORS policy on our API." }, { "code": null, "e": 12438, "s": 12284, "text": "Line 4: We then use the route() decorator to tell Flask what URL should trigger our function. In this case, we use the /movie endpoint with the base URL." }, { "code": null, "e": 12554, "s": 12438, "text": "Line 5: Now, we define a function named recommend_movies() which will be used to return the top 20 recommendations." }, { "code": null, "e": 12825, "s": 12554, "text": "Line 6: In this line, we call the results() function from our recommendation.py file and store the recommendations in a variable named res. The movie name is passed as a query string to our results() function using the request.args.get() and the parameter name is title." }, { "code": null, "e": 12983, "s": 12825, "text": "Line 7: Lastly we return the results received from recommendation.py in a dictionary format to app.py and convert them to JSON format and return the results." }, { "code": null, "e": 13126, "s": 12983, "text": "Line 9: This line indicates that if we call our app.py file directly from the terminal/command prompt then it will execute what follows after." }, { "code": null, "e": 13371, "s": 13126, "text": "Line 10: We run the app after our app.py file is called directly in the terminal/command prompt. We set our port number to 5000 when running on localhost and we set debug=True to trace back any errors that occurs whilst running our application." }, { "code": null, "e": 13479, "s": 13371, "text": "Now, that we are done with the coding part let’s test our application on localhost and see if it’s working." }, { "code": null, "e": 13564, "s": 13479, "text": "If you want to use Postman for testing our API then download it from the below link." }, { "code": null, "e": 13581, "s": 13564, "text": "Download Postman" }, { "code": null, "e": 13725, "s": 13581, "text": "You can use your browser for testing as well if you prefer that over Postman. We will test on both of them and you will get to see the results." }, { "code": null, "e": 13813, "s": 13725, "text": "Step — 1: Open up your command prompt if in Windows or terminal if you are using Linux." }, { "code": null, "e": 13940, "s": 13813, "text": "Step — 2: Navigate to the folder where you have stored the dataset, recommendation.py file and app.py file using command line." }, { "code": null, "e": 14031, "s": 13940, "text": "We store our files in a folder named Recommendation 2.0. Below is our directory structure." }, { "code": null, "e": 14147, "s": 14031, "text": "All the files and the dataset should be present in a single folder for ease of use when developing the application." }, { "code": null, "e": 14251, "s": 14147, "text": "Step — 3: When we are in our Recommendation 2.0 folder type the following commands in the command line." }, { "code": null, "e": 14272, "s": 14251, "text": "set FLASK_APP=app.py" }, { "code": null, "e": 14302, "s": 14272, "text": "for running the application:-" }, { "code": null, "e": 14312, "s": 14302, "text": "flask run" }, { "code": null, "e": 14396, "s": 14312, "text": "After executing both the commands we will see our application running on localhost." }, { "code": null, "e": 14462, "s": 14396, "text": "Step — 4: Test our API on localhost using Postman or any browser." }, { "code": null, "e": 14517, "s": 14462, "text": "Let’s see our results when we pass a movie to our API." }, { "code": null, "e": 14587, "s": 14517, "text": "We are done with testing our API on localhost and it works perfectly." }, { "code": null, "e": 14651, "s": 14587, "text": "Let’s move onto the last part i.e. deploying our API to Heroku." }, { "code": null, "e": 14864, "s": 14651, "text": "Before we move on to the deployment part we need to have a basic understanding about GitHub. You should be able to make a new repository, add files, delete files and create folders in the repository if necessary." }, { "code": null, "e": 15015, "s": 14864, "text": "Step — 1: Create a repository with any name you like. I have named my repository BioScope, the reason is me and my friends thought it was a cool name." }, { "code": null, "e": 15041, "s": 15015, "text": "Step — 2: Create Procfile" }, { "code": null, "e": 15237, "s": 15041, "text": "Heroku apps include a Procfile that specifies the commands that are executed by the app on startup. You can use a Procfile to declare a variety of process types, including: Your app’s web server." }, { "code": null, "e": 15351, "s": 15237, "text": "To create one, open up a new file named Procfile (no extension) in the working directory and paste the following." }, { "code": null, "e": 15390, "s": 15351, "text": "web: gunicorn app:app --max-requests 2" }, { "code": null, "e": 15584, "s": 15390, "text": "We add max requests to ensure our server restarts after every 2nd request to our API. This is done to ensure that we do not exceed our RAM limit of 512 MB allotted by Heroku when using the API." }, { "code": null, "e": 15618, "s": 15584, "text": "Step — 3: Create requirements.txt" }, { "code": null, "e": 15817, "s": 15618, "text": "The requirements.txt file will contain all of the dependencies for the flask app. If you’re not working from a new environment, this file will contain all requirements from your current environment." }, { "code": null, "e": 15893, "s": 15817, "text": "At the bare minimum for this project, your requirements.txt should contain:" }, { "code": null, "e": 16150, "s": 15893, "text": "Flask==1.1.2 Flask-Cors==3.0.8 Flask-RESTful==0.3.7 gunicorn==20.0.4 joblib==0.13.2 jsonschema==2.6.0 pandas==0.25.1 pickleshare==0.7.5requests==2.23.0 requests-file==1.4.3 scikit-learn==0.22.2 scipy==1.4.1 wcwidth==0.1.7 webencodings==0.5.1Werkzeug==1.0.1" }, { "code": null, "e": 16234, "s": 16150, "text": "Copy paste the above in your requirements.txt file and commit it to the repository." }, { "code": null, "e": 16278, "s": 16234, "text": "Step — 4: Commit recommendation.py, app.py." }, { "code": null, "e": 16376, "s": 16278, "text": "Step — 5: Make a folder named dataset/ in your repository and commit the movie_data.csv.zip file." }, { "code": null, "e": 16435, "s": 16376, "text": "Our repository structure should look something like this:-" }, { "code": null, "e": 16626, "s": 16435, "text": "The Jupyter Notebook contains the preprocessing part involved to make our movie_data.csv.zip file. So, this folder is optional. Apart from that all the other files and folders are necessary." }, { "code": null, "e": 16644, "s": 16626, "text": "recommendation.py" }, { "code": null, "e": 16651, "s": 16644, "text": "app.py" }, { "code": null, "e": 16668, "s": 16651, "text": "requirements.txt" }, { "code": null, "e": 16677, "s": 16668, "text": "Procfile" }, { "code": null, "e": 16774, "s": 16677, "text": "Note: All of the above files should be at the working directory level and not in another folder." }, { "code": null, "e": 16903, "s": 16774, "text": "We can deploy our app using either Heroku CLI or GitHub. In this article we will discuss how we can deploy our app using GitHub." }, { "code": null, "e": 16954, "s": 16903, "text": "Step — 1: Create a free account at www.heroku.com." }, { "code": null, "e": 17090, "s": 16954, "text": "Step — 2: Create a new app simply by choosing a name and clicking “create app”. This name doesn’t matter but it does have to be unique." }, { "code": null, "e": 17163, "s": 17090, "text": "Step — 3: Connect your GitHub account by clicking the GitHub icon below." }, { "code": null, "e": 17226, "s": 17163, "text": "Step — 4: Search for the correct repository and click connect." }, { "code": null, "e": 17296, "s": 17226, "text": "Step — 5: Scroll to the bottom of the page and click “Deploy Branch”." }, { "code": null, "e": 17419, "s": 17296, "text": "If something went wrong, check your requirements.txt, delete the dependencies that are giving you problems, and try again." }, { "code": null, "e": 17474, "s": 17419, "text": "Notice the link through which we send the GET request." }, { "code": null, "e": 17589, "s": 17474, "text": "Anyone with the Heroku link can now access the movie recommendation API and show movie suggestions to their users." }, { "code": null, "e": 17749, "s": 17589, "text": "So, we have reached the end of this article. I hope you have learned something new and I surely want you all to use the API or build something similar to this." }, { "code": null, "e": 18020, "s": 17749, "text": "We just built a basic Content-Based Recommendation System. Much more can be done than this like building a Collaborative Recommendation System or even building a Hybrid Recommendation System. We will discuss about that in detail but that’s a story for another blog post." } ]
Retrieve data from a MongoDB collection?
To return a single document from a collection, use findOne() in MongoDB. Let us create a collection with documents − > db.demo463.insertOne({"StudentName":"Chris Brown","StudentAge":21,"StudentCountryName":"US"});{ "acknowledged" : true, "insertedId" : ObjectId("5e7f7ec8cb66ccba22cc9dcf") } > db.demo463.insertOne({"StudentName":"David Miller","StudentAge":23,"StudentCountryName":"UK"});{ "acknowledged" : true, "insertedId" : ObjectId("5e7f7ed5cb66ccba22cc9dd0") } > db.demo463.insertOne({"StudentName":"John Doe","StudentAge":22,"StudentCountryName":"AUS"});{ "acknowledged" : true, "insertedId" : ObjectId("5e7f7ee1cb66ccba22cc9dd1") } > db.demo463.insertOne({"StudentName":"John Smith","StudentAge":24,"StudentCountryName":"US"});{ "acknowledged" : true, "insertedId" : ObjectId("5e7f7eefcb66ccba22cc9dd2") } Display all documents from a collection with the help of find() method − > db.demo463.find(); This will produce the following output − { "_id" : ObjectId("5e7f7ec8cb66ccba22cc9dcf"), "StudentName" : "Chris Brown", "StudentAge" : 21, "StudentCountryName" : "US" } { "_id" : ObjectId("5e7f7ed5cb66ccba22cc9dd0"), "StudentName" : "David Miller", "StudentAge" : 23, "StudentCountryName" : "UK" } { "_id" : ObjectId("5e7f7ee1cb66ccba22cc9dd1"), "StudentName" : "John Doe", "StudentAge" : 22, "StudentCountryName" : "AUS" } { "_id" : ObjectId("5e7f7eefcb66ccba22cc9dd2"), "StudentName" : "John Smith", "StudentAge" : 24, "StudentCountryName" : "US" } Following is the query to retrieve data from MongoDB − > db.demo463.findOne({"StudentName":"John Doe"}); This will produce the following output − { "_id" : ObjectId("5e7f7ee1cb66ccba22cc9dd1"), "StudentName" : "John Doe", "StudentAge" : 22, "StudentCountryName" : "AUS" }
[ { "code": null, "e": 1179, "s": 1062, "text": "To return a single document from a collection, use findOne() in MongoDB. Let us create a collection with documents −" }, { "code": null, "e": 1901, "s": 1179, "text": "> db.demo463.insertOne({\"StudentName\":\"Chris\nBrown\",\"StudentAge\":21,\"StudentCountryName\":\"US\"});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e7f7ec8cb66ccba22cc9dcf\")\n}\n> db.demo463.insertOne({\"StudentName\":\"David\nMiller\",\"StudentAge\":23,\"StudentCountryName\":\"UK\"});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e7f7ed5cb66ccba22cc9dd0\")\n}\n> db.demo463.insertOne({\"StudentName\":\"John\nDoe\",\"StudentAge\":22,\"StudentCountryName\":\"AUS\"});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e7f7ee1cb66ccba22cc9dd1\")\n}\n> db.demo463.insertOne({\"StudentName\":\"John\nSmith\",\"StudentAge\":24,\"StudentCountryName\":\"US\"});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e7f7eefcb66ccba22cc9dd2\")\n}" }, { "code": null, "e": 1974, "s": 1901, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1995, "s": 1974, "text": "> db.demo463.find();" }, { "code": null, "e": 2036, "s": 1995, "text": "This will produce the following output −" }, { "code": null, "e": 2546, "s": 2036, "text": "{ \"_id\" : ObjectId(\"5e7f7ec8cb66ccba22cc9dcf\"), \"StudentName\" : \"Chris Brown\",\n\"StudentAge\" : 21, \"StudentCountryName\" : \"US\" }\n{ \"_id\" : ObjectId(\"5e7f7ed5cb66ccba22cc9dd0\"), \"StudentName\" : \"David Miller\",\n\"StudentAge\" : 23, \"StudentCountryName\" : \"UK\" }\n{ \"_id\" : ObjectId(\"5e7f7ee1cb66ccba22cc9dd1\"), \"StudentName\" : \"John Doe\", \"StudentAge\" :\n22, \"StudentCountryName\" : \"AUS\" }\n{ \"_id\" : ObjectId(\"5e7f7eefcb66ccba22cc9dd2\"), \"StudentName\" : \"John Smith\", \"StudentAge\"\n: 24, \"StudentCountryName\" : \"US\" }" }, { "code": null, "e": 2601, "s": 2546, "text": "Following is the query to retrieve data from MongoDB −" }, { "code": null, "e": 2651, "s": 2601, "text": "> db.demo463.findOne({\"StudentName\":\"John Doe\"});" }, { "code": null, "e": 2692, "s": 2651, "text": "This will produce the following output −" }, { "code": null, "e": 2830, "s": 2692, "text": "{\n \"_id\" : ObjectId(\"5e7f7ee1cb66ccba22cc9dd1\"),\n \"StudentName\" : \"John Doe\",\n \"StudentAge\" : 22,\n \"StudentCountryName\" : \"AUS\"\n}" } ]
Distribute Candies in C++
Suppose we have an array with even length, here different numbers in this array will represent different kinds of candies. Now each number means one candy of the corresponding kind. we have to distribute candies equally in number to brother and sister. We have to find the maximum number of kinds of candies the sister could receive. So, if the input is like [1,1,2,3], then the output will be 2 as if we consider the sister has candies [2,3] and the brother has candies [1,1]. Now the sister has two different kinds of candies, the brother has only one kind of candies. To solve this, we will follow these steps − Define one set s Define one set s for initialize i := 0, when i < size of candies, update (increase i by 1), do −insert candies[i] into s for initialize i := 0, when i < size of candies, update (increase i by 1), do − insert candies[i] into s insert candies[i] into s return a minimum of size of s and size of candies / 2 return a minimum of size of s and size of candies / 2 Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int distributeCandies(vector<int>& candies){ unordered_set<int> s; for (int i = 0; i < candies.size(); i++) s.insert(candies[i]); return min(s.size(), candies.size() / 2); } }; main(){ Solution ob; vector<int> v = {1,1,2,3}; cout << (ob.distributeCandies(v)); } {1,1,2,3} 2
[ { "code": null, "e": 1396, "s": 1062, "text": "Suppose we have an array with even length, here different numbers in this array will represent different kinds of candies. Now each number means one candy of the corresponding kind. we have to distribute candies equally in number to brother and sister. We have to find the maximum number of kinds of candies the sister could receive." }, { "code": null, "e": 1633, "s": 1396, "text": "So, if the input is like [1,1,2,3], then the output will be 2 as if we consider the sister has candies [2,3] and the brother has candies [1,1]. Now the sister has two different kinds of candies, the brother has only one kind of candies." }, { "code": null, "e": 1677, "s": 1633, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1694, "s": 1677, "text": "Define one set s" }, { "code": null, "e": 1711, "s": 1694, "text": "Define one set s" }, { "code": null, "e": 1815, "s": 1711, "text": "for initialize i := 0, when i < size of candies, update (increase i by 1), do −insert candies[i] into s" }, { "code": null, "e": 1895, "s": 1815, "text": "for initialize i := 0, when i < size of candies, update (increase i by 1), do −" }, { "code": null, "e": 1920, "s": 1895, "text": "insert candies[i] into s" }, { "code": null, "e": 1945, "s": 1920, "text": "insert candies[i] into s" }, { "code": null, "e": 1999, "s": 1945, "text": "return a minimum of size of s and size of candies / 2" }, { "code": null, "e": 2053, "s": 1999, "text": "return a minimum of size of s and size of candies / 2" }, { "code": null, "e": 2125, "s": 2053, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 2136, "s": 2125, "text": " Live Demo" }, { "code": null, "e": 2511, "s": 2136, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candies){\n unordered_set<int> s;\n for (int i = 0; i < candies.size(); i++)\n s.insert(candies[i]);\n return min(s.size(), candies.size() / 2);\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {1,1,2,3};\n cout << (ob.distributeCandies(v));\n}" }, { "code": null, "e": 2521, "s": 2511, "text": "{1,1,2,3}" }, { "code": null, "e": 2523, "s": 2521, "text": "2" } ]
Describe a NumPy Array in Python - GeeksforGeeks
02 Sep, 2021 NumPy is a Python library used for numerical computing. It offers robust multidimensional arrays as a Python object along with a variety of mathematical functions. In this article, we will go through all the essential NumPy functions used in the descriptive analysis of an array. Let’s start by initializing a sample array for our analysis. The following code initializes a NumPy array: Python3 import numpy as np # sample arrayarr = np.array([4, 5, 8, 5, 6, 4, 9, 2, 4, 3, 6])print(arr) Output: [4 5 8 5 6 4 9 2 4 3 6] In order to describe our NumPy array, we need to find two types of statistics: Measures of central tendency. Measures of dispersion. The following methods are used to find measures of central tendency in NumPy: mean()- takes a NumPy array as an argument and returns the arithmetic mean of the data. np.mean(arr) median()- takes a NumPy array as an argument and returns the median of the data. np.median(arr) The following example illustrates the usage of the mean() and median() methods. Example: Python3 import numpy as np arr = np.array([4, 5, 8, 5, 6, 4, 9, 2, 4, 3, 6]) # measures of central tendencymean = np.mean(arr)median = np.median(arr) print("Array =", arr)print("Mean =", mean)print("Median =", median) Output: Array = [4 5 8 5 6 4 9 2 4 3 6] Mean = 5.09090909091 Median = 5.0 The following methods are used to find measures of dispersion in NumPy: amin()- it takes a NumPy array as an argument and returns the minimum. np.amin(arr) amax()- it takes a NumPy array as an argument and returns maximum. np.amax(arr) ptp()- it takes a NumPy array as an argument and returns the range of the data. np.ptp(arr) var()- it takes a NumPy array as an argument and returns the variance of the data. np.var(arr) std()- it takes a NumPy array as an argument and returns the standard variation of the data. np.std(arr) Example: The following code illustrates amin(), amax(), ptp(), var() and std() methods. Python3 import numpy as np arr = np.array([4, 5, 8, 5, 6, 4, 9, 2, 4, 3, 6]) # measures of dispersionmin = np.amin(arr)max = np.amax(arr)range = np.ptp(arr)variance = np.var(arr)sd = np.std(arr) print("Array =", arr)print("Measures of Dispersion")print("Minimum =", min)print("Maximum =", max)print("Range =", range)print("Variance =", variance)print("Standard Deviation =", sd) Output: Array = [4 5 8 5 6 4 9 2 4 3 6] Measures of Dispersion Minimum = 2 Maximum = 9 Range = 7 Variance = 3.90082644628 Standard Deviation = 1.9750509984 Example: Now we can combine the above-mentioned examples to get a complete descriptive analysis of our array. Python3 import numpy as np arr = np.array([4, 5, 8, 5, 6, 4, 9, 2, 4, 3, 6]) # measures of central tendencymean = np.mean(arr)median = np.median(arr) # measures of dispersionmin = np.amin(arr)max = np.amax(arr)range = np.ptp(arr)variance = np.var(arr)sd = np.std(arr) print("Descriptive analysis")print("Array =", arr)print("Measures of Central Tendency")print("Mean =", mean)print("Median =", median)print("Measures of Dispersion")print("Minimum =", min)print("Maximum =", max)print("Range =", range)print("Variance =", variance)print("Standard Deviation =", sd) Output: Descriptive analysis Array = [4 5 8 5 6 4 9 2 4 3 6] Measurements of Central Tendency Mean = 5.09090909091 Median = 5.0 Minimum = 2 Maximum = 9 Range = 7 Variance = 3.90082644628 Standard Deviation = 1.9750509984 sagar0719kumar Python numpy-Statistics Functions Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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 Defaultdict in Python Python | os.path.join() method Python | Get unique values from a list Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n02 Sep, 2021" }, { "code": null, "e": 24633, "s": 24292, "text": "NumPy is a Python library used for numerical computing. It offers robust multidimensional arrays as a Python object along with a variety of mathematical functions. In this article, we will go through all the essential NumPy functions used in the descriptive analysis of an array. Let’s start by initializing a sample array for our analysis." }, { "code": null, "e": 24679, "s": 24633, "text": "The following code initializes a NumPy array:" }, { "code": null, "e": 24687, "s": 24679, "text": "Python3" }, { "code": "import numpy as np # sample arrayarr = np.array([4, 5, 8, 5, 6, 4, 9, 2, 4, 3, 6])print(arr)", "e": 24796, "s": 24687, "text": null }, { "code": null, "e": 24805, "s": 24796, "text": "Output: " }, { "code": null, "e": 24829, "s": 24805, "text": "[4 5 8 5 6 4 9 2 4 3 6]" }, { "code": null, "e": 24908, "s": 24829, "text": "In order to describe our NumPy array, we need to find two types of statistics:" }, { "code": null, "e": 24938, "s": 24908, "text": "Measures of central tendency." }, { "code": null, "e": 24962, "s": 24938, "text": "Measures of dispersion." }, { "code": null, "e": 25040, "s": 24962, "text": "The following methods are used to find measures of central tendency in NumPy:" }, { "code": null, "e": 25128, "s": 25040, "text": "mean()- takes a NumPy array as an argument and returns the arithmetic mean of the data." }, { "code": null, "e": 25141, "s": 25128, "text": "np.mean(arr)" }, { "code": null, "e": 25222, "s": 25141, "text": "median()- takes a NumPy array as an argument and returns the median of the data." }, { "code": null, "e": 25238, "s": 25222, "text": " np.median(arr)" }, { "code": null, "e": 25318, "s": 25238, "text": "The following example illustrates the usage of the mean() and median() methods." }, { "code": null, "e": 25327, "s": 25318, "text": "Example:" }, { "code": null, "e": 25335, "s": 25327, "text": "Python3" }, { "code": "import numpy as np arr = np.array([4, 5, 8, 5, 6, 4, 9, 2, 4, 3, 6]) # measures of central tendencymean = np.mean(arr)median = np.median(arr) print(\"Array =\", arr)print(\"Mean =\", mean)print(\"Median =\", median)", "e": 25564, "s": 25335, "text": null }, { "code": null, "e": 25573, "s": 25564, "text": "Output: " }, { "code": null, "e": 25639, "s": 25573, "text": "Array = [4 5 8 5 6 4 9 2 4 3 6]\nMean = 5.09090909091\nMedian = 5.0" }, { "code": null, "e": 25712, "s": 25639, "text": "The following methods are used to find measures of dispersion in NumPy: " }, { "code": null, "e": 25783, "s": 25712, "text": "amin()- it takes a NumPy array as an argument and returns the minimum." }, { "code": null, "e": 25796, "s": 25783, "text": "np.amin(arr)" }, { "code": null, "e": 25863, "s": 25796, "text": "amax()- it takes a NumPy array as an argument and returns maximum." }, { "code": null, "e": 25876, "s": 25863, "text": "np.amax(arr)" }, { "code": null, "e": 25956, "s": 25876, "text": "ptp()- it takes a NumPy array as an argument and returns the range of the data." }, { "code": null, "e": 25968, "s": 25956, "text": "np.ptp(arr)" }, { "code": null, "e": 26051, "s": 25968, "text": "var()- it takes a NumPy array as an argument and returns the variance of the data." }, { "code": null, "e": 26063, "s": 26051, "text": "np.var(arr)" }, { "code": null, "e": 26156, "s": 26063, "text": "std()- it takes a NumPy array as an argument and returns the standard variation of the data." }, { "code": null, "e": 26168, "s": 26156, "text": "np.std(arr)" }, { "code": null, "e": 26257, "s": 26168, "text": "Example: The following code illustrates amin(), amax(), ptp(), var() and std() methods. " }, { "code": null, "e": 26265, "s": 26257, "text": "Python3" }, { "code": "import numpy as np arr = np.array([4, 5, 8, 5, 6, 4, 9, 2, 4, 3, 6]) # measures of dispersionmin = np.amin(arr)max = np.amax(arr)range = np.ptp(arr)variance = np.var(arr)sd = np.std(arr) print(\"Array =\", arr)print(\"Measures of Dispersion\")print(\"Minimum =\", min)print(\"Maximum =\", max)print(\"Range =\", range)print(\"Variance =\", variance)print(\"Standard Deviation =\", sd)", "e": 26652, "s": 26265, "text": null }, { "code": null, "e": 26660, "s": 26652, "text": "Output:" }, { "code": null, "e": 26808, "s": 26660, "text": "Array = [4 5 8 5 6 4 9 2 4 3 6]\nMeasures of Dispersion\nMinimum = 2\nMaximum = 9\nRange = 7\nVariance = 3.90082644628\nStandard Deviation = 1.9750509984" }, { "code": null, "e": 26918, "s": 26808, "text": "Example: Now we can combine the above-mentioned examples to get a complete descriptive analysis of our array." }, { "code": null, "e": 26926, "s": 26918, "text": "Python3" }, { "code": "import numpy as np arr = np.array([4, 5, 8, 5, 6, 4, 9, 2, 4, 3, 6]) # measures of central tendencymean = np.mean(arr)median = np.median(arr) # measures of dispersionmin = np.amin(arr)max = np.amax(arr)range = np.ptp(arr)variance = np.var(arr)sd = np.std(arr) print(\"Descriptive analysis\")print(\"Array =\", arr)print(\"Measures of Central Tendency\")print(\"Mean =\", mean)print(\"Median =\", median)print(\"Measures of Dispersion\")print(\"Minimum =\", min)print(\"Maximum =\", max)print(\"Range =\", range)print(\"Variance =\", variance)print(\"Standard Deviation =\", sd)", "e": 27502, "s": 26926, "text": null }, { "code": null, "e": 27510, "s": 27502, "text": "Output:" }, { "code": null, "e": 27723, "s": 27510, "text": "Descriptive analysis\nArray = [4 5 8 5 6 4 9 2 4 3 6]\nMeasurements of Central Tendency\nMean = 5.09090909091\nMedian = 5.0\nMinimum = 2\nMaximum = 9\nRange = 7\nVariance = 3.90082644628\nStandard Deviation = 1.9750509984" }, { "code": null, "e": 27738, "s": 27723, "text": "sagar0719kumar" }, { "code": null, "e": 27772, "s": 27738, "text": "Python numpy-Statistics Functions" }, { "code": null, "e": 27785, "s": 27772, "text": "Python-numpy" }, { "code": null, "e": 27792, "s": 27785, "text": "Python" }, { "code": null, "e": 27890, "s": 27792, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27922, "s": 27890, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27978, "s": 27922, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28020, "s": 27978, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28062, "s": 28020, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28084, "s": 28062, "text": "Defaultdict in Python" }, { "code": null, "e": 28115, "s": 28084, "text": "Python | os.path.join() method" }, { "code": null, "e": 28154, "s": 28115, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28209, "s": 28154, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28238, "s": 28209, "text": "Create a directory in Python" } ]
Sort an array of strings lexicographically based on prefix
31 Aug, 2021 Given an array of strings arr[] of size N, the task is to sort the array of strings in lexicographical order and if while sorting for any two string A and string B, if string A is prefix of string B then string B should come in the sorted order. Examples: Input: arr[] = {“sun”, “moon”, “mock”} Output: mock moon sun Explanation: The lexicographical sorting is mock, moon, and sun. Input: arr[] = {“geeks”, “geeksfor”, “geeksforgeeks”} Output: geeksforgeeks geeksfor geeks Approach: The idea is to sort the given array of strings using the inbuilt sort function using the below comparator function. The comparator function used to check if any string occurs as a substring in another string using compare() function in C++ then, it should arrange them in decreasing order of their length. C++ bool my_compare(string a, string b){ // If any string is a substring then // return the size with greater length if (a.compare(0, b.size(), b) == 0 || b.compare(0, a.size(), a) == 0) return a.size() & gt; b.size(); // Else return lexicographically // smallest string else return a & lt; b;} Below is the implementation of the above approach: C++ // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to print the vectorvoid Print(vector<string> v){ for (auto i : v) cout << i << endl;} // Comparator function to sort the// array of string wrt given conditionsbool my_compare(string a, string b){ // Check if a string is present as // prefix in another string, then // compare the size of the string // and return the larger size if (a.compare(0, b.size(), b) == 0 || b.compare(0, a.size(), a) == 0) return a.size() > b.size(); // Else return lexicographically // smallest string else return a < b;} // Driver Codeint main(){ // GIven vector of strings vector<string> v = { "batman", "bat", "apple" }; // Calling Sort STL with my_compare // function passed as third parameter sort(v.begin(), v.end(), my_compare); // Function call to print the vector Print(v); return 0;} apple batman bat Time Complexity: O(N*log N)Auxiliary Space: O(1) shashanksdev lexicographic-ordering prefix Arrays Sorting Strings Arrays Strings Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n31 Aug, 2021" }, { "code": null, "e": 298, "s": 52, "text": "Given an array of strings arr[] of size N, the task is to sort the array of strings in lexicographical order and if while sorting for any two string A and string B, if string A is prefix of string B then string B should come in the sorted order." }, { "code": null, "e": 308, "s": 298, "text": "Examples:" }, { "code": null, "e": 434, "s": 308, "text": "Input: arr[] = {“sun”, “moon”, “mock”} Output: mock moon sun Explanation: The lexicographical sorting is mock, moon, and sun." }, { "code": null, "e": 527, "s": 434, "text": "Input: arr[] = {“geeks”, “geeksfor”, “geeksforgeeks”} Output: geeksforgeeks geeksfor geeks " }, { "code": null, "e": 843, "s": 527, "text": "Approach: The idea is to sort the given array of strings using the inbuilt sort function using the below comparator function. The comparator function used to check if any string occurs as a substring in another string using compare() function in C++ then, it should arrange them in decreasing order of their length." }, { "code": null, "e": 847, "s": 843, "text": "C++" }, { "code": "bool my_compare(string a, string b){ // If any string is a substring then // return the size with greater length if (a.compare(0, b.size(), b) == 0 || b.compare(0, a.size(), a) == 0) return a.size() & gt; b.size(); // Else return lexicographically // smallest string else return a & lt; b;}", "e": 1177, "s": 847, "text": null }, { "code": null, "e": 1228, "s": 1177, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1232, "s": 1228, "text": "C++" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to print the vectorvoid Print(vector<string> v){ for (auto i : v) cout << i << endl;} // Comparator function to sort the// array of string wrt given conditionsbool my_compare(string a, string b){ // Check if a string is present as // prefix in another string, then // compare the size of the string // and return the larger size if (a.compare(0, b.size(), b) == 0 || b.compare(0, a.size(), a) == 0) return a.size() > b.size(); // Else return lexicographically // smallest string else return a < b;} // Driver Codeint main(){ // GIven vector of strings vector<string> v = { \"batman\", \"bat\", \"apple\" }; // Calling Sort STL with my_compare // function passed as third parameter sort(v.begin(), v.end(), my_compare); // Function call to print the vector Print(v); return 0;}", "e": 2181, "s": 1232, "text": null }, { "code": null, "e": 2198, "s": 2181, "text": "apple\nbatman\nbat" }, { "code": null, "e": 2249, "s": 2200, "text": "Time Complexity: O(N*log N)Auxiliary Space: O(1)" }, { "code": null, "e": 2264, "s": 2251, "text": "shashanksdev" }, { "code": null, "e": 2287, "s": 2264, "text": "lexicographic-ordering" }, { "code": null, "e": 2294, "s": 2287, "text": "prefix" }, { "code": null, "e": 2301, "s": 2294, "text": "Arrays" }, { "code": null, "e": 2309, "s": 2301, "text": "Sorting" }, { "code": null, "e": 2317, "s": 2309, "text": "Strings" }, { "code": null, "e": 2324, "s": 2317, "text": "Arrays" }, { "code": null, "e": 2332, "s": 2324, "text": "Strings" }, { "code": null, "e": 2340, "s": 2332, "text": "Sorting" } ]
Python | Set 4 (Dictionary, Keywords in Python)
27 May, 2022 In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary. (Before python 3.7 dictionary used to be unordered meant key-value pairs are not stored in the order they are inputted into the dictionary but from python 3.7 they are stored in order like the first element will be stored in the first position and the last at the last position.) Python3 # Create a new dictionaryd = dict() # or d = {} # Add a key - value pairs to dictionaryd['xyz'] = 123d['abc'] = 345 # print the whole dictionaryprint (d) # print only the keysprint (d.keys()) # print only valuesprint (d.values()) # iterate over dictionaryfor i in d : print ("%s %d" %(i, d[i])) # another method of iterationfor index, key in enumerate(d): print (index, key, d[key]) # check if key existprint ('xyz' in d) # delete the key-value pairdel d['xyz'] # check againprint ("xyz" in d) Output: {'xyz': 123, 'abc': 345} ['xyz', 'abc'] [123, 345] xyz 123 abc 345 0 xyz 123 1 abc 345 True False break: takes you out of the current loop. continue: ends the current iteration in the loop and moves to the next iteration. pass: The pass statement does nothing. It can be used when a statement is required. syntactically but the program requires no action. It is commonly used for creating minimal classes. Python3 # Function to illustrate break in loopdef breakTest(arr): for i in arr: if i == 5: break print (i) # For new line print("") # Function to illustrate continue in loopdef continueTest(arr): for i in arr: if i == 5: continue print (i) # For new line print("") # Function to illustrate passdef passTest(arr): pass # Driver program to test above functions # Array to be used for above functions:arr = [1, 3 , 4, 5, 6 , 7] # Illustrate breakprint ("Break method output")breakTest(arr) # Illustrate continueprint ("Continue method output")continueTest(arr) # Illustrate pass- Does nothingpassTest(arr) Output: Break method output 1 3 4 Continue method output 1 3 4 6 7 map: The map() function applies a function to every member of iterable and returns the result. If there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables. filter: It takes a function returning True or False and applies it to a sequence, returning a list of only those members of the sequence for which the function returned True. lambda: Python provides the ability to create a simple (no statements allowed internally) anonymous inline function called lambda function. Using lambda and map you can have two for loops in one line. Python3 # python program to test map, filter and lambdaitems = [1, 2, 3, 4, 5] #Using map function to map the lambda operation on itemscubes = list(map(lambda x: x**3, items))print(cubes) # first parentheses contains a lambda form, that is # a squaring function and second parentheses represents# calling lambdaprint( (lambda x: x**2)(5)) # Make function of two arguments that return their productprint ((lambda x, y: x*y)(3, 4)) #Using filter function to filter all# numbers less than 5 from a listnumber_list = range(-10, 10)less_than_five = list(filter(lambda x: x < 5, number_list))print(less_than_five) Output: [1, 8, 27, 64, 125] 25 12 [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4] For more clarity about map, filter, and lambda, you can have a look at the below example: Python3 # code without using map, filter and lambda # Find the number which are odd in the list# and multiply them by 5 and create a new list # Declare a new listx = [2, 3, 4, 5, 6] # Empty list for answery = [] # Perform the operations and print the answerfor v in x: if v % 2: y += [v*5]print(y) Output: [15, 25] The same operation can be performed in two lines using map, filter, and lambda as : Python3 # above code with map, filter and lambda # Declare a listx = [2, 3, 4, 5, 6] # Perform the same operation as in above posty = list(map(lambda v: v * 5, filter(lambda u: u % 2, x)))print(y) Output: [15, 25] https://www.youtube.com/watch?v=z7z_e5-l2yE This article is contributed by Nikhil Kumar Singh. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. guddu9211 RajuKumar19 arorakashish0911 vikx4915 jhav365 python-dict Python School Programming python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n27 May, 2022" }, { "code": null, "e": 216, "s": 54, "text": "In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python." }, { "code": null, "e": 662, "s": 216, "text": "In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary. (Before python 3.7 dictionary used to be unordered meant key-value pairs are not stored in the order they are inputted into the dictionary but from python 3.7 they are stored in order like the first element will be stored in the first position and the last at the last position.)" }, { "code": null, "e": 670, "s": 662, "text": "Python3" }, { "code": "# Create a new dictionaryd = dict() # or d = {} # Add a key - value pairs to dictionaryd['xyz'] = 123d['abc'] = 345 # print the whole dictionaryprint (d) # print only the keysprint (d.keys()) # print only valuesprint (d.values()) # iterate over dictionaryfor i in d : print (\"%s %d\" %(i, d[i])) # another method of iterationfor index, key in enumerate(d): print (index, key, d[key]) # check if key existprint ('xyz' in d) # delete the key-value pairdel d['xyz'] # check againprint (\"xyz\" in d)", "e": 1171, "s": 670, "text": null }, { "code": null, "e": 1180, "s": 1171, "text": "Output: " }, { "code": null, "e": 1278, "s": 1180, "text": "{'xyz': 123, 'abc': 345}\n['xyz', 'abc']\n[123, 345]\nxyz 123\nabc 345\n0 xyz 123\n1 abc 345\nTrue\nFalse" }, { "code": null, "e": 1320, "s": 1278, "text": "break: takes you out of the current loop." }, { "code": null, "e": 1403, "s": 1320, "text": "continue: ends the current iteration in the loop and moves to the next iteration." }, { "code": null, "e": 1537, "s": 1403, "text": "pass: The pass statement does nothing. It can be used when a statement is required. syntactically but the program requires no action." }, { "code": null, "e": 1587, "s": 1537, "text": "It is commonly used for creating minimal classes." }, { "code": null, "e": 1595, "s": 1587, "text": "Python3" }, { "code": "# Function to illustrate break in loopdef breakTest(arr): for i in arr: if i == 5: break print (i) # For new line print(\"\") # Function to illustrate continue in loopdef continueTest(arr): for i in arr: if i == 5: continue print (i) # For new line print(\"\") # Function to illustrate passdef passTest(arr): pass # Driver program to test above functions # Array to be used for above functions:arr = [1, 3 , 4, 5, 6 , 7] # Illustrate breakprint (\"Break method output\")breakTest(arr) # Illustrate continueprint (\"Continue method output\")continueTest(arr) # Illustrate pass- Does nothingpassTest(arr)", "e": 2271, "s": 1595, "text": null }, { "code": null, "e": 2280, "s": 2271, "text": "Output: " }, { "code": null, "e": 2339, "s": 2280, "text": "Break method output\n1 3 4\nContinue method output\n1 3 4 6 7" }, { "code": null, "e": 2564, "s": 2339, "text": "map: The map() function applies a function to every member of iterable and returns the result. If there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables." }, { "code": null, "e": 2740, "s": 2564, "text": "filter: It takes a function returning True or False and applies it to a sequence, returning a list of only those members of the sequence for which the function returned True." }, { "code": null, "e": 2941, "s": 2740, "text": "lambda: Python provides the ability to create a simple (no statements allowed internally) anonymous inline function called lambda function. Using lambda and map you can have two for loops in one line." }, { "code": null, "e": 2949, "s": 2941, "text": "Python3" }, { "code": "# python program to test map, filter and lambdaitems = [1, 2, 3, 4, 5] #Using map function to map the lambda operation on itemscubes = list(map(lambda x: x**3, items))print(cubes) # first parentheses contains a lambda form, that is # a squaring function and second parentheses represents# calling lambdaprint( (lambda x: x**2)(5)) # Make function of two arguments that return their productprint ((lambda x, y: x*y)(3, 4)) #Using filter function to filter all# numbers less than 5 from a listnumber_list = range(-10, 10)less_than_five = list(filter(lambda x: x < 5, number_list))print(less_than_five)", "e": 3549, "s": 2949, "text": null }, { "code": null, "e": 3557, "s": 3549, "text": "Output:" }, { "code": null, "e": 3640, "s": 3557, "text": "[1, 8, 27, 64, 125]\n25\n12\n[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4]" }, { "code": null, "e": 3731, "s": 3640, "text": "For more clarity about map, filter, and lambda, you can have a look at the below example: " }, { "code": null, "e": 3739, "s": 3731, "text": "Python3" }, { "code": "# code without using map, filter and lambda # Find the number which are odd in the list# and multiply them by 5 and create a new list # Declare a new listx = [2, 3, 4, 5, 6] # Empty list for answery = [] # Perform the operations and print the answerfor v in x: if v % 2: y += [v*5]print(y)", "e": 4039, "s": 3739, "text": null }, { "code": null, "e": 4048, "s": 4039, "text": "Output: " }, { "code": null, "e": 4057, "s": 4048, "text": "[15, 25]" }, { "code": null, "e": 4142, "s": 4057, "text": "The same operation can be performed in two lines using map, filter, and lambda as : " }, { "code": null, "e": 4150, "s": 4142, "text": "Python3" }, { "code": "# above code with map, filter and lambda # Declare a listx = [2, 3, 4, 5, 6] # Perform the same operation as in above posty = list(map(lambda v: v * 5, filter(lambda u: u % 2, x)))print(y)", "e": 4340, "s": 4150, "text": null }, { "code": null, "e": 4348, "s": 4340, "text": "Output:" }, { "code": null, "e": 4357, "s": 4348, "text": "[15, 25]" }, { "code": null, "e": 4401, "s": 4357, "text": "https://www.youtube.com/watch?v=z7z_e5-l2yE" }, { "code": null, "e": 4580, "s": 4401, "text": "This article is contributed by Nikhil Kumar Singh. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above." }, { "code": null, "e": 4590, "s": 4580, "text": "guddu9211" }, { "code": null, "e": 4602, "s": 4590, "text": "RajuKumar19" }, { "code": null, "e": 4619, "s": 4602, "text": "arorakashish0911" }, { "code": null, "e": 4628, "s": 4619, "text": "vikx4915" }, { "code": null, "e": 4636, "s": 4628, "text": "jhav365" }, { "code": null, "e": 4648, "s": 4636, "text": "python-dict" }, { "code": null, "e": 4655, "s": 4648, "text": "Python" }, { "code": null, "e": 4674, "s": 4655, "text": "School Programming" }, { "code": null, "e": 4686, "s": 4674, "text": "python-dict" } ]
How to set state with a dynamic key name in ReactJS ?
27 Oct, 2021 React.js introduces the concept of state. The states are used to store data for specific components. These states can be updated accordingly using setState function. Updation of state leads to rerendering of UI. You can assign meaningful names to states. There can be a requirement to create a state with a dynamic key name. We can do this in React. Let us create a React project and then we will create a state with a dynamic key name. Creating React Project: Step 1: Create a react application by typing the following command in the terminal. npx create-react-app project_name Step 2: Now, go to the project folder i.e project_name by running the following command. cd project_name Project Structure: It will look like the following: Project Structure Example: Let us create an input field that takes the state name as input and state value as another input. Now a button is added which has an onclick function. It creates the state with a dynamic key name enclosing value inside this ‘[ ]’ on a user click. Users can click on the button to create a new state and it will display the newly created state in the UI. Filename: App.js Javascript import React, { Component } from "react"; class App extends Component { constructor() { super(); this.state = { name: "", value: " ", }; } render() { return ( <div> <p>Enter State Name:</p> <input onChange={(e) => { this.setState({ name: e.target.value }); }} type="text" ></input> <p>Enter State Value:</p> <input onChange={(e) => { this.setState({ value: e.target.value }); }} type="text" ></input> <br /> <br /> <button onClick={() => { this.setState({ [this.state.name]: this.state.value, }); }} > Create a dynamic state </button> {this.state[this.state.name] ? ( <p> {this.state.name}:{this.state[this.state.name]} </p> ) : null} </div> ); }} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Open your browser. It will by default open a tab with localhost running and you can see the output shown in the image. Fill in the required details and click on the button. As you can see in the output new state with a dynamic name is created with the value you entered.UI checks if the state exists and then displays the value. Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Oct, 2021" }, { "code": null, "e": 403, "s": 52, "text": "React.js introduces the concept of state. The states are used to store data for specific components. These states can be updated accordingly using setState function. Updation of state leads to rerendering of UI. You can assign meaningful names to states. There can be a requirement to create a state with a dynamic key name. We can do this in React. " }, { "code": null, "e": 491, "s": 403, "text": "Let us create a React project and then we will create a state with a dynamic key name. " }, { "code": null, "e": 515, "s": 491, "text": "Creating React Project:" }, { "code": null, "e": 599, "s": 515, "text": "Step 1: Create a react application by typing the following command in the terminal." }, { "code": null, "e": 633, "s": 599, "text": "npx create-react-app project_name" }, { "code": null, "e": 724, "s": 635, "text": "Step 2: Now, go to the project folder i.e project_name by running the following command." }, { "code": null, "e": 740, "s": 724, "text": "cd project_name" }, { "code": null, "e": 792, "s": 740, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 810, "s": 792, "text": "Project Structure" }, { "code": null, "e": 1175, "s": 810, "text": "Example: Let us create an input field that takes the state name as input and state value as another input. Now a button is added which has an onclick function. It creates the state with a dynamic key name enclosing value inside this ‘[ ]’ on a user click. Users can click on the button to create a new state and it will display the newly created state in the UI. " }, { "code": null, "e": 1192, "s": 1175, "text": "Filename: App.js" }, { "code": null, "e": 1203, "s": 1192, "text": "Javascript" }, { "code": "import React, { Component } from \"react\"; class App extends Component { constructor() { super(); this.state = { name: \"\", value: \" \", }; } render() { return ( <div> <p>Enter State Name:</p> <input onChange={(e) => { this.setState({ name: e.target.value }); }} type=\"text\" ></input> <p>Enter State Value:</p> <input onChange={(e) => { this.setState({ value: e.target.value }); }} type=\"text\" ></input> <br /> <br /> <button onClick={() => { this.setState({ [this.state.name]: this.state.value, }); }} > Create a dynamic state </button> {this.state[this.state.name] ? ( <p> {this.state.name}:{this.state[this.state.name]} </p> ) : null} </div> ); }} export default App;", "e": 2172, "s": 1203, "text": null }, { "code": null, "e": 2285, "s": 2172, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2295, "s": 2285, "text": "npm start" }, { "code": null, "e": 2632, "s": 2295, "text": "Output: Open your browser. It will by default open a tab with localhost running and you can see the output shown in the image. Fill in the required details and click on the button. As you can see in the output new state with a dynamic name is created with the value you entered.UI checks if the state exists and then displays the value." }, { "code": null, "e": 2639, "s": 2632, "text": "Picked" }, { "code": null, "e": 2655, "s": 2639, "text": "React-Questions" }, { "code": null, "e": 2663, "s": 2655, "text": "ReactJS" }, { "code": null, "e": 2680, "s": 2663, "text": "Web Technologies" } ]
PHP | date_diff() Function
12 Feb, 2019 The date_diff() is an inbuilt function in PHP which is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns FALSE on failure. Syntax: date_diff($datetime1, $datetime2); Parameters: The date_diff() function accepts two parameters as mentioned above and described below: $datetime1: It is a mandatory parameter which specifies the first DateTime object. $datetime2: It is a mandatory parameter which specifies the second DateTime object. Return Value: It returns the difference between two DateTime objects otherwise, FALSE on failure. Below programs illustrate the date_diff() function:Program 1: <?php// PHP program to illustrate // date_diff() function // creates DateTime objects$datetime1 = date_create('2017-06-28');$datetime2 = date_create('2018-06-28'); // calculates the difference between DateTime objects$interval = date_diff($datetime1, $datetime2); // printing result in days formatecho $interval->format('%R%a days');?> +365 days Program 2: <?php// PHP program to illustrate // date_diff() function // difference only in year$datetime1 = date_create('2017-06-28');$datetime2 = date_create('2018-06-28'); $interval = date_diff($datetime1, $datetime2);echo $interval->format('%R%a days') . "\n"; // Difference only in months$datetime1 = date_create('2018-04-28');$datetime2 = date_create('2018-06-28'); $interval = date_diff($datetime1, $datetime2);echo $interval->format('%R%a days') . "\n"; // Difference in year, month, days$datetime1 = date_create('2017-06-28');$datetime2 = date_create('2018-04-05'); $interval = date_diff($datetime1, $datetime2);echo $interval->format('%R%a days') . "\n"; ?> +365 days +61 days +281 days Reference:http://php.net/manual/en/function.date-diff.php AndroGarcia PHP-date-time PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Feb, 2019" }, { "code": null, "e": 224, "s": 28, "text": "The date_diff() is an inbuilt function in PHP which is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns FALSE on failure." }, { "code": null, "e": 232, "s": 224, "text": "Syntax:" }, { "code": null, "e": 268, "s": 232, "text": "date_diff($datetime1, $datetime2);\n" }, { "code": null, "e": 368, "s": 268, "text": "Parameters: The date_diff() function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 451, "s": 368, "text": "$datetime1: It is a mandatory parameter which specifies the first DateTime object." }, { "code": null, "e": 535, "s": 451, "text": "$datetime2: It is a mandatory parameter which specifies the second DateTime object." }, { "code": null, "e": 633, "s": 535, "text": "Return Value: It returns the difference between two DateTime objects otherwise, FALSE on failure." }, { "code": null, "e": 695, "s": 633, "text": "Below programs illustrate the date_diff() function:Program 1:" }, { "code": "<?php// PHP program to illustrate // date_diff() function // creates DateTime objects$datetime1 = date_create('2017-06-28');$datetime2 = date_create('2018-06-28'); // calculates the difference between DateTime objects$interval = date_diff($datetime1, $datetime2); // printing result in days formatecho $interval->format('%R%a days');?>", "e": 1034, "s": 695, "text": null }, { "code": null, "e": 1045, "s": 1034, "text": "+365 days\n" }, { "code": null, "e": 1056, "s": 1045, "text": "Program 2:" }, { "code": "<?php// PHP program to illustrate // date_diff() function // difference only in year$datetime1 = date_create('2017-06-28');$datetime2 = date_create('2018-06-28'); $interval = date_diff($datetime1, $datetime2);echo $interval->format('%R%a days') . \"\\n\"; // Difference only in months$datetime1 = date_create('2018-04-28');$datetime2 = date_create('2018-06-28'); $interval = date_diff($datetime1, $datetime2);echo $interval->format('%R%a days') . \"\\n\"; // Difference in year, month, days$datetime1 = date_create('2017-06-28');$datetime2 = date_create('2018-04-05'); $interval = date_diff($datetime1, $datetime2);echo $interval->format('%R%a days') . \"\\n\"; ?>", "e": 1720, "s": 1056, "text": null }, { "code": null, "e": 1750, "s": 1720, "text": "+365 days\n+61 days\n+281 days\n" }, { "code": null, "e": 1808, "s": 1750, "text": "Reference:http://php.net/manual/en/function.date-diff.php" }, { "code": null, "e": 1820, "s": 1808, "text": "AndroGarcia" }, { "code": null, "e": 1834, "s": 1820, "text": "PHP-date-time" }, { "code": null, "e": 1847, "s": 1834, "text": "PHP-function" }, { "code": null, "e": 1851, "s": 1847, "text": "PHP" }, { "code": null, "e": 1868, "s": 1851, "text": "Web Technologies" }, { "code": null, "e": 1872, "s": 1868, "text": "PHP" } ]
Path relativize() method in Java with Examples
20 Jun, 2022 The relativize(Path other) method of java.nio.file.Path used to create a relative path between this path and a given path as a parameter. Relativization is the inverse of resolution. This method creates a relative path that when resolved against this path object, yields a path that helps us to locate the same file as the given path. For example, if this path is “/dir1/dir2” and the given path as a parameter is “/dir1/dir2/dir3/file1” then this method will construct a relative path “dir3/file1”. Where this path and the given path do not have a root component, then a relative path can be constructed. If anyone of the paths has a root component then the relative path cannot be constructed. When both paths have a root component then it is implementation-dependent if a relative path can be constructed. If this path and the given path are equal then an empty path is returned. Syntax: Path relativize(Path other) Parameters: This method accepts a one parameter other which is the path to relativize against this path. Return value: This method returns the resulting relative path, or an empty path if both paths are equal. Exception: This method throws IllegalArgumentException if other is not a Path that can be relativized against this path. Below programs illustrate relativize() method: Program 1: Java // Java program to demonstrate// java.nio.file.Path.relativize() method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create objects of Path Path path = Paths.get("D:\\eclipse\\p2" + "\\org\\eclipse"); Path passedPath = Paths.get("D:\\eclipse\\p2" + "\\org\\eclipse\\equinox\\p2\\core" + "\\cache\\binary"); // print paths System.out.println("This Path:" + path); System.out.println("Given Path:" + passedPath); // call relativize() to create // a relative path Path relativize = path.relativize(passedPath); // print result System.out.println("Relative Path: " + relativize); }} Program 2: Java // Java program to demonstrate// java.nio.file.Path.relativize() method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create objects of Path Path path = Paths.get("\\nEclipseWork"); Path passedPath = Paths.get("\\nEclipseWork\\GFG" + "\\bin\\defaultpackage"); // print paths System.out.println("This Path:" + path); System.out.println("Given Path:" + passedPath); // call relativize() // to create a relative path Path relativize = path.relativize(passedPath); // print result System.out.println("Relative Path: " + relativize); }} References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#relativize(java.nio.file.Path) simmytarika5 Java-Functions Java-Path java.nio.file package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jun, 2022" }, { "code": null, "e": 912, "s": 28, "text": "The relativize(Path other) method of java.nio.file.Path used to create a relative path between this path and a given path as a parameter. Relativization is the inverse of resolution. This method creates a relative path that when resolved against this path object, yields a path that helps us to locate the same file as the given path. For example, if this path is “/dir1/dir2” and the given path as a parameter is “/dir1/dir2/dir3/file1” then this method will construct a relative path “dir3/file1”. Where this path and the given path do not have a root component, then a relative path can be constructed. If anyone of the paths has a root component then the relative path cannot be constructed. When both paths have a root component then it is implementation-dependent if a relative path can be constructed. If this path and the given path are equal then an empty path is returned. " }, { "code": null, "e": 920, "s": 912, "text": "Syntax:" }, { "code": null, "e": 948, "s": 920, "text": "Path relativize(Path other)" }, { "code": null, "e": 1054, "s": 948, "text": "Parameters: This method accepts a one parameter other which is the path to relativize against this path. " }, { "code": null, "e": 1160, "s": 1054, "text": "Return value: This method returns the resulting relative path, or an empty path if both paths are equal. " }, { "code": null, "e": 1282, "s": 1160, "text": "Exception: This method throws IllegalArgumentException if other is not a Path that can be relativized against this path. " }, { "code": null, "e": 1330, "s": 1282, "text": "Below programs illustrate relativize() method: " }, { "code": null, "e": 1342, "s": 1330, "text": "Program 1: " }, { "code": null, "e": 1347, "s": 1342, "text": "Java" }, { "code": "// Java program to demonstrate// java.nio.file.Path.relativize() method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create objects of Path Path path = Paths.get(\"D:\\\\eclipse\\\\p2\" + \"\\\\org\\\\eclipse\"); Path passedPath = Paths.get(\"D:\\\\eclipse\\\\p2\" + \"\\\\org\\\\eclipse\\\\equinox\\\\p2\\\\core\" + \"\\\\cache\\\\binary\"); // print paths System.out.println(\"This Path:\" + path); System.out.println(\"Given Path:\" + passedPath); // call relativize() to create // a relative path Path relativize = path.relativize(passedPath); // print result System.out.println(\"Relative Path: \" + relativize); }}", "e": 2267, "s": 1347, "text": null }, { "code": null, "e": 2279, "s": 2267, "text": "Program 2: " }, { "code": null, "e": 2284, "s": 2279, "text": "Java" }, { "code": "// Java program to demonstrate// java.nio.file.Path.relativize() method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create objects of Path Path path = Paths.get(\"\\\\nEclipseWork\"); Path passedPath = Paths.get(\"\\\\nEclipseWork\\\\GFG\" + \"\\\\bin\\\\defaultpackage\"); // print paths System.out.println(\"This Path:\" + path); System.out.println(\"Given Path:\" + passedPath); // call relativize() // to create a relative path Path relativize = path.relativize(passedPath); // print result System.out.println(\"Relative Path: \" + relativize); }}", "e": 3110, "s": 2284, "text": null }, { "code": null, "e": 3220, "s": 3110, "text": "References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#relativize(java.nio.file.Path)" }, { "code": null, "e": 3233, "s": 3220, "text": "simmytarika5" }, { "code": null, "e": 3248, "s": 3233, "text": "Java-Functions" }, { "code": null, "e": 3258, "s": 3248, "text": "Java-Path" }, { "code": null, "e": 3280, "s": 3258, "text": "java.nio.file package" }, { "code": null, "e": 3285, "s": 3280, "text": "Java" }, { "code": null, "e": 3290, "s": 3285, "text": "Java" } ]
How to Implement YoutubePlayerView Library in Android?
18 Feb, 2021 If you are looking to display YouTube videos inside your app without redirecting your user from your app to YouTube then this library is very helpful for you to use. With the help of this library, you can simply play videos from YouTube with the help of video id inside your app itself without redirecting your user to YouTube. Now we will see towards the implementation of this library in our Android App. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add jar file inside the libs folder in Android Studio Download the jar file from the link here. To add this file open your android project in “Project” mode as shown in the below image. Then go to Your Project Name > app > libs and right-click on it and paste the downloaded JAR files. You may also refer to the below image. Note: You may also refer to this article How to Import External JAR Files in Android Studio? Step 3: Now add the dependency in your build.gradle file To add this dependency. Navigate to your app’s name > app > and you will get to see build.gradle file. Inside that file add the dependency in the dependencies section. implementation ‘com.pierfrancescosoffritti.androidyoutubeplayer:core:10.0.3’ Now click on the “sync now” option which you will get to see in the top right corner after adding this library. After that, we are ready for integrating YouTube video player into the app. Step 4: Working with the activity_main.xml file Now change the project tab in the top left corner to Android. After that navigate to the app > res > layout > activity_main.xml. Inside this, we will create a simple button that will redirect to a new activity where we will play our YouTube video. Below is the XML code snippet for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Button which is used to navigate to video player screen--> <Button android:id="@+id/idBtnPlayVideo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Play Youtube Video" android:textColor="@color/white" /></RelativeLayout> Step 5: Create a new empty activity Now we will create a new activity where we will display our YouTube video player. To create a new activity navigate to the app > java > your app’s package name and right-click on it > New > Activity > Empty Activity > Give a name to your activity and make sure to keep its language as Java. Now your new activity has been created. (Here we have given the activity name as VideoPlayerActivity). Step 6: Implement YoutubePlayerView inside the new activity Below is the code for the activity_video_player.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".VideoPlayerActivity"> <!--Youtube Player view which will play our youtube video--> <com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView android:id="@+id/videoPlayer" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:showFullScreenButton="false"> </com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView> </androidx.constraintlayout.widget.ConstraintLayout> Step 7: Working with the VideoPlayerActivity.java file Before working with the VideoPlayerActivity.java file let’s have a look at how to get the video id of any YouTube video. Open YouTube and search for any video which you want to play inside your app. Play that video inside your browser. In the top section of your browser, there will be an address bar where you can get to see the URL for that video. For example, here we have taken the below URL. Inside the above URL, the video ID is present in the extreme left part i.e after the v = sign is your video id. In the above example, the video ID will be vG2PNdI8axo In this way, we can get URL for any video. Now go to the VideoPlayerActivity.java file and refer to the following code. Below is the code for the VideoPlayerActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.Window;import android.view.WindowManager; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.PlayerConstants;import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer;import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.AbstractYouTubePlayerListener;import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView; public class VideoPlayerActivity extends AppCompatActivity { // id of the video // which we are playing. String video_id = "vG2PNdI8axo"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // below two lines are used to set our // screen orientation in landscape mode. requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_video_player); // below line of code is // to hide our action bar. getSupportActionBar().hide(); // declaring variable for youtubeplayer view final YouTubePlayerView youTubePlayerView = findViewById(R.id.videoPlayer); // below line is to place your youtube player in a full screen mode (i.e landscape mode) youTubePlayerView.enterFullScreen(); youTubePlayerView.toggleFullScreen(); // here we are adding observer to our youtubeplayerview. getLifecycle().addObserver(youTubePlayerView); // below method will provides us the youtube player // ui controller such as to play and pause a video // to forward a video // and many more features. youTubePlayerView.getPlayerUiController(); // below line is to enter full screen mode. youTubePlayerView.enterFullScreen(); youTubePlayerView.toggleFullScreen(); // adding listener for our youtube player view. youTubePlayerView.addYouTubePlayerListener(new AbstractYouTubePlayerListener() { @Override public void onReady(@NonNull YouTubePlayer youTubePlayer) { // loading the selected video into the YouTube Player youTubePlayer.loadVideo(video_id, 0); } @Override public void onStateChange(@NonNull YouTubePlayer youTubePlayer, @NonNull PlayerConstants.PlayerState state) { // this method is called if video has ended, super.onStateChange(youTubePlayer, state); } }); }} Step 8: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // variable for our button Button playBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize our Button playBtn = findViewById(R.id.idBtnPlayVideo); // we have set onclick listener for our button playBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // we have declared an intent to open new activity. Intent i = new Intent(MainActivity.this, VideoPlayerActivity.class); startActivity(i); } }); }} Step 9: Add internet permission in the Manifest file Navigate to the app > AndroidManifest.xml file there you have to add the below permissions. <!–For internet usage–> <uses-permission android:name=”android.permission.INTERNET”/> <uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE”/> Along with this you will get to see activity section inside your application tag inside that add your video player’s activity screen orientation to landscape mode. <!–Here my activity name was VideoPlayerActivity–> <activity android:name=”.VideoPlayerActivity” android:screenOrientation=”landscape”> </activity> Below is the code for the complete AndroidManifest.xml file: XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.gtappdevelopers.youtubeplayerview"> <!--For internet usage--> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.YoutubePlayerView"> <!--Here my activity name was VideoPlayerActivity--> <activity android:name=".VideoPlayerActivity" android:screenOrientation="landscape"> </activity> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Check out the project on the below GitHub link: https://github.com/ChaitanyaMunje/YoutubePlayerView android Android-View Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Feb, 2021" }, { "code": null, "e": 538, "s": 52, "text": "If you are looking to display YouTube videos inside your app without redirecting your user from your app to YouTube then this library is very helpful for you to use. With the help of this library, you can simply play videos from YouTube with the help of video id inside your app itself without redirecting your user to YouTube. Now we will see towards the implementation of this library in our Android App. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 567, "s": 538, "text": "Step 1: Create a New Project" }, { "code": null, "e": 729, "s": 567, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 791, "s": 729, "text": "Step 2: Add jar file inside the libs folder in Android Studio" }, { "code": null, "e": 923, "s": 791, "text": "Download the jar file from the link here. To add this file open your android project in “Project” mode as shown in the below image." }, { "code": null, "e": 1063, "s": 923, "text": "Then go to Your Project Name > app > libs and right-click on it and paste the downloaded JAR files. You may also refer to the below image. " }, { "code": null, "e": 1156, "s": 1063, "text": "Note: You may also refer to this article How to Import External JAR Files in Android Studio?" }, { "code": null, "e": 1213, "s": 1156, "text": "Step 3: Now add the dependency in your build.gradle file" }, { "code": null, "e": 1382, "s": 1213, "text": "To add this dependency. Navigate to your app’s name > app > and you will get to see build.gradle file. Inside that file add the dependency in the dependencies section. " }, { "code": null, "e": 1459, "s": 1382, "text": "implementation ‘com.pierfrancescosoffritti.androidyoutubeplayer:core:10.0.3’" }, { "code": null, "e": 1648, "s": 1459, "text": "Now click on the “sync now” option which you will get to see in the top right corner after adding this library. After that, we are ready for integrating YouTube video player into the app. " }, { "code": null, "e": 1696, "s": 1648, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 2006, "s": 1696, "text": "Now change the project tab in the top left corner to Android. After that navigate to the app > res > layout > activity_main.xml. Inside this, we will create a simple button that will redirect to a new activity where we will play our YouTube video. Below is the XML code snippet for the activity_main.xml file." }, { "code": null, "e": 2010, "s": 2006, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Button which is used to navigate to video player screen--> <Button android:id=\"@+id/idBtnPlayVideo\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"Play Youtube Video\" android:textColor=\"@color/white\" /></RelativeLayout>", "e": 2649, "s": 2010, "text": null }, { "code": null, "e": 2685, "s": 2649, "text": "Step 5: Create a new empty activity" }, { "code": null, "e": 3080, "s": 2685, "text": "Now we will create a new activity where we will display our YouTube video player. To create a new activity navigate to the app > java > your app’s package name and right-click on it > New > Activity > Empty Activity > Give a name to your activity and make sure to keep its language as Java. Now your new activity has been created. (Here we have given the activity name as VideoPlayerActivity). " }, { "code": null, "e": 3141, "s": 3080, "text": "Step 6: Implement YoutubePlayerView inside the new activity " }, { "code": null, "e": 3199, "s": 3141, "text": "Below is the code for the activity_video_player.xml file." }, { "code": null, "e": 3203, "s": 3199, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".VideoPlayerActivity\"> <!--Youtube Player view which will play our youtube video--> <com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView android:id=\"@+id/videoPlayer\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:showFullScreenButton=\"false\"> </com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 4260, "s": 3203, "text": null }, { "code": null, "e": 4315, "s": 4260, "text": "Step 7: Working with the VideoPlayerActivity.java file" }, { "code": null, "e": 4712, "s": 4315, "text": "Before working with the VideoPlayerActivity.java file let’s have a look at how to get the video id of any YouTube video. Open YouTube and search for any video which you want to play inside your app. Play that video inside your browser. In the top section of your browser, there will be an address bar where you can get to see the URL for that video. For example, here we have taken the below URL." }, { "code": null, "e": 4868, "s": 4712, "text": "Inside the above URL, the video ID is present in the extreme left part i.e after the v = sign is your video id. In the above example, the video ID will be " }, { "code": null, "e": 4881, "s": 4868, "text": "vG2PNdI8axo " }, { "code": null, "e": 5132, "s": 4881, "text": "In this way, we can get URL for any video. Now go to the VideoPlayerActivity.java file and refer to the following code. Below is the code for the VideoPlayerActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 5137, "s": 5132, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.Window;import android.view.WindowManager; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.PlayerConstants;import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer;import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.AbstractYouTubePlayerListener;import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView; public class VideoPlayerActivity extends AppCompatActivity { // id of the video // which we are playing. String video_id = \"vG2PNdI8axo\"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // below two lines are used to set our // screen orientation in landscape mode. requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_video_player); // below line of code is // to hide our action bar. getSupportActionBar().hide(); // declaring variable for youtubeplayer view final YouTubePlayerView youTubePlayerView = findViewById(R.id.videoPlayer); // below line is to place your youtube player in a full screen mode (i.e landscape mode) youTubePlayerView.enterFullScreen(); youTubePlayerView.toggleFullScreen(); // here we are adding observer to our youtubeplayerview. getLifecycle().addObserver(youTubePlayerView); // below method will provides us the youtube player // ui controller such as to play and pause a video // to forward a video // and many more features. youTubePlayerView.getPlayerUiController(); // below line is to enter full screen mode. youTubePlayerView.enterFullScreen(); youTubePlayerView.toggleFullScreen(); // adding listener for our youtube player view. youTubePlayerView.addYouTubePlayerListener(new AbstractYouTubePlayerListener() { @Override public void onReady(@NonNull YouTubePlayer youTubePlayer) { // loading the selected video into the YouTube Player youTubePlayer.loadVideo(video_id, 0); } @Override public void onStateChange(@NonNull YouTubePlayer youTubePlayer, @NonNull PlayerConstants.PlayerState state) { // this method is called if video has ended, super.onStateChange(youTubePlayer, state); } }); }}", "e": 7972, "s": 5137, "text": null }, { "code": null, "e": 8020, "s": 7972, "text": "Step 8: Working with the MainActivity.java file" }, { "code": null, "e": 8210, "s": 8020, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 8215, "s": 8210, "text": "Java" }, { "code": "import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // variable for our button Button playBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize our Button playBtn = findViewById(R.id.idBtnPlayVideo); // we have set onclick listener for our button playBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // we have declared an intent to open new activity. Intent i = new Intent(MainActivity.this, VideoPlayerActivity.class); startActivity(i); } }); }}", "e": 9135, "s": 8215, "text": null }, { "code": null, "e": 9188, "s": 9135, "text": "Step 9: Add internet permission in the Manifest file" }, { "code": null, "e": 9281, "s": 9188, "text": "Navigate to the app > AndroidManifest.xml file there you have to add the below permissions. " }, { "code": null, "e": 9308, "s": 9281, "text": "<!–For internet usage–> " }, { "code": null, "e": 9373, "s": 9308, "text": "<uses-permission android:name=”android.permission.INTERNET”/> " }, { "code": null, "e": 9447, "s": 9373, "text": "<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE”/>" }, { "code": null, "e": 9612, "s": 9447, "text": "Along with this you will get to see activity section inside your application tag inside that add your video player’s activity screen orientation to landscape mode. " }, { "code": null, "e": 9663, "s": 9612, "text": "<!–Here my activity name was VideoPlayerActivity–>" }, { "code": null, "e": 9709, "s": 9663, "text": "<activity android:name=”.VideoPlayerActivity”" }, { "code": null, "e": 9752, "s": 9709, "text": " android:screenOrientation=”landscape”>" }, { "code": null, "e": 9768, "s": 9752, "text": "</activity> " }, { "code": null, "e": 9829, "s": 9768, "text": "Below is the code for the complete AndroidManifest.xml file:" }, { "code": null, "e": 9833, "s": 9829, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.gtappdevelopers.youtubeplayerview\"> <!--For internet usage--> <uses-permission android:name=\"android.permission.INTERNET\"/> <uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/Theme.YoutubePlayerView\"> <!--Here my activity name was VideoPlayerActivity--> <activity android:name=\".VideoPlayerActivity\" android:screenOrientation=\"landscape\"> </activity> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>", "e": 10929, "s": 9833, "text": null }, { "code": null, "e": 11029, "s": 10929, "text": "Check out the project on the below GitHub link: https://github.com/ChaitanyaMunje/YoutubePlayerView" }, { "code": null, "e": 11037, "s": 11029, "text": "android" }, { "code": null, "e": 11050, "s": 11037, "text": "Android-View" }, { "code": null, "e": 11058, "s": 11050, "text": "Android" }, { "code": null, "e": 11063, "s": 11058, "text": "Java" }, { "code": null, "e": 11082, "s": 11063, "text": "Technical Scripter" }, { "code": null, "e": 11087, "s": 11082, "text": "Java" }, { "code": null, "e": 11095, "s": 11087, "text": "Android" } ]
Fading Text Animation Effect Using CSS3
18 Jan, 2021 The fading text animation effect is one of the most demanding effects on UI/UX designing. This effect can be achieved by using HTML5 and CSS3. In the fading text effect, whenever we load the window, the text will slowly start disappearing. We can implement this effect using the animation property in CSS3. HTML code: In this section, we will make the layout of the web-page. index.html HTML <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"></head> <body> <div> <h2>GeeksforGeeks</h2> </div></body> </html> CSS code: In this section, we will add some CSS properties to create a fading text effect. CSS <style> * { margin: 0; padding: 0; } body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: green; animation-name: gfg; animation-duration: 4s; } h2 { position: relative; margin: 0; font-size: 5em; font-weight: 750; color: white; z-index: 1; overflow: hidden; } h2:before { content: ''; position: absolute; right: 130%; width: 130%; height: 100%; background: linear-gradient(90deg, transparent 0%, green 5%, green 100%); animation: geeksforgeeks 5s linear backwards; } @keyframes geeksforgeeks { from { right: 130% } to { right: -10%; } }</style> Complete Code: In this section, we will combine the above two sections to create a fading text effect using HTML5 and CSS3. HTML <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <style> * { margin: 0; padding: 0; } body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: green; animation-name: gfg; animation-duration: 4s; } h2 { position: relative; margin: 0; font-size: 5em; font-weight: 750; color: white; z-index: 1; overflow: hidden; } h2:before { content: ''; position: absolute; right: 130%; width: 130%; height: 100%; background: linear-gradient(90deg, transparent 0%, green 5%, green 100%); animation: geeksforgeeks 5s linear backwards; } @keyframes geeksforgeeks { from { right: 130% } to { right: -10%; } } </style></head> <body> <div> <h2>GeeksforGeeks</h2> </div></body> </html> Output: CSS-Misc HTML-Misc Technical Scripter 2020 CSS HTML Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jan, 2021" }, { "code": null, "e": 335, "s": 28, "text": "The fading text animation effect is one of the most demanding effects on UI/UX designing. This effect can be achieved by using HTML5 and CSS3. In the fading text effect, whenever we load the window, the text will slowly start disappearing. We can implement this effect using the animation property in CSS3." }, { "code": null, "e": 404, "s": 335, "text": "HTML code: In this section, we will make the layout of the web-page." }, { "code": null, "e": 415, "s": 404, "text": "index.html" }, { "code": null, "e": 420, "s": 415, "text": "HTML" }, { "code": "<html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"></head> <body> <div> <h2>GeeksforGeeks</h2> </div></body> </html>", "e": 633, "s": 420, "text": null }, { "code": null, "e": 724, "s": 633, "text": "CSS code: In this section, we will add some CSS properties to create a fading text effect." }, { "code": null, "e": 728, "s": 724, "text": "CSS" }, { "code": "<style> * { margin: 0; padding: 0; } body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: green; animation-name: gfg; animation-duration: 4s; } h2 { position: relative; margin: 0; font-size: 5em; font-weight: 750; color: white; z-index: 1; overflow: hidden; } h2:before { content: ''; position: absolute; right: 130%; width: 130%; height: 100%; background: linear-gradient(90deg, transparent 0%, green 5%, green 100%); animation: geeksforgeeks 5s linear backwards; } @keyframes geeksforgeeks { from { right: 130% } to { right: -10%; } }</style>", "e": 1598, "s": 728, "text": null }, { "code": null, "e": 1722, "s": 1598, "text": "Complete Code: In this section, we will combine the above two sections to create a fading text effect using HTML5 and CSS3." }, { "code": null, "e": 1727, "s": 1722, "text": "HTML" }, { "code": "<html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <style> * { margin: 0; padding: 0; } body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: green; animation-name: gfg; animation-duration: 4s; } h2 { position: relative; margin: 0; font-size: 5em; font-weight: 750; color: white; z-index: 1; overflow: hidden; } h2:before { content: ''; position: absolute; right: 130%; width: 130%; height: 100%; background: linear-gradient(90deg, transparent 0%, green 5%, green 100%); animation: geeksforgeeks 5s linear backwards; } @keyframes geeksforgeeks { from { right: 130% } to { right: -10%; } } </style></head> <body> <div> <h2>GeeksforGeeks</h2> </div></body> </html>", "e": 2983, "s": 1727, "text": null }, { "code": null, "e": 2991, "s": 2983, "text": "Output:" }, { "code": null, "e": 3000, "s": 2991, "text": "CSS-Misc" }, { "code": null, "e": 3010, "s": 3000, "text": "HTML-Misc" }, { "code": null, "e": 3034, "s": 3010, "text": "Technical Scripter 2020" }, { "code": null, "e": 3038, "s": 3034, "text": "CSS" }, { "code": null, "e": 3043, "s": 3038, "text": "HTML" }, { "code": null, "e": 3062, "s": 3043, "text": "Technical Scripter" }, { "code": null, "e": 3079, "s": 3062, "text": "Web Technologies" }, { "code": null, "e": 3084, "s": 3079, "text": "HTML" } ]
Optional empty() method in Java with examples
30 Jul, 2019 The empty() method of java.util.Optional class in Java is used to get an empty instance of this Optional class. This instance do not contain any value. Syntax: public static <T> Optional<T> empty() Parameters: This method accepts nothing. Return value: This method returns an empty instance of this Optional class. Below programs illustrate empty() method:Program 1: // Java program to demonstrate// Optional.empty() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print value System.out.println("Optional: " + op); }} Optional: Optional.empty Program 2: // Java program to demonstrate// Optional.empty() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<String> op = Optional.empty(); // print value System.out.println("Optional: " + op); }} Optional: Optional.empty Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#empty– Java - util package Java-Functions Java-Optional 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 Strings in Java Java Programming Examples HashSet in Java Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jul, 2019" }, { "code": null, "e": 180, "s": 28, "text": "The empty() method of java.util.Optional class in Java is used to get an empty instance of this Optional class. This instance do not contain any value." }, { "code": null, "e": 188, "s": 180, "text": "Syntax:" }, { "code": null, "e": 230, "s": 188, "text": "public static <T> \n Optional<T> empty()\n" }, { "code": null, "e": 271, "s": 230, "text": "Parameters: This method accepts nothing." }, { "code": null, "e": 347, "s": 271, "text": "Return value: This method returns an empty instance of this Optional class." }, { "code": null, "e": 399, "s": 347, "text": "Below programs illustrate empty() method:Program 1:" }, { "code": "// Java program to demonstrate// Optional.empty() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print value System.out.println(\"Optional: \" + op); }}", "e": 737, "s": 399, "text": null }, { "code": null, "e": 763, "s": 737, "text": "Optional: Optional.empty\n" }, { "code": null, "e": 774, "s": 763, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Optional.empty() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<String> op = Optional.empty(); // print value System.out.println(\"Optional: \" + op); }}", "e": 1111, "s": 774, "text": null }, { "code": null, "e": 1137, "s": 1111, "text": "Optional: Optional.empty\n" }, { "code": null, "e": 1221, "s": 1137, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#empty–" }, { "code": null, "e": 1241, "s": 1221, "text": "Java - util package" }, { "code": null, "e": 1256, "s": 1241, "text": "Java-Functions" }, { "code": null, "e": 1270, "s": 1256, "text": "Java-Optional" }, { "code": null, "e": 1275, "s": 1270, "text": "Java" }, { "code": null, "e": 1280, "s": 1275, "text": "Java" }, { "code": null, "e": 1378, "s": 1280, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1393, "s": 1378, "text": "Stream In Java" }, { "code": null, "e": 1414, "s": 1393, "text": "Introduction to Java" }, { "code": null, "e": 1435, "s": 1414, "text": "Constructors in Java" }, { "code": null, "e": 1454, "s": 1435, "text": "Exceptions in Java" }, { "code": null, "e": 1471, "s": 1454, "text": "Generics in Java" }, { "code": null, "e": 1501, "s": 1471, "text": "Functional Interfaces in Java" }, { "code": null, "e": 1517, "s": 1501, "text": "Strings in Java" }, { "code": null, "e": 1543, "s": 1517, "text": "Java Programming Examples" }, { "code": null, "e": 1559, "s": 1543, "text": "HashSet in Java" } ]
How to call some function before main() function in C++?
03 Jun, 2020 Since it is known that main() method is the entry point of the program. Hence it is the first method that will get executed by the compiler. But this article explains how to call some function before the main() method gets executed in C++. How to call some function before main() function?To call some function before main() method in C++, Create a classCreate a function in this class to be called.Create the constructor of this class and call the above method in this constructorNow declare an object of this class as a global variable.Global variables are usually declared outside of all of the functions and blocks, at the top of the program. They can be accessed from any portion of the program. Create a class Create a function in this class to be called. Create the constructor of this class and call the above method in this constructor Now declare an object of this class as a global variable. Global variables are usually declared outside of all of the functions and blocks, at the top of the program. They can be accessed from any portion of the program. Below is the implementation of the above approach: // C++ program to call some function// before main() function #include <iostream>using namespace std; // Classclass GFG { public: // Constructor of the class GFG() { // Call the other function func(); } // Function to get executed before main() void func() { cout << "Inside the other function" << endl; }}; // Global variable to declare// the object of class GFGGFG obj; // Driver codeint main(){ cout << "Inside main method" << endl; return 0;} Inside the other function Inside main method How will this get executed?Now when the program will get executed, the global variable will get created before calling the main() method. Now, while creating the object with the help of a constructor, the constructor will get executed and the other function will get executed before main() method. Hence we can easily call the function before the main(). pawan_joshi CPP-Functions cpp-main main Technical Scripter 2019 C++ Programs Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Jun, 2020" }, { "code": null, "e": 294, "s": 54, "text": "Since it is known that main() method is the entry point of the program. Hence it is the first method that will get executed by the compiler. But this article explains how to call some function before the main() method gets executed in C++." }, { "code": null, "e": 394, "s": 294, "text": "How to call some function before main() function?To call some function before main() method in C++," }, { "code": null, "e": 755, "s": 394, "text": "Create a classCreate a function in this class to be called.Create the constructor of this class and call the above method in this constructorNow declare an object of this class as a global variable.Global variables are usually declared outside of all of the functions and blocks, at the top of the program. They can be accessed from any portion of the program." }, { "code": null, "e": 770, "s": 755, "text": "Create a class" }, { "code": null, "e": 816, "s": 770, "text": "Create a function in this class to be called." }, { "code": null, "e": 899, "s": 816, "text": "Create the constructor of this class and call the above method in this constructor" }, { "code": null, "e": 957, "s": 899, "text": "Now declare an object of this class as a global variable." }, { "code": null, "e": 1120, "s": 957, "text": "Global variables are usually declared outside of all of the functions and blocks, at the top of the program. They can be accessed from any portion of the program." }, { "code": null, "e": 1171, "s": 1120, "text": "Below is the implementation of the above approach:" }, { "code": "// C++ program to call some function// before main() function #include <iostream>using namespace std; // Classclass GFG { public: // Constructor of the class GFG() { // Call the other function func(); } // Function to get executed before main() void func() { cout << \"Inside the other function\" << endl; }}; // Global variable to declare// the object of class GFGGFG obj; // Driver codeint main(){ cout << \"Inside main method\" << endl; return 0;}", "e": 1690, "s": 1171, "text": null }, { "code": null, "e": 1736, "s": 1690, "text": "Inside the other function\nInside main method\n" }, { "code": null, "e": 2034, "s": 1736, "text": "How will this get executed?Now when the program will get executed, the global variable will get created before calling the main() method. Now, while creating the object with the help of a constructor, the constructor will get executed and the other function will get executed before main() method." }, { "code": null, "e": 2091, "s": 2034, "text": "Hence we can easily call the function before the main()." }, { "code": null, "e": 2103, "s": 2091, "text": "pawan_joshi" }, { "code": null, "e": 2117, "s": 2103, "text": "CPP-Functions" }, { "code": null, "e": 2126, "s": 2117, "text": "cpp-main" }, { "code": null, "e": 2131, "s": 2126, "text": "main" }, { "code": null, "e": 2155, "s": 2131, "text": "Technical Scripter 2019" }, { "code": null, "e": 2168, "s": 2155, "text": "C++ Programs" }, { "code": null, "e": 2187, "s": 2168, "text": "Technical Scripter" } ]
What is DVM(Dalvik Virtual Machine)?
22 May, 2020 Dalvik Virtual Machine is a Register-Based virtual machine. It was designed and written by Dan Bornstein with contributions of other Google engineers as part of the Android mobile phone platform. The Dalvik virtual machine was named after Bornstein after the fishing village “Dalvík” in Eyjafjörður, Iceland, where some of his ancestors used to live. The Java Compiler(javac) converts the Java Source Code into Java Byte-Code(.class). Then DEX Compiler converts this (.class) file into in Dalvik Byte Code i.e. “.dex” file. For Android, a new Virtual machine was developed by Google as stated above. It uses registers of the CPU to store the operands. So no requirement of any pushing and popping of instructions. Hence making execution faster. The instructions operate on virtual registers, being those virtual registers memory positions in the host device. Register-based models are good at optimizing and running on low memory. They can store common sub-expression results which can be used again in the future. This is not possible in a Stack-based model at all. Dalvik Virtual Machine uses its own byte-code and runs “.dex”(Dalvik Executable File) file. DVM supports the Android operating system only. In DVM executable is APK. Execution is faster. From Android 2.2 SDK Dalvik has it’s own JIT (Just In Time) compiler. DVM has been designed so that a device can run multiple instances of the Virtual Machine effectively. Applications are given their own instances. DVM supports only Android Operating System. For DVM very few Re-Tools are available. Requires more instructions than register machines to implement the same high-level code. App Installation takes more time due to dex. More internal storage is required. Picked Computer Organization & Architecture Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 May, 2020" }, { "code": null, "e": 381, "s": 28, "text": "Dalvik Virtual Machine is a Register-Based virtual machine. It was designed and written by Dan Bornstein with contributions of other Google engineers as part of the Android mobile phone platform. The Dalvik virtual machine was named after Bornstein after the fishing village “Dalvík” in Eyjafjörður, Iceland, where some of his ancestors used to live." }, { "code": null, "e": 554, "s": 381, "text": "The Java Compiler(javac) converts the Java Source Code into Java Byte-Code(.class). Then DEX Compiler converts this (.class) file into in Dalvik Byte Code i.e. “.dex” file." }, { "code": null, "e": 1189, "s": 554, "text": "For Android, a new Virtual machine was developed by Google as stated above. It uses registers of the CPU to store the operands. So no requirement of any pushing and popping of instructions. Hence making execution faster. The instructions operate on virtual registers, being those virtual registers memory positions in the host device. Register-based models are good at optimizing and running on low memory. They can store common sub-expression results which can be used again in the future. This is not possible in a Stack-based model at all. Dalvik Virtual Machine uses its own byte-code and runs “.dex”(Dalvik Executable File) file." }, { "code": null, "e": 1237, "s": 1189, "text": "DVM supports the Android operating system only." }, { "code": null, "e": 1263, "s": 1237, "text": "In DVM executable is APK." }, { "code": null, "e": 1284, "s": 1263, "text": "Execution is faster." }, { "code": null, "e": 1354, "s": 1284, "text": "From Android 2.2 SDK Dalvik has it’s own JIT (Just In Time) compiler." }, { "code": null, "e": 1456, "s": 1354, "text": "DVM has been designed so that a device can run multiple instances of the Virtual Machine effectively." }, { "code": null, "e": 1500, "s": 1456, "text": "Applications are given their own instances." }, { "code": null, "e": 1544, "s": 1500, "text": "DVM supports only Android Operating System." }, { "code": null, "e": 1585, "s": 1544, "text": "For DVM very few Re-Tools are available." }, { "code": null, "e": 1674, "s": 1585, "text": "Requires more instructions than register machines to implement the same high-level code." }, { "code": null, "e": 1719, "s": 1674, "text": "App Installation takes more time due to dex." }, { "code": null, "e": 1754, "s": 1719, "text": "More internal storage is required." }, { "code": null, "e": 1761, "s": 1754, "text": "Picked" }, { "code": null, "e": 1798, "s": 1761, "text": "Computer Organization & Architecture" }, { "code": null, "e": 1814, "s": 1798, "text": "Write From Home" } ]
How to change the “checked” background color of toggle switch in Bootstrap 4?
28 Oct, 2020 Bootstrap is a popular choice among web developers for building interactive webpage designs. Bootstrap has come along a long way with multiple releases and enriched content with every new release. Bootstrap has a wide community that has also contributed newer packages that have made working with Bootstrap easier. In this article, we shall deal with changing the background color of the toggle switch in Bootstrap 4. Bootstrap 4 provides a custom-switch class by default which is used to create toggle switch and the custom-control-input class deals with the background color and border color of the switch. In Bootstrap 4, the background color of the toggle switch is blue. This color can be changed by manipulating the custom-control-input class. There is another method to change the color using external libraries with a wide range of color classes. We shall discuss both the methods in the examples below. First Approach This approach creates the toggle switch using the predefined custom-switch class and the color is altered by specifying the required color in the custom-control-input classes. This method includes a great deal of coding as one must repeat the entire code for a different color. This makes it cumbersome. Code Implementation <!DOCTYPE html><html> <head> <title></title> <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" /> <style> .custom-control-input:focus ~ .custom-control-label::before { /* when the button is toggled off it is still in focus and a violet border will appear */ border-color: violet !important; /* box shadow is blue by default but we do not want any shadow hence we have set all the values as 0 */ box-shadow: 0 0 0 0rem rgba(0, 0, 0, 0) !important; } /*sets the background color of switch to violet when it is checked*/ .custom-control-input:checked ~ .custom-control-label::before { border-color: violet !important; background-color: violet !important; } /*sets the background color of switch to violet when it is active*/ .custom-control-input:active ~ .custom-control-label::before { background-color: violet !important; border-color: violet !important; } /*sets the border color of switch to violet when it is not checked*/ .custom-control-input:focus: not(:checked) ~ .custom-control-label::before { border-color: violet !important; } </style> </head> <body> <!--main container which contains the web elements--> <div class="container mt-5"> <div class="custom-control custom-switch"> <input type="checkbox" class="custom-control-input" id="customSwitch1" /> <label class="custom-control-label" for="customSwitch1"> Toggle this switch</label> </div> </div> </body></html> Output Second Approach The second method eliminates the extra efforts required in the first method to specify the color changes for each and every custom-control-input class. This is a better and sophisticated approach as it does not include lengthy coding. The method makes use of the Bootstrap Switch Button package available on Github. It is an open-source library and works with all Bootstrap 4 components. This library has predefined classes that help us define a color for the toggle switch. The data-onstyle attribute of the input tag is responsible for setting the toggle switch color. The color options available are similar to Buttons in Bootstrap 4. The data-toggle attribute specifies that the checkbox is a switch button and the data-width attribute specifies the width of the toggle switch. The checked attribute denotes that when the page loads the switch is already checked and can be unchecked as per requirement. Code implementation <!DOCTYPE html><html> <head> <title>Toggle switch</title> <!--import Bootstrap Switch Button package using cdn--> <link href="https://cdn.jsdelivr.net/gh/gitbrent/[email protected]/css/bootstrap-switch-button.min.css" rel="stylesheet" /> <!--import Bootstrap 4 using cdn--> <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" /> </head> <body> <!--main container which contains the web elements--> <div class="container mt-5"> <input type="checkbox" data-toggle="switchbutton" checked data-width="100" data-onstyle="primary" /> <input type="checkbox" data-toggle="switchbutton" checked data-width="100" data-onstyle="secondary" /><br /> <br /> <input type="checkbox" data-toggle="switchbutton" checked data-width="100" data-onstyle="success" /> <input type="checkbox" data-toggle="switchbutton" checked data-width="100" data-onstyle="danger" /><br /> <br /> <input type="checkbox" data-toggle="switchbutton" checked data-width="100" data-onstyle="warning" /> <input type="checkbox" data-toggle="switchbutton" checked data-width="100" data-onstyle="info" /><br /> <br /> <input type="checkbox" data-toggle="switchbutton" checked data-width="100" data-onstyle="light" /> <input type="checkbox" data-toggle="switchbutton" checked data-width="100" data-onstyle="dark" /> </div> <!--javascript cdn--> <script src="https://cdn.jsdelivr.net/gh/gitbrent/[email protected]/dist/bootstrap-switch-button.min.js"> </script> </body></html> Output Technical Scripter 2020 Bootstrap Technical Scripter 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": "\n28 Oct, 2020" }, { "code": null, "e": 940, "s": 28, "text": "Bootstrap is a popular choice among web developers for building interactive webpage designs. Bootstrap has come along a long way with multiple releases and enriched content with every new release. Bootstrap has a wide community that has also contributed newer packages that have made working with Bootstrap easier. In this article, we shall deal with changing the background color of the toggle switch in Bootstrap 4. Bootstrap 4 provides a custom-switch class by default which is used to create toggle switch and the custom-control-input class deals with the background color and border color of the switch. In Bootstrap 4, the background color of the toggle switch is blue. This color can be changed by manipulating the custom-control-input class. There is another method to change the color using external libraries with a wide range of color classes. We shall discuss both the methods in the examples below." }, { "code": null, "e": 955, "s": 940, "text": "First Approach" }, { "code": null, "e": 1259, "s": 955, "text": "This approach creates the toggle switch using the predefined custom-switch class and the color is altered by specifying the required color in the custom-control-input classes. This method includes a great deal of coding as one must repeat the entire code for a different color. This makes it cumbersome." }, { "code": null, "e": 1279, "s": 1259, "text": "Code Implementation" }, { "code": "<!DOCTYPE html><html> <head> <title></title> <link rel=\"stylesheet\" type=\"text/css\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\" /> <style> .custom-control-input:focus ~ .custom-control-label::before { /* when the button is toggled off it is still in focus and a violet border will appear */ border-color: violet !important; /* box shadow is blue by default but we do not want any shadow hence we have set all the values as 0 */ box-shadow: 0 0 0 0rem rgba(0, 0, 0, 0) !important; } /*sets the background color of switch to violet when it is checked*/ .custom-control-input:checked ~ .custom-control-label::before { border-color: violet !important; background-color: violet !important; } /*sets the background color of switch to violet when it is active*/ .custom-control-input:active ~ .custom-control-label::before { background-color: violet !important; border-color: violet !important; } /*sets the border color of switch to violet when it is not checked*/ .custom-control-input:focus: not(:checked) ~ .custom-control-label::before { border-color: violet !important; } </style> </head> <body> <!--main container which contains the web elements--> <div class=\"container mt-5\"> <div class=\"custom-control custom-switch\"> <input type=\"checkbox\" class=\"custom-control-input\" id=\"customSwitch1\" /> <label class=\"custom-control-label\" for=\"customSwitch1\"> Toggle this switch</label> </div> </div> </body></html>", "e": 3299, "s": 1279, "text": null }, { "code": null, "e": 3306, "s": 3299, "text": "Output" }, { "code": null, "e": 3322, "s": 3306, "text": "Second Approach" }, { "code": null, "e": 4230, "s": 3322, "text": "The second method eliminates the extra efforts required in the first method to specify the color changes for each and every custom-control-input class. This is a better and sophisticated approach as it does not include lengthy coding. The method makes use of the Bootstrap Switch Button package available on Github. It is an open-source library and works with all Bootstrap 4 components. This library has predefined classes that help us define a color for the toggle switch. The data-onstyle attribute of the input tag is responsible for setting the toggle switch color. The color options available are similar to Buttons in Bootstrap 4. The data-toggle attribute specifies that the checkbox is a switch button and the data-width attribute specifies the width of the toggle switch. The checked attribute denotes that when the page loads the switch is already checked and can be unchecked as per requirement." }, { "code": null, "e": 4250, "s": 4230, "text": "Code implementation" }, { "code": "<!DOCTYPE html><html> <head> <title>Toggle switch</title> <!--import Bootstrap Switch Button package using cdn--> <link href=\"https://cdn.jsdelivr.net/gh/gitbrent/[email protected]/css/bootstrap-switch-button.min.css\" rel=\"stylesheet\" /> <!--import Bootstrap 4 using cdn--> <link rel=\"stylesheet\" type=\"text/css\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\" /> </head> <body> <!--main container which contains the web elements--> <div class=\"container mt-5\"> <input type=\"checkbox\" data-toggle=\"switchbutton\" checked data-width=\"100\" data-onstyle=\"primary\" /> <input type=\"checkbox\" data-toggle=\"switchbutton\" checked data-width=\"100\" data-onstyle=\"secondary\" /><br /> <br /> <input type=\"checkbox\" data-toggle=\"switchbutton\" checked data-width=\"100\" data-onstyle=\"success\" /> <input type=\"checkbox\" data-toggle=\"switchbutton\" checked data-width=\"100\" data-onstyle=\"danger\" /><br /> <br /> <input type=\"checkbox\" data-toggle=\"switchbutton\" checked data-width=\"100\" data-onstyle=\"warning\" /> <input type=\"checkbox\" data-toggle=\"switchbutton\" checked data-width=\"100\" data-onstyle=\"info\" /><br /> <br /> <input type=\"checkbox\" data-toggle=\"switchbutton\" checked data-width=\"100\" data-onstyle=\"light\" /> <input type=\"checkbox\" data-toggle=\"switchbutton\" checked data-width=\"100\" data-onstyle=\"dark\" /> </div> <!--javascript cdn--> <script src=\"https://cdn.jsdelivr.net/gh/gitbrent/[email protected]/dist/bootstrap-switch-button.min.js\"> </script> </body></html>", "e": 6460, "s": 4250, "text": null }, { "code": null, "e": 6467, "s": 6460, "text": "Output" }, { "code": null, "e": 6491, "s": 6467, "text": "Technical Scripter 2020" }, { "code": null, "e": 6501, "s": 6491, "text": "Bootstrap" }, { "code": null, "e": 6520, "s": 6501, "text": "Technical Scripter" }, { "code": null, "e": 6537, "s": 6520, "text": "Web Technologies" } ]
How to move a text in HTML ?
21 Jun, 2021 Some content of a website is like an alert or notification/information that has to be shown to each and every person who is using the website. It has to be placed at some point where everyone can see it. In this article, we will learn how to create moving content on your website using HTML <marquee> tag. The <marquee> tag in HTML is used to create scrolling text or image in a webpages. It scrolls either from horizontally left to right or right to left, or vertically top to bottom or bottom to top. Syntax: <marquee> Contents... </marquee> Approach: Create a simple HTML file in any text editor. Add the text you want to move inside the <marquee> tag. Example: HTML <!DOCTYPE html><html> <body> <h2>Welcome To GFG</h2> <marquee> Lets Move this text.</marquee> <marquee direction="right" behavior="alternate" style="border:BLACK 2px SOLID"> Geeks for Geeks </marquee></body> </html> Output: HTML-Questions HTML-Tags Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jun, 2021" }, { "code": null, "e": 232, "s": 28, "text": "Some content of a website is like an alert or notification/information that has to be shown to each and every person who is using the website. It has to be placed at some point where everyone can see it." }, { "code": null, "e": 531, "s": 232, "text": "In this article, we will learn how to create moving content on your website using HTML <marquee> tag. The <marquee> tag in HTML is used to create scrolling text or image in a webpages. It scrolls either from horizontally left to right or right to left, or vertically top to bottom or bottom to top." }, { "code": null, "e": 539, "s": 531, "text": "Syntax:" }, { "code": null, "e": 572, "s": 539, "text": "<marquee> Contents... </marquee>" }, { "code": null, "e": 582, "s": 572, "text": "Approach:" }, { "code": null, "e": 628, "s": 582, "text": "Create a simple HTML file in any text editor." }, { "code": null, "e": 685, "s": 628, "text": " Add the text you want to move inside the <marquee> tag." }, { "code": null, "e": 694, "s": 685, "text": "Example:" }, { "code": null, "e": 699, "s": 694, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h2>Welcome To GFG</h2> <marquee> Lets Move this text.</marquee> <marquee direction=\"right\" behavior=\"alternate\" style=\"border:BLACK 2px SOLID\"> Geeks for Geeks </marquee></body> </html>", "e": 952, "s": 699, "text": null }, { "code": null, "e": 960, "s": 952, "text": "Output:" }, { "code": null, "e": 975, "s": 960, "text": "HTML-Questions" }, { "code": null, "e": 985, "s": 975, "text": "HTML-Tags" }, { "code": null, "e": 992, "s": 985, "text": "Picked" }, { "code": null, "e": 997, "s": 992, "text": "HTML" }, { "code": null, "e": 1014, "s": 997, "text": "Web Technologies" }, { "code": null, "e": 1019, "s": 1014, "text": "HTML" } ]
Python program to find N largest elements from a list
24 Apr, 2020 Given a list of integers, the task is to find N largest elements assuming size of list is greater than or equal o N. Examples : Input : [4, 5, 1, 2, 9] N = 2 Output : [9, 5] Input : [81, 52, 45, 10, 3, 2, 96] N = 3 Output : [81, 96, 52] A simple solution traverse the given list N times. In every traversal, find the maximum, add it to result, and remove it from the list. Below is the implementation : # Python program to find N largest# element from given list of integers # Function returns N largest elementsdef Nmaxelements(list1, N): final_list = [] for i in range(0, N): max1 = 0 for j in range(len(list1)): if list1[j] > max1: max1 = list1[j]; list1.remove(max1); final_list.append(max1) print(final_list) # Driver codelist1 = [2, 6, 41, 85, 0, 3, 7, 6, 10]N = 2 # Calling the functionNmaxelements(list1, N) Output : [85, 41] Time Complexity : O(N * size) where size is size of the given list.Method 2: # Python program to find N largest# element from given list of integers l = [1000,298,3579,100,200,-45,900]n = 4 l.sort()print(l[-n:]) Output: [-45, 100, 200, 298, 900, 1000, 3579] Find the N largest element: 4 [298, 900, 1000, 3579] Please refer k largest(or smallest) elements in an array for more efficient solutions of this problem. shyampopz0 Python list-programs python-list Python Python Programs Technical Scripter python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Apr, 2020" }, { "code": null, "e": 169, "s": 52, "text": "Given a list of integers, the task is to find N largest elements assuming size of list is greater than or equal o N." }, { "code": null, "e": 180, "s": 169, "text": "Examples :" }, { "code": null, "e": 310, "s": 180, "text": "Input : [4, 5, 1, 2, 9] \n N = 2\nOutput : [9, 5]\n\nInput : [81, 52, 45, 10, 3, 2, 96] \n N = 3\nOutput : [81, 96, 52]\n" }, { "code": null, "e": 476, "s": 310, "text": "A simple solution traverse the given list N times. In every traversal, find the maximum, add it to result, and remove it from the list. Below is the implementation :" }, { "code": "# Python program to find N largest# element from given list of integers # Function returns N largest elementsdef Nmaxelements(list1, N): final_list = [] for i in range(0, N): max1 = 0 for j in range(len(list1)): if list1[j] > max1: max1 = list1[j]; list1.remove(max1); final_list.append(max1) print(final_list) # Driver codelist1 = [2, 6, 41, 85, 0, 3, 7, 6, 10]N = 2 # Calling the functionNmaxelements(list1, N)", "e": 1001, "s": 476, "text": null }, { "code": null, "e": 1010, "s": 1001, "text": "Output :" }, { "code": null, "e": 1019, "s": 1010, "text": "[85, 41]" }, { "code": null, "e": 1096, "s": 1019, "text": "Time Complexity : O(N * size) where size is size of the given list.Method 2:" }, { "code": "# Python program to find N largest# element from given list of integers l = [1000,298,3579,100,200,-45,900]n = 4 l.sort()print(l[-n:])", "e": 1233, "s": 1096, "text": null }, { "code": null, "e": 1241, "s": 1233, "text": "Output:" }, { "code": null, "e": 1333, "s": 1241, "text": "[-45, 100, 200, 298, 900, 1000, 3579]\nFind the N largest element: 4\n[298, 900, 1000, 3579]\n" }, { "code": null, "e": 1436, "s": 1333, "text": "Please refer k largest(or smallest) elements in an array for more efficient solutions of this problem." }, { "code": null, "e": 1447, "s": 1436, "text": "shyampopz0" }, { "code": null, "e": 1468, "s": 1447, "text": "Python list-programs" }, { "code": null, "e": 1480, "s": 1468, "text": "python-list" }, { "code": null, "e": 1487, "s": 1480, "text": "Python" }, { "code": null, "e": 1503, "s": 1487, "text": "Python Programs" }, { "code": null, "e": 1522, "s": 1503, "text": "Technical Scripter" }, { "code": null, "e": 1534, "s": 1522, "text": "python-list" } ]
Hello World program in Kotlin
03 Jun, 2022 Hello, World! is the first basic program in any programming language. Let’s write the first program in Kotlin programming language. The “Hello, World!” program in Kotlin: Open your favorite editor notepad or notepad++ and create a file named firstapp.kt with the following code. // Kotlin Hello World Program fun main(args: Array<String>) { println("Hello, World!") } You can compile the program in the command-line compiler. $ kotlinc firstapp.kt Now, Run the program to see the output in a command-line compiler. $kotlin firstapp.kt Hello, World! Note: You can run the program in Intellij IDEA as shown in the Setting up the environment article. Line #1: First line is a comment which is ignored by the compiler. Comments are added to the program with the purpose to make the source code easy to read and understand by the readers. Kotlin supports two types of comments as follows: 1. Single line comment // single line comment 2. Multiple line comment /* This is multi line comment */ Line #2: The second line defines the main function fun main(args: Array<String>) { // ... } The main() function is the entry point of every program. All functions in kotlin start fun keyword followed by the name of function(here main is the name), a list of parameters, an optional return type, and the body of the function ( { ....... } ). In this case, main function contains the argument – an array of strings and return units. Unit type corresponds to void in java means the function does not return any value. Line #3: The third line is a statement and it prints “Hello, World!” to print the output of the program. println("Hello, World!") Semicolons are optional in Kotlin, just like other modern programming languages. simranarora5sos singhankitasingh066 Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n03 Jun, 2022" }, { "code": null, "e": 186, "s": 53, "text": "Hello, World! is the first basic program in any programming language. Let’s write the first program in Kotlin programming language. " }, { "code": null, "e": 334, "s": 186, "text": "The “Hello, World!” program in Kotlin: Open your favorite editor notepad or notepad++ and create a file named firstapp.kt with the following code. " }, { "code": null, "e": 427, "s": 334, "text": "// Kotlin Hello World Program\nfun main(args: Array<String>) {\n println(\"Hello, World!\")\n}" }, { "code": null, "e": 486, "s": 427, "text": "You can compile the program in the command-line compiler. " }, { "code": null, "e": 508, "s": 486, "text": "$ kotlinc firstapp.kt" }, { "code": null, "e": 576, "s": 508, "text": "Now, Run the program to see the output in a command-line compiler. " }, { "code": null, "e": 610, "s": 576, "text": "$kotlin firstapp.kt\nHello, World!" }, { "code": null, "e": 710, "s": 610, "text": "Note: You can run the program in Intellij IDEA as shown in the Setting up the environment article. " }, { "code": null, "e": 896, "s": 710, "text": "Line #1: First line is a comment which is ignored by the compiler. Comments are added to the program with the purpose to make the source code easy to read and understand by the readers." }, { "code": null, "e": 947, "s": 896, "text": "Kotlin supports two types of comments as follows: " }, { "code": null, "e": 970, "s": 947, "text": "1. Single line comment" }, { "code": null, "e": 993, "s": 970, "text": "// single line comment" }, { "code": null, "e": 1018, "s": 993, "text": "2. Multiple line comment" }, { "code": null, "e": 1063, "s": 1018, "text": "/* This is\n multi line\n comment\n*/" }, { "code": null, "e": 1115, "s": 1063, "text": "Line #2: The second line defines the main function " }, { "code": null, "e": 1161, "s": 1115, "text": " fun main(args: Array<String>) {\n // ...\n}" }, { "code": null, "e": 1586, "s": 1161, "text": "The main() function is the entry point of every program. All functions in kotlin start fun keyword followed by the name of function(here main is the name), a list of parameters, an optional return type, and the body of the function ( { ....... } ). In this case, main function contains the argument – an array of strings and return units. Unit type corresponds to void in java means the function does not return any value. " }, { "code": null, "e": 1692, "s": 1586, "text": "Line #3: The third line is a statement and it prints “Hello, World!” to print the output of the program. " }, { "code": null, "e": 1717, "s": 1692, "text": "println(\"Hello, World!\")" }, { "code": null, "e": 1799, "s": 1717, "text": "Semicolons are optional in Kotlin, just like other modern programming languages. " }, { "code": null, "e": 1815, "s": 1799, "text": "simranarora5sos" }, { "code": null, "e": 1835, "s": 1815, "text": "singhankitasingh066" }, { "code": null, "e": 1842, "s": 1835, "text": "Kotlin" } ]
How to plot a normal distribution with Matplotlib in Python ?
03 Jan, 2021 Prerequisites: Matplotlib Numpy Scipy Statistics Normal Distribution is a probability function used in statistics that tells about how the data values are distributed. It is the most important probability distribution function used in statistics because of its advantages in real case scenarios. For example, the height of the population, shoe size, IQ level, rolling a die, and many more. The probability density function of normal or Gaussian distribution is given by: Probability Density Function Where, x is the variable, mu is the mean, and sigma standard deviation Matplotlib is python’s data visualization library which is widely used for the purpose of data visualization. Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python. Scipy is a python library that is useful in solving many mathematical equations and algorithms. Statistics module provides functions for calculating mathematical statistics of numeric data. To calculate mean of the data Syntax: mean(data) To calculate standard deviation of the data Syntax: stdev(data) To calculate normal probability density of the data norm.pdf is used, it refers to the normal probability density function which is a module in scipy library that uses the above probability density function to calculate the value. Syntax: norm.pdf(Data, loc, scale) Here, loc parameter is also known as the mean and the scale parameter is also known as standard deviation. Import module Create data Calculate mean and deviation Calculate normal probability density Plot using above calculated values Display plot Below is the implementation. Python3 import numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import normimport statistics # Plot between -10 and 10 with .001 steps.x_axis = np.arange(-20, 20, 0.01) # Calculating mean and standard deviationmean = statistics.mean(x_axis)sd = statistics.stdev(x_axis) plt.plot(x_axis, norm.pdf(x_axis, mean, sd))plt.show() Output: The output of above code Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jan, 2021" }, { "code": null, "e": 43, "s": 28, "text": "Prerequisites:" }, { "code": null, "e": 54, "s": 43, "text": "Matplotlib" }, { "code": null, "e": 60, "s": 54, "text": "Numpy" }, { "code": null, "e": 66, "s": 60, "text": "Scipy" }, { "code": null, "e": 77, "s": 66, "text": "Statistics" }, { "code": null, "e": 419, "s": 77, "text": "Normal Distribution is a probability function used in statistics that tells about how the data values are distributed. It is the most important probability distribution function used in statistics because of its advantages in real case scenarios. For example, the height of the population, shoe size, IQ level, rolling a die, and many more. " }, { "code": null, "e": 500, "s": 419, "text": "The probability density function of normal or Gaussian distribution is given by:" }, { "code": null, "e": 529, "s": 500, "text": "Probability Density Function" }, { "code": null, "e": 600, "s": 529, "text": "Where, x is the variable, mu is the mean, and sigma standard deviation" }, { "code": null, "e": 710, "s": 600, "text": "Matplotlib is python’s data visualization library which is widely used for the purpose of data visualization." }, { "code": null, "e": 934, "s": 710, "text": "Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python." }, { "code": null, "e": 1030, "s": 934, "text": "Scipy is a python library that is useful in solving many mathematical equations and algorithms." }, { "code": null, "e": 1124, "s": 1030, "text": "Statistics module provides functions for calculating mathematical statistics of numeric data." }, { "code": null, "e": 1154, "s": 1124, "text": "To calculate mean of the data" }, { "code": null, "e": 1162, "s": 1154, "text": "Syntax:" }, { "code": null, "e": 1173, "s": 1162, "text": "mean(data)" }, { "code": null, "e": 1217, "s": 1173, "text": "To calculate standard deviation of the data" }, { "code": null, "e": 1225, "s": 1217, "text": "Syntax:" }, { "code": null, "e": 1237, "s": 1225, "text": "stdev(data)" }, { "code": null, "e": 1468, "s": 1237, "text": "To calculate normal probability density of the data norm.pdf is used, it refers to the normal probability density function which is a module in scipy library that uses the above probability density function to calculate the value." }, { "code": null, "e": 1476, "s": 1468, "text": "Syntax:" }, { "code": null, "e": 1503, "s": 1476, "text": "norm.pdf(Data, loc, scale)" }, { "code": null, "e": 1610, "s": 1503, "text": "Here, loc parameter is also known as the mean and the scale parameter is also known as standard deviation." }, { "code": null, "e": 1624, "s": 1610, "text": "Import module" }, { "code": null, "e": 1636, "s": 1624, "text": "Create data" }, { "code": null, "e": 1665, "s": 1636, "text": "Calculate mean and deviation" }, { "code": null, "e": 1702, "s": 1665, "text": "Calculate normal probability density" }, { "code": null, "e": 1737, "s": 1702, "text": "Plot using above calculated values" }, { "code": null, "e": 1750, "s": 1737, "text": "Display plot" }, { "code": null, "e": 1779, "s": 1750, "text": "Below is the implementation." }, { "code": null, "e": 1787, "s": 1779, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import normimport statistics # Plot between -10 and 10 with .001 steps.x_axis = np.arange(-20, 20, 0.01) # Calculating mean and standard deviationmean = statistics.mean(x_axis)sd = statistics.stdev(x_axis) plt.plot(x_axis, norm.pdf(x_axis, mean, sd))plt.show()", "e": 2117, "s": 1787, "text": null }, { "code": null, "e": 2125, "s": 2117, "text": "Output:" }, { "code": null, "e": 2150, "s": 2125, "text": "The output of above code" }, { "code": null, "e": 2157, "s": 2150, "text": "Picked" }, { "code": null, "e": 2175, "s": 2157, "text": "Python-matplotlib" }, { "code": null, "e": 2182, "s": 2175, "text": "Python" }, { "code": null, "e": 2280, "s": 2182, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2298, "s": 2280, "text": "Python Dictionary" }, { "code": null, "e": 2340, "s": 2298, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2362, "s": 2340, "text": "Enumerate() in Python" }, { "code": null, "e": 2397, "s": 2362, "text": "Read a file line by line in Python" }, { "code": null, "e": 2423, "s": 2397, "text": "Python String | replace()" }, { "code": null, "e": 2455, "s": 2423, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2484, "s": 2455, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2514, "s": 2484, "text": "Iterate over a list in Python" }, { "code": null, "e": 2541, "s": 2514, "text": "Python Classes and Objects" } ]
Python OpenCV | cv2.ellipse() method
28 Aug, 2019 OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.ellipse() method is used to draw a ellipse on any image. Syntax: cv2.ellipse(image, centerCoordinates, axesLength, angle, startAngle, endAngle, color [, thickness[, lineType[, shift]]]) Parameters:image: It is the image on which ellipse is to be drawn.centerCoordinates: It is the center coordinates of ellipse. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).axesLength: It contains tuple of two variables containing major and minor axis of ellipse (major axis length, minor axis length).angle: Ellipse rotation angle in degrees.startAngle: Starting angle of the elliptic arc in degrees.endAngle: Ending angle of the elliptic arc in degrees.color: It is the color of border line of shape to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color.thickness: It is the thickness of the shape border line in px. Thickness of -1 px will fill the shape by the specified color.lineType: This is an optional parameter.It gives the type of the ellipse boundary.shift: This is an optional parameter. It denotes the number of fractional bits in the coordinates of the center and values of axes. Return Value: It returns an image. Image used for all the below examples: Example #1: # Python program to explain cv2.ellipse() method # importing cv2 import cv2 # path path = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png' # Reading an image in default modeimage = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' center_coordinates = (120, 100) axesLength = (100, 50) angle = 0 startAngle = 0 endAngle = 360 # Red color in BGRcolor = (0, 0, 255) # Line thickness of 5 pxthickness = 5 # Using cv2.ellipse() method# Draw a ellipse with red line borders of thickness of 5 pximage = cv2.ellipse(image, center_coordinates, axesLength, angle, startAngle, endAngle, color, thickness) # Displaying the image cv2.imshow(window_name, image) Output: Example #2:Using thickness of -1 px and rotation of 30 degrees. # Python program to explain cv2.ellipse() method # importing cv2import cv2 # pathpath = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png' # Reading an image in default modeimage = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' center_coordinates = (120, 100) axesLength = (100, 50) angle = 30 startAngle = 0 endAngle = 360 # Blue color in BGRcolor = (255, 0, 0) # Line thickness of -1 pxthickness = -1 # Using cv2.ellipse() method# Draw a ellipse with blue line borders of thickness of -1 pximage = cv2.ellipse(image, center_coordinates, axesLength, angle, startAngle, endAngle, color, thickness) # Displaying the imagecv2.imshow(window_name, image) Output: Image-Processing OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Aug, 2019" }, { "code": null, "e": 179, "s": 28, "text": "OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.ellipse() method is used to draw a ellipse on any image." }, { "code": null, "e": 308, "s": 179, "text": "Syntax: cv2.ellipse(image, centerCoordinates, axesLength, angle, startAngle, endAngle, color [, thickness[, lineType[, shift]]])" }, { "code": null, "e": 1274, "s": 308, "text": "Parameters:image: It is the image on which ellipse is to be drawn.centerCoordinates: It is the center coordinates of ellipse. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).axesLength: It contains tuple of two variables containing major and minor axis of ellipse (major axis length, minor axis length).angle: Ellipse rotation angle in degrees.startAngle: Starting angle of the elliptic arc in degrees.endAngle: Ending angle of the elliptic arc in degrees.color: It is the color of border line of shape to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color.thickness: It is the thickness of the shape border line in px. Thickness of -1 px will fill the shape by the specified color.lineType: This is an optional parameter.It gives the type of the ellipse boundary.shift: This is an optional parameter. It denotes the number of fractional bits in the coordinates of the center and values of axes." }, { "code": null, "e": 1309, "s": 1274, "text": "Return Value: It returns an image." }, { "code": null, "e": 1348, "s": 1309, "text": "Image used for all the below examples:" }, { "code": null, "e": 1360, "s": 1348, "text": "Example #1:" }, { "code": "# Python program to explain cv2.ellipse() method # importing cv2 import cv2 # path path = r'C:\\Users\\Rajnish\\Desktop\\geeksforgeeks\\geeks.png' # Reading an image in default modeimage = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' center_coordinates = (120, 100) axesLength = (100, 50) angle = 0 startAngle = 0 endAngle = 360 # Red color in BGRcolor = (0, 0, 255) # Line thickness of 5 pxthickness = 5 # Using cv2.ellipse() method# Draw a ellipse with red line borders of thickness of 5 pximage = cv2.ellipse(image, center_coordinates, axesLength, angle, startAngle, endAngle, color, thickness) # Displaying the image cv2.imshow(window_name, image) ", "e": 2081, "s": 1360, "text": null }, { "code": null, "e": 2089, "s": 2081, "text": "Output:" }, { "code": null, "e": 2153, "s": 2089, "text": "Example #2:Using thickness of -1 px and rotation of 30 degrees." }, { "code": "# Python program to explain cv2.ellipse() method # importing cv2import cv2 # pathpath = r'C:\\Users\\Rajnish\\Desktop\\geeksforgeeks\\geeks.png' # Reading an image in default modeimage = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' center_coordinates = (120, 100) axesLength = (100, 50) angle = 30 startAngle = 0 endAngle = 360 # Blue color in BGRcolor = (255, 0, 0) # Line thickness of -1 pxthickness = -1 # Using cv2.ellipse() method# Draw a ellipse with blue line borders of thickness of -1 pximage = cv2.ellipse(image, center_coordinates, axesLength, angle, startAngle, endAngle, color, thickness) # Displaying the imagecv2.imshow(window_name, image) ", "e": 2890, "s": 2153, "text": null }, { "code": null, "e": 2898, "s": 2890, "text": "Output:" }, { "code": null, "e": 2915, "s": 2898, "text": "Image-Processing" }, { "code": null, "e": 2922, "s": 2915, "text": "OpenCV" }, { "code": null, "e": 2929, "s": 2922, "text": "Python" } ]
Recursive Tower of Hanoi using 4 pegs / rods
18 Aug, 2020 Tower of Hanoi is a mathematical puzzle. Traditionally, It consists of three poles and a number of disks of different sizes which can slide onto any poles. The puzzle starts with the disk in a neat stack in ascending order of size in one pole, the smallest at the top thus making a conical shape. The objective of the puzzle is to move all the disks from one pole (say ‘source pole’) to another pole (say ‘destination pole’) with the help of third pole (say auxiliary pole). The puzzle has the following two rules: 1. You can’t place a larger disk onto smaller disk2. Only one disk can be moved at a time We’ve already discussed recursive solution for Tower of Hanoi with time complexity O(2^n). Using 4 rods, same approach shows significant decrease in time complexity. Examples: Input : 3 Output : Move disk 1 from rod A to rod B Move disk 2 from rod A to rod C Move disk 3 from rod A to rod D Move disk 2 from rod C to rod D Move disk 1 from rod B to rod D Input : 5 Output : Move disk 1 from rod A to rod C Move disk 2 from rod A to rod D Move disk 3 from rod A to rod B Move disk 2 from rod D to rod B Move disk 1 from rod C to rod B Move disk 4 from rod A to rod C Move disk 5 from rod A to rod D Move disk 4 from rod C to rod D Move disk 1 from rod B to rod A Move disk 2 from rod B to rod C Move disk 3 from rod B to rod D Move disk 2 from rod C to rod D Move disk 1 from rod A to rod D C++ // C++ Recursive program for Tower of Hanoi#include using namespace std;// Recursive function to solve Tower// of Hanoi puzzlevoid towerOfHanoi(int n, char from_rod, char to_rod,char aux_rod1, char aux_rod2){if (n == 0)return;if (n == 1){cout << "\n Move disk" < // Recursive program for Tower of Hanoi#include // Recursive function to solve Tower// of Hanoi puzzlevoid towerOfHanoi(int n, char from_rod, char to_rod,char aux_rod1, char aux_rod2){if (n == 0)return;if (n == 1) {printf(“\n Move disk %d from rod %c to rod %c”,n, from_rod, to_rod);return;}towerOfHanoi(n – 2, from_rod, aux_rod1, aux_rod2,to_rod);printf(“\n Move disk %d from rod %c to rod %c “,n – 1, from_rod, aux_rod2);printf(“\n Move disk %d from rod %c to rod %c “,n, from_rod, to_rod);printf(“\n Move disk %d from rod %c to rod %c “,n – 1, aux_rod2, to_rod);towerOfHanoi(n – 2, aux_rod1, to_rod, from_rod,aux_rod2);}// driver programint main(){int n = 4; // Number of disks// A, B, C and D are names of rodstowerOfHanoi(n, ‘A’, ‘D’, ‘B’, ‘C’);return 0;} // Recursive function to solve Tower// of Hanoi puzzlevoid towerOfHanoi(int n, char from_rod, char to_rod,char aux_rod1, char aux_rod2){if (n == 0)return;if (n == 1) {printf(“\n Move disk %d from rod %c to rod %c”,n, from_rod, to_rod);return;} towerOfHanoi(n – 2, from_rod, aux_rod1, aux_rod2,to_rod);printf(“\n Move disk %d from rod %c to rod %c “,n – 1, from_rod, aux_rod2);printf(“\n Move disk %d from rod %c to rod %c “,n, from_rod, to_rod);printf(“\n Move disk %d from rod %c to rod %c “,n – 1, aux_rod2, to_rod);towerOfHanoi(n – 2, aux_rod1, to_rod, from_rod,aux_rod2);} // driver programint main(){int n = 4; // Number of disks // A, B, C and D are names of rodstowerOfHanoi(n, ‘A’, ‘D’, ‘B’, ‘C’);return 0;} // Recursive program for Tower of Hanoipublic class GFG {// recursive function to solve// Tower of Hanoi puzzlestatic void towerOfHanoi(int n, char from_rod,char to_rod, char aux_rod1,char aux_rod2){if (n == 0)return;if (n == 1) {System.out.println(“Move disk ” + n +” from rod ” + from_rod +” to rod ” + to_rod);return;}towerOfHanoi(n – 2, from_rod, aux_rod1, aux_rod2,to_rod);System.out.println(“Move disk ” + (n – 1) +” from rod ” + from_rod +” to rod ” + aux_rod2);System.out.println(“Move disk ” + n +” from rod ” + from_rod +” to rod ” + to_rod);System.out.println(“Move disk ” + (n – 1) +” from rod ” + aux_rod2 +” to rod ” + to_rod);towerOfHanoi(n – 2, aux_rod1, to_rod, from_rod,aux_rod2);}// Driver methodpublic static void main(String args[]){int n = 4; // Number of disks// A, B, C and D are names of rodstowerOfHanoi(n, ‘A’, ‘D’, ‘B’, ‘C’);}} // recursive function to solve// Tower of Hanoi puzzlestatic void towerOfHanoi(int n, char from_rod,char to_rod, char aux_rod1,char aux_rod2){if (n == 0)return;if (n == 1) {System.out.println(“Move disk ” + n +” from rod ” + from_rod +” to rod ” + to_rod);return;} towerOfHanoi(n – 2, from_rod, aux_rod1, aux_rod2,to_rod);System.out.println(“Move disk ” + (n – 1) +” from rod ” + from_rod +” to rod ” + aux_rod2);System.out.println(“Move disk ” + n +” from rod ” + from_rod +” to rod ” + to_rod);System.out.println(“Move disk ” + (n – 1) +” from rod ” + aux_rod2 +” to rod ” + to_rod);towerOfHanoi(n – 2, aux_rod1, to_rod, from_rod,aux_rod2);} // Driver methodpublic static void main(String args[]){int n = 4; // Number of disks // A, B, C and D are names of rodstowerOfHanoi(n, ‘A’, ‘D’, ‘B’, ‘C’);}} # Recursive program for Tower of Hanoi# Recursive function to solve Tower# of Hanoi puzzledef towerOfHanoi(n, from_rod, to_rod, aux_rod1,aux_rod2):if (n == 0):returnif (n == 1):print(“Move disk”, n, “from rod”,from_rod, “c to rod”, to_rod)returntowerOfHanoi(n – 2, from_rod, aux_rod1,aux_rod2, to_rod)print(“Move disk”, n-1, “from rod”, from_rod,“c to rod”, aux_rod2)print(“Move disk”, n, “from rod”, from_rod,“c to rod”, to_rod)print(“Move disk”, n-1, “from rod”, aux_rod2,“c to rod”, to_rod)towerOfHanoi(n – 2, aux_rod1, to_rod,from_rod, aux_rod2)# driver programn = 4 # Number of disks# A, B, C and D are names of rodstowerOfHanoi(n, ‘A’, ‘D’, ‘B’, ‘C’)# This code is contributed by Smitha. # Recursive function to solve Tower# of Hanoi puzzledef towerOfHanoi(n, from_rod, to_rod, aux_rod1,aux_rod2): if (n == 0):returnif (n == 1):print(“Move disk”, n, “from rod”,from_rod, “c to rod”, to_rod)return towerOfHanoi(n – 2, from_rod, aux_rod1,aux_rod2, to_rod)print(“Move disk”, n-1, “from rod”, from_rod,“c to rod”, aux_rod2) print(“Move disk”, n, “from rod”, from_rod,“c to rod”, to_rod) print(“Move disk”, n-1, “from rod”, aux_rod2,“c to rod”, to_rod) towerOfHanoi(n – 2, aux_rod1, to_rod,from_rod, aux_rod2) # driver programn = 4 # Number of disks # A, B, C and D are names of rodstowerOfHanoi(n, ‘A’, ‘D’, ‘B’, ‘C’) # This code is contributed by Smitha. // Recursive program for Tower of Hanoiusing System;public class GFG {// recursive function to solve// Tower of Hanoi puzzlestatic void towerOfHanoi(int n, char from_rod,char to_rod, char aux_rod1,char aux_rod2){if (n == 0)return;if (n == 1) {Console.WriteLine(“Move disk ” + n +” from rod ” + from_rod +” to rod ” + to_rod);return;}towerOfHanoi(n – 2, from_rod, aux_rod1,aux_rod2, to_rod);Console.WriteLine(“Move disk ” + (n – 1)+ ” from rod ” + from_rod+ ” to rod ” + aux_rod2);Console.WriteLine(“Move disk ” + n +” from rod ” + from_rod+ ” to rod ” + to_rod);Console.WriteLine(“Move disk ” + (n – 1)+ ” from rod ” + aux_rod2+ ” to rod ” + to_rod);towerOfHanoi(n – 2, aux_rod1, to_rod,from_rod, aux_rod2);}// Driver methodpublic static void Main(){int n = 4; // Number of disks// A, B, C and D are names of rodstowerOfHanoi(n, ‘A’, ‘D’, ‘B’, ‘C’);}}// This code is contributed by Anant Agarwal. public class GFG { // recursive function to solve// Tower of Hanoi puzzlestatic void towerOfHanoi(int n, char from_rod,char to_rod, char aux_rod1,char aux_rod2){if (n == 0)return;if (n == 1) {Console.WriteLine(“Move disk ” + n +” from rod ” + from_rod +” to rod ” + to_rod);return;} towerOfHanoi(n – 2, from_rod, aux_rod1,aux_rod2, to_rod);Console.WriteLine(“Move disk ” + (n – 1)+ ” from rod ” + from_rod+ ” to rod ” + aux_rod2);Console.WriteLine(“Move disk ” + n +” from rod ” + from_rod+ ” to rod ” + to_rod);Console.WriteLine(“Move disk ” + (n – 1)+ ” from rod ” + aux_rod2+ ” to rod ” + to_rod);towerOfHanoi(n – 2, aux_rod1, to_rod,from_rod, aux_rod2);} // Driver methodpublic static void Main(){int n = 4; // Number of disks // A, B, C and D are names of rodstowerOfHanoi(n, ‘A’, ‘D’, ‘B’, ‘C’);}} // This code is contributed by Anant Agarwal. Move disk 1 from rod A to rod D Move disk 2 from rod A to rod B Move disk 1 from rod D to rod B Move disk 3 from rod A to rod C Move disk 4 from rod A to rod D Move disk 3 from rod C to rod D Move disk 1 from rod B to rod C Move disk 2 from rod B to rod D Move disk 1 from rod C to rod D Time Complexity: O(2^(N/2)) This article contributed by madHEYsia. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Smitha Dinesh Semwal jit_t SHUBHAMSINGH10 Arkapravo Ghosh Recursion Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Aug, 2020" }, { "code": null, "e": 527, "s": 52, "text": "Tower of Hanoi is a mathematical puzzle. Traditionally, It consists of three poles and a number of disks of different sizes which can slide onto any poles. The puzzle starts with the disk in a neat stack in ascending order of size in one pole, the smallest at the top thus making a conical shape. The objective of the puzzle is to move all the disks from one pole (say ‘source pole’) to another pole (say ‘destination pole’) with the help of third pole (say auxiliary pole)." }, { "code": null, "e": 567, "s": 527, "text": "The puzzle has the following two rules:" }, { "code": null, "e": 657, "s": 567, "text": "1. You can’t place a larger disk onto smaller disk2. Only one disk can be moved at a time" }, { "code": null, "e": 823, "s": 657, "text": "We’ve already discussed recursive solution for Tower of Hanoi with time complexity O(2^n). Using 4 rods, same approach shows significant decrease in time complexity." }, { "code": null, "e": 833, "s": 823, "text": "Examples:" }, { "code": null, "e": 1450, "s": 833, "text": "Input : 3\nOutput :\nMove disk 1 from rod A to rod B\nMove disk 2 from rod A to rod C\nMove disk 3 from rod A to rod D\nMove disk 2 from rod C to rod D\nMove disk 1 from rod B to rod D\n\nInput : 5\nOutput : \nMove disk 1 from rod A to rod C\nMove disk 2 from rod A to rod D\nMove disk 3 from rod A to rod B\nMove disk 2 from rod D to rod B\nMove disk 1 from rod C to rod B\nMove disk 4 from rod A to rod C\nMove disk 5 from rod A to rod D\nMove disk 4 from rod C to rod D\nMove disk 1 from rod B to rod A\nMove disk 2 from rod B to rod C\nMove disk 3 from rod B to rod D\nMove disk 2 from rod C to rod D\nMove disk 1 from rod A to rod D\n" }, { "code": null, "e": 1454, "s": 1450, "text": "C++" }, { "code": "// C++ Recursive program for Tower of Hanoi#include using namespace std;// Recursive function to solve Tower// of Hanoi puzzlevoid towerOfHanoi(int n, char from_rod, char to_rod,char aux_rod1, char aux_rod2){if (n == 0)return;if (n == 1){cout << \"\\n Move disk\" <", "e": 1717, "s": 1454, "text": null }, { "code": "// Recursive program for Tower of Hanoi#include // Recursive function to solve Tower// of Hanoi puzzlevoid towerOfHanoi(int n, char from_rod, char to_rod,char aux_rod1, char aux_rod2){if (n == 0)return;if (n == 1) {printf(“\\n Move disk %d from rod %c to rod %c”,n, from_rod, to_rod);return;}towerOfHanoi(n – 2, from_rod, aux_rod1, aux_rod2,to_rod);printf(“\\n Move disk %d from rod %c to rod %c “,n – 1, from_rod, aux_rod2);printf(“\\n Move disk %d from rod %c to rod %c “,n, from_rod, to_rod);printf(“\\n Move disk %d from rod %c to rod %c “,n – 1, aux_rod2, to_rod);towerOfHanoi(n – 2, aux_rod1, to_rod, from_rod,aux_rod2);}// driver programint main(){int n = 4; // Number of disks// A, B, C and D are names of rodstowerOfHanoi(n, ‘A’, ‘D’, ‘B’, ‘C’);return 0;}", "e": 2478, "s": 1717, "text": null }, { "code": null, "e": 2722, "s": 2478, "text": "// Recursive function to solve Tower// of Hanoi puzzlevoid towerOfHanoi(int n, char from_rod, char to_rod,char aux_rod1, char aux_rod2){if (n == 0)return;if (n == 1) {printf(“\\n Move disk %d from rod %c to rod %c”,n, from_rod, to_rod);return;}" }, { "code": null, "e": 3055, "s": 2722, "text": "towerOfHanoi(n – 2, from_rod, aux_rod1, aux_rod2,to_rod);printf(“\\n Move disk %d from rod %c to rod %c “,n – 1, from_rod, aux_rod2);printf(“\\n Move disk %d from rod %c to rod %c “,n, from_rod, to_rod);printf(“\\n Move disk %d from rod %c to rod %c “,n – 1, aux_rod2, to_rod);towerOfHanoi(n – 2, aux_rod1, to_rod, from_rod,aux_rod2);}" }, { "code": null, "e": 3113, "s": 3055, "text": "// driver programint main(){int n = 4; // Number of disks" }, { "code": null, "e": 3194, "s": 3113, "text": "// A, B, C and D are names of rodstowerOfHanoi(n, ‘A’, ‘D’, ‘B’, ‘C’);return 0;}" }, { "code": "// Recursive program for Tower of Hanoipublic class GFG {// recursive function to solve// Tower of Hanoi puzzlestatic void towerOfHanoi(int n, char from_rod,char to_rod, char aux_rod1,char aux_rod2){if (n == 0)return;if (n == 1) {System.out.println(“Move disk ” + n +” from rod ” + from_rod +” to rod ” + to_rod);return;}towerOfHanoi(n – 2, from_rod, aux_rod1, aux_rod2,to_rod);System.out.println(“Move disk ” + (n – 1) +” from rod ” + from_rod +” to rod ” + aux_rod2);System.out.println(“Move disk ” + n +” from rod ” + from_rod +” to rod ” + to_rod);System.out.println(“Move disk ” + (n – 1) +” from rod ” + aux_rod2 +” to rod ” + to_rod);towerOfHanoi(n – 2, aux_rod1, to_rod, from_rod,aux_rod2);}// Driver methodpublic static void main(String args[]){int n = 4; // Number of disks// A, B, C and D are names of rodstowerOfHanoi(n, ‘A’, ‘D’, ‘B’, ‘C’);}}", "e": 4050, "s": 3194, "text": null }, { "code": null, "e": 4315, "s": 4050, "text": "// recursive function to solve// Tower of Hanoi puzzlestatic void towerOfHanoi(int n, char from_rod,char to_rod, char aux_rod1,char aux_rod2){if (n == 0)return;if (n == 1) {System.out.println(“Move disk ” + n +” from rod ” + from_rod +” to rod ” + to_rod);return;}" }, { "code": null, "e": 4694, "s": 4315, "text": "towerOfHanoi(n – 2, from_rod, aux_rod1, aux_rod2,to_rod);System.out.println(“Move disk ” + (n – 1) +” from rod ” + from_rod +” to rod ” + aux_rod2);System.out.println(“Move disk ” + n +” from rod ” + from_rod +” to rod ” + to_rod);System.out.println(“Move disk ” + (n – 1) +” from rod ” + aux_rod2 +” to rod ” + to_rod);towerOfHanoi(n – 2, aux_rod1, to_rod, from_rod,aux_rod2);}" }, { "code": null, "e": 4779, "s": 4694, "text": "// Driver methodpublic static void main(String args[]){int n = 4; // Number of disks" }, { "code": null, "e": 4852, "s": 4779, "text": "// A, B, C and D are names of rodstowerOfHanoi(n, ‘A’, ‘D’, ‘B’, ‘C’);}}" }, { "code": "# Recursive program for Tower of Hanoi# Recursive function to solve Tower# of Hanoi puzzledef towerOfHanoi(n, from_rod, to_rod, aux_rod1,aux_rod2):if (n == 0):returnif (n == 1):print(“Move disk”, n, “from rod”,from_rod, “c to rod”, to_rod)returntowerOfHanoi(n – 2, from_rod, aux_rod1,aux_rod2, to_rod)print(“Move disk”, n-1, “from rod”, from_rod,“c to rod”, aux_rod2)print(“Move disk”, n, “from rod”, from_rod,“c to rod”, to_rod)print(“Move disk”, n-1, “from rod”, aux_rod2,“c to rod”, to_rod)towerOfHanoi(n – 2, aux_rod1, to_rod,from_rod, aux_rod2)# driver programn = 4 # Number of disks# A, B, C and D are names of rodstowerOfHanoi(n, ‘A’, ‘D’, ‘B’, ‘C’)# This code is contributed by Smitha.", "e": 5546, "s": 4852, "text": null }, { "code": null, "e": 5656, "s": 5546, "text": "# Recursive function to solve Tower# of Hanoi puzzledef towerOfHanoi(n, from_rod, to_rod, aux_rod1,aux_rod2):" }, { "code": null, "e": 5755, "s": 5656, "text": "if (n == 0):returnif (n == 1):print(“Move disk”, n, “from rod”,from_rod, “c to rod”, to_rod)return" }, { "code": null, "e": 5878, "s": 5755, "text": "towerOfHanoi(n – 2, from_rod, aux_rod1,aux_rod2, to_rod)print(“Move disk”, n-1, “from rod”, from_rod,“c to rod”, aux_rod2)" }, { "code": null, "e": 5941, "s": 5878, "text": "print(“Move disk”, n, “from rod”, from_rod,“c to rod”, to_rod)" }, { "code": null, "e": 6006, "s": 5941, "text": "print(“Move disk”, n-1, “from rod”, aux_rod2,“c to rod”, to_rod)" }, { "code": null, "e": 6063, "s": 6006, "text": "towerOfHanoi(n – 2, aux_rod1, to_rod,from_rod, aux_rod2)" }, { "code": null, "e": 6103, "s": 6063, "text": "# driver programn = 4 # Number of disks" }, { "code": null, "e": 6172, "s": 6103, "text": "# A, B, C and D are names of rodstowerOfHanoi(n, ‘A’, ‘D’, ‘B’, ‘C’)" }, { "code": null, "e": 6210, "s": 6172, "text": "# This code is contributed by Smitha." }, { "code": "// Recursive program for Tower of Hanoiusing System;public class GFG {// recursive function to solve// Tower of Hanoi puzzlestatic void towerOfHanoi(int n, char from_rod,char to_rod, char aux_rod1,char aux_rod2){if (n == 0)return;if (n == 1) {Console.WriteLine(“Move disk ” + n +” from rod ” + from_rod +” to rod ” + to_rod);return;}towerOfHanoi(n – 2, from_rod, aux_rod1,aux_rod2, to_rod);Console.WriteLine(“Move disk ” + (n – 1)+ ” from rod ” + from_rod+ ” to rod ” + aux_rod2);Console.WriteLine(“Move disk ” + n +” from rod ” + from_rod+ ” to rod ” + to_rod);Console.WriteLine(“Move disk ” + (n – 1)+ ” from rod ” + aux_rod2+ ” to rod ” + to_rod);towerOfHanoi(n – 2, aux_rod1, to_rod,from_rod, aux_rod2);}// Driver methodpublic static void Main(){int n = 4; // Number of disks// A, B, C and D are names of rodstowerOfHanoi(n, ‘A’, ‘D’, ‘B’, ‘C’);}}// This code is contributed by Anant Agarwal.", "e": 7107, "s": 6210, "text": null }, { "code": null, "e": 7126, "s": 7107, "text": "public class GFG {" }, { "code": null, "e": 7390, "s": 7126, "text": "// recursive function to solve// Tower of Hanoi puzzlestatic void towerOfHanoi(int n, char from_rod,char to_rod, char aux_rod1,char aux_rod2){if (n == 0)return;if (n == 1) {Console.WriteLine(“Move disk ” + n +” from rod ” + from_rod +” to rod ” + to_rod);return;}" }, { "code": null, "e": 7766, "s": 7390, "text": "towerOfHanoi(n – 2, from_rod, aux_rod1,aux_rod2, to_rod);Console.WriteLine(“Move disk ” + (n – 1)+ ” from rod ” + from_rod+ ” to rod ” + aux_rod2);Console.WriteLine(“Move disk ” + n +” from rod ” + from_rod+ ” to rod ” + to_rod);Console.WriteLine(“Move disk ” + (n – 1)+ ” from rod ” + aux_rod2+ ” to rod ” + to_rod);towerOfHanoi(n – 2, aux_rod1, to_rod,from_rod, aux_rod2);}" }, { "code": null, "e": 7838, "s": 7766, "text": "// Driver methodpublic static void Main(){int n = 4; // Number of disks" }, { "code": null, "e": 7911, "s": 7838, "text": "// A, B, C and D are names of rodstowerOfHanoi(n, ‘A’, ‘D’, ‘B’, ‘C’);}}" }, { "code": null, "e": 7957, "s": 7911, "text": "// This code is contributed by Anant Agarwal." }, { "code": null, "e": 8246, "s": 7957, "text": "Move disk 1 from rod A to rod D\nMove disk 2 from rod A to rod B\nMove disk 1 from rod D to rod B\nMove disk 3 from rod A to rod C\nMove disk 4 from rod A to rod D\nMove disk 3 from rod C to rod D\nMove disk 1 from rod B to rod C\nMove disk 2 from rod B to rod D\nMove disk 1 from rod C to rod D\n" }, { "code": null, "e": 8274, "s": 8246, "text": "Time Complexity: O(2^(N/2))" }, { "code": null, "e": 8568, "s": 8274, "text": "This article contributed by madHEYsia. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 8693, "s": 8568, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 8714, "s": 8693, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 8720, "s": 8714, "text": "jit_t" }, { "code": null, "e": 8735, "s": 8720, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 8751, "s": 8735, "text": "Arkapravo Ghosh" }, { "code": null, "e": 8761, "s": 8751, "text": "Recursion" }, { "code": null, "e": 8771, "s": 8761, "text": "Recursion" } ]
Shortest path with exactly k edges in a directed and weighted graph
23 Jun, 2022 Given a directed and two vertices ‘u’ and ‘v’ in it, find shortest path from ‘u’ to ‘v’ with exactly k edges on the path. The graph is given as adjacency matrix representation where value of graph[i][j] indicates the weight of an edge from vertex i to vertex j and a value INF(infinite) indicates no edge from i to j. For example, consider the following graph. Let source ‘u’ be vertex 0, destination ‘v’ be 3 and k be 2. There are two walks of length 2, the walks are {0, 2, 3} and {0, 1, 3}. The shortest among the two is {0, 2, 3} and weight of path is 3+6 = 9. The idea is to browse through all paths of length k from u to v using the approach discussed in the previous post and return weight of the shortest path. A simple solution is to start from u, go to all adjacent vertices, and recur for adjacent vertices with k as k-1, source as adjacent vertex and destination as v. Following are C++ and Java implementations of this simple solution. C++ Java Python3 C# Javascript // C++ program to find shortest path with exactly k edges#include <bits/stdc++.h>using namespace std; // Define number of vertices in the graph and infinite value#define V 4#define INF INT_MAX // A naive recursive function to count walks from u to v with k edgesint shortestPath(int graph[][V], int u, int v, int k){ // Base cases if (k == 0 && u == v) return 0; if (k == 1 && graph[u][v] != INF) return graph[u][v]; if (k <= 0) return INF; // Initialize result int res = INF; // Go to all adjacents of u and recur for (int i = 0; i < V; i++) { if (graph[u][i] != INF && u != i && v != i) { int rec_res = shortestPath(graph, i, v, k-1); if (rec_res != INF) res = min(res, graph[u][i] + rec_res); } } return res;} // driver program to test above functionint main(){ /* Let us create the graph shown in above diagram*/ int graph[V][V] = { {0, 10, 3, 2}, {INF, 0, INF, 7}, {INF, INF, 0, 6}, {INF, INF, INF, 0} }; int u = 0, v = 3, k = 2; cout << "Weight of the shortest path is " << shortestPath(graph, u, v, k); return 0;} // Dynamic Programming based Java program to find shortest path// with exactly k edgesimport java.util.*;import java.lang.*;import java.io.*; class ShortestPath{ // Define number of vertices in the graph and infinite value static final int V = 4; static final int INF = Integer.MAX_VALUE; // A naive recursive function to count walks from u to v // with k edges int shortestPath(int graph[][], int u, int v, int k) { // Base cases if (k == 0 && u == v) return 0; if (k == 1 && graph[u][v] != INF) return graph[u][v]; if (k <= 0) return INF; // Initialize result int res = INF; // Go to all adjacents of u and recur for (int i = 0; i < V; i++) { if (graph[u][i] != INF && u != i && v != i) { int rec_res = shortestPath(graph, i, v, k-1); if (rec_res != INF) res = Math.min(res, graph[u][i] + rec_res); } } return res; } public static void main (String[] args) { /* Let us create the graph shown in above diagram*/ int graph[][] = new int[][]{ {0, 10, 3, 2}, {INF, 0, INF, 7}, {INF, INF, 0, 6}, {INF, INF, INF, 0} }; ShortestPath t = new ShortestPath(); int u = 0, v = 3, k = 2; System.out.println("Weight of the shortest path is "+ t.shortestPath(graph, u, v, k)); }} # Python3 program to find shortest path# with exactly k edges # Define number of vertices in the graph# and infinite value # A naive recursive function to count# walks from u to v with k edgesdef shortestPath(graph, u, v, k): V = 4 INF = 999999999999 # Base cases if k == 0 and u == v: return 0 if k == 1 and graph[u][v] != INF: return graph[u][v] if k <= 0: return INF # Initialize result res = INF # Go to all adjacents of u and recur for i in range(V): if graph[u][i] != INF and u != i and v != i: rec_res = shortestPath(graph, i, v, k - 1) if rec_res != INF: res = min(res, graph[u][i] + rec_res) return res # Driver Codeif __name__ == '__main__': INF = 999999999999 # Let us create the graph shown # in above diagram graph = [[0, 10, 3, 2], [INF, 0, INF, 7], [INF, INF, 0, 6], [INF, INF, INF, 0]] u = 0 v = 3 k = 2 print("Weight of the shortest path is", shortestPath(graph, u, v, k)) # This code is contributed by PranchalK // Dynamic Programming based C# program to// find shortest pathwith exactly k edgesusing System; class GFG{ // Define number of vertices in the// graph and infinite valueconst int V = 4;const int INF = Int32.MaxValue; // A naive recursive function to count// walks from u to v with k edgesint shortestPath(int[,] graph, int u, int v, int k){ // Base cases if (k == 0 && u == v) return 0; if (k == 1 && graph[u, v] != INF) return graph[u, v]; if (k <= 0) return INF; // Initialize result int res = INF; // Go to all adjacents of u and recur for (int i = 0; i < V; i++) { if (graph[u, i] != INF && u != i && v != i) { int rec_res = shortestPath(graph, i, v, k - 1); if (rec_res != INF) res = Math.Min(res, graph[u, i] + rec_res); } } return res;} // Driver Codepublic static void Main (){ /* Let us create the graph shown in above diagram*/ int[,] graph = new int[,]{{0, 10, 3, 2}, {INF, 0, INF, 7}, {INF, INF, 0, 6}, {INF, INF, INF, 0}}; GFG t = new GFG(); int u = 0, v = 3, k = 2; Console.WriteLine("Weight of the shortest path is "+ t.shortestPath(graph, u, v, k));}} // This code is contributed by Akanksha Rai <script> // Dynamic Programming based Javascript// program to find shortest path// with exactly k edges // Define number of vertices in the graph and infinite valuelet V = 4;let INF = Number.MAX_VALUE; // A naive recursive function to count walks from u to v// with k edgesfunction shortestPath(graph,u,v,k){ // Base cases if (k == 0 && u == v) return 0; if (k == 1 && graph[u][v] != INF) return graph[u][v]; if (k <= 0) return INF; // Initialize result let res = INF; // Go to all adjacents of u and recur for (let i = 0; i < V; i++) { if (graph[u][i] != INF && u != i && v != i) { let rec_res = shortestPath(graph, i, v, k-1); if (rec_res != INF) res = Math.min(res, graph[u][i] + rec_res); } } return res;} let graph=[[0, 10, 3, 2],[INF, 0, INF, 7], [INF, INF, 0, 6],[INF, INF, INF, 0]]; let u = 0, v = 3, k = 2;document.write("Weight of the shortest path is "+ shortestPath(graph, u, v, k)); // This code is contributed by rag2127 </script> Weight of the shortest path is 9 The worst-case time complexity of the above function is O(Vk) where V is the number of vertices in the given graph. We can simply analyze the time complexity by drawing recursion tree. The worst occurs for a complete graph. In worst case, every internal node of recursion tree would have exactly V children. We can optimize the above solution using Dynamic Programming. The idea is to build a 3D table where first dimension is source, second dimension is destination, third dimension is number of edges from source to destination, and the value is the weight of the shortest path having exactly the number of edges, stored in the third dimension, from source to destination. Like other Dynamic Programming problems, we fill the 3D table in bottom-up manner. C++ Java Python3 C# Javascript // Dynamic Programming based C++ program to find shortest path with// exactly k edges#include <iostream>#include <climits>using namespace std; // Define number of vertices in the graph and infinite value#define V 4#define INF INT_MAX // A Dynamic programming based function to find the shortest path from// u to v with exactly k edges.int shortestPath(int graph[][V], int u, int v, int k){ // Table to be filled up using DP. The value sp[i][j][e] will store // weight of the shortest path from i to j with exactly k edges int sp[V][V][k+1]; // Loop for number of edges from 0 to k for (int e = 0; e <= k; e++) { for (int i = 0; i < V; i++) // for source { for (int j = 0; j < V; j++) // for destination { // initialize value sp[i][j][e] = INF; // from base cases if (e == 0 && i == j) sp[i][j][e] = 0; if (e == 1 && graph[i][j] != INF) sp[i][j][e] = graph[i][j]; //go to adjacent only when number of edges is more than 1 if (e > 1) { for (int a = 0; a < V; a++) { // There should be an edge from i to a and a // should not be same as either i or j if (graph[i][a] != INF && i != a && j!= a && sp[a][j][e-1] != INF) sp[i][j][e] = min(sp[i][j][e], graph[i][a] + sp[a][j][e-1]); } } } } } return sp[u][v][k];} // driver program to test above functionint main(){ /* Let us create the graph shown in above diagram*/ int graph[V][V] = { {0, 10, 3, 2}, {INF, 0, INF, 7}, {INF, INF, 0, 6}, {INF, INF, INF, 0} }; int u = 0, v = 3, k = 2; cout << shortestPath(graph, u, v, k); return 0;} // Dynamic Programming based Java program to find shortest path with// exactly k edgesimport java.util.*;import java.lang.*;import java.io.*; class ShortestPath{ // Define number of vertices in the graph and infinite value static final int V = 4; static final int INF = Integer.MAX_VALUE; // A Dynamic programming based function to find the shortest path // from u to v with exactly k edges. int shortestPath(int graph[][], int u, int v, int k) { // Table to be filled up using DP. The value sp[i][j][e] will // store weight of the shortest path from i to j with exactly // k edges int sp[][][] = new int[V][V][k+1]; // Loop for number of edges from 0 to k for (int e = 0; e <= k; e++) { for (int i = 0; i < V; i++) // for source { for (int j = 0; j < V; j++) // for destination { // initialize value sp[i][j][e] = INF; // from base cases if (e == 0 && i == j) sp[i][j][e] = 0; if (e == 1 && graph[i][j] != INF) sp[i][j][e] = graph[i][j]; // go to adjacent only when number of edges is // more than 1 if (e > 1) { for (int a = 0; a < V; a++) { // There should be an edge from i to a and // a should not be same as either i or j if (graph[i][a] != INF && i != a && j!= a && sp[a][j][e-1] != INF) sp[i][j][e] = Math.min(sp[i][j][e], graph[i][a] + sp[a][j][e-1]); } } } } } return sp[u][v][k]; } public static void main (String[] args) { /* Let us create the graph shown in above diagram*/ int graph[][] = new int[][]{ {0, 10, 3, 2}, {INF, 0, INF, 7}, {INF, INF, 0, 6}, {INF, INF, INF, 0} }; ShortestPath t = new ShortestPath(); int u = 0, v = 3, k = 2; System.out.println("Weight of the shortest path is "+ t.shortestPath(graph, u, v, k)); }}//This code is contributed by Aakash Hasija # Dynamic Programming based Python3# program to find shortest path with # A Dynamic programming based function# to find the shortest path from u to v# with exactly k edges.def shortestPath(graph, u, v, k): global V, INF # Table to be filled up using DP. The # value sp[i][j][e] will store weight # of the shortest path from i to j # with exactly k edges sp = [[None] * V for i in range(V)] for i in range(V): for j in range(V): sp[i][j] = [None] * (k + 1) # Loop for number of edges from 0 to k for e in range(k + 1): for i in range(V): # for source for j in range(V): # for destination # initialize value sp[i][j][e] = INF # from base cases if (e == 0 and i == j): sp[i][j][e] = 0 if (e == 1 and graph[i][j] != INF): sp[i][j][e] = graph[i][j] # go to adjacent only when number # of edges is more than 1 if (e > 1): for a in range(V): # There should be an edge from # i to a and a should not be # same as either i or j if (graph[i][a] != INF and i != a and j!= a and sp[a][j][e - 1] != INF): sp[i][j][e] = min(sp[i][j][e], graph[i][a] + sp[a][j][e - 1]) return sp[u][v][k] # Driver Code # Define number of vertices in# the graph and infinite valueV = 4INF = 999999999999 # Let us create the graph shown# in above diagramgraph = [[0, 10, 3, 2], [INF, 0, INF, 7], [INF, INF, 0, 6], [INF, INF, INF, 0]]u = 0v = 3k = 2print("Weight of the shortest path is", shortestPath(graph, u, v, k)) # This code is contributed by PranchalK // Dynamic Programming based C# program to find// shortest path with exactly k edgesusing System; class GFG{ // Define number of vertices in the graph// and infinite valuestatic readonly int V = 4;static readonly int INF = int.MaxValue; // A Dynamic programming based function to// find the shortest path from u to v// with exactly k edges.int shortestPath(int [,]graph, int u, int v, int k){ // Table to be filled up using DP. The value // sp[i][j][e] will store weight of the shortest // path from i to j with exactly k edges int [,,]sp = new int[V, V, k + 1]; // Loop for number of edges from 0 to k for (int e = 0; e <= k; e++) { for (int i = 0; i < V; i++) // for source { for (int j = 0; j < V; j++) // for destination { // initialize value sp[i, j, e] = INF; // from base cases if (e == 0 && i == j) sp[i, j, e] = 0; if (e == 1 && graph[i, j] != INF) sp[i, j, e] = graph[i, j]; // go to adjacent only when number of // edges is more than 1 if (e > 1) { for (int a = 0; a < V; a++) { // There should be an edge from i to a and // a should not be same as either i or j if (graph[i, a] != INF && i != a && j!= a && sp[a, j, e - 1] != INF) sp[i, j, e] = Math.Min(sp[i, j, e], graph[i, a] + sp[a, j, e - 1]); } } } } } return sp[u, v, k];} // Driver Codepublic static void Main(String[] args){ /* Let us create the graph shown in above diagram*/ int [,]graph = new int[,]{ {0, 10, 3, 2}, {INF, 0, INF, 7}, {INF, INF, 0, 6}, {INF, INF, INF, 0} }; GFG t = new GFG(); int u = 0, v = 3, k = 2; Console.WriteLine("Weight of the shortest path is "+ t.shortestPath(graph, u, v, k));}} // This code is contributed by 29AjayKumar <script>// Dynamic Programming based Javascript program to find shortest path with// exactly k edges // Define number of vertices in the graph and infinite valuelet V = 4;let INF = Number.MAX_VALUE; // A Dynamic programming based function to find the shortest path // from u to v with exactly k edges.function shortestPath(graph, u, v, k){ // Table to be filled up using DP. The value sp[i][j][e] will // store weight of the shortest path from i to j with exactly // k edges let sp = new Array(V); for(let i = 0; i < V; i++) { sp[i] = new Array(V); for(let j = 0; j < V; j++) { sp[i][j] = new Array(k + 1); for(let l = 0; l < (k + 1); l++) { sp[i][j][l] = 0; } } } // Loop for number of edges from 0 to k for (let e = 0; e <= k; e++) { for (let i = 0; i < V; i++) // for source { for (let j = 0; j < V; j++) // for destination { // initialize value sp[i][j][e] = INF; // from base cases if (e == 0 && i == j) sp[i][j][e] = 0; if (e == 1 && graph[i][j] != INF) sp[i][j][e] = graph[i][j]; // go to adjacent only when number of edges is // more than 1 if (e > 1) { for (let a = 0; a < V; a++) { // There should be an edge from i to a and // a should not be same as either i or j if (graph[i][a] != INF && i != a && j!= a && sp[a][j][e-1] != INF) sp[i][j][e] = Math.min(sp[i][j][e], graph[i][a] + sp[a][j][e-1]); } } } } } return sp[u][v][k];} let graph = [[0, 10, 3, 2], [INF, 0, INF, 7], [INF, INF, 0, 6], [INF, INF, INF, 0]];let u = 0, v = 3, k = 2;document.write("Weight of the shortest path is "+ shortestPath(graph, u, v, k)); // This code is contributed by avanitrachhadiya2155</script> 9 Time complexity of the above DP-based solution is O(V3K) which is much better than the naive solution. 29AjayKumar PranchalKatiyar Akanksha_Rai rag2127 avanitrachhadiya2155 anikakapoor eternalLearner hardikkoriintern Shortest Path Dynamic Programming Graph Dynamic Programming Graph Shortest Path Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 174, "s": 52, "text": "Given a directed and two vertices ‘u’ and ‘v’ in it, find shortest path from ‘u’ to ‘v’ with exactly k edges on the path." }, { "code": null, "e": 370, "s": 174, "text": "The graph is given as adjacency matrix representation where value of graph[i][j] indicates the weight of an edge from vertex i to vertex j and a value INF(infinite) indicates no edge from i to j." }, { "code": null, "e": 617, "s": 370, "text": "For example, consider the following graph. Let source ‘u’ be vertex 0, destination ‘v’ be 3 and k be 2. There are two walks of length 2, the walks are {0, 2, 3} and {0, 1, 3}. The shortest among the two is {0, 2, 3} and weight of path is 3+6 = 9." }, { "code": null, "e": 1002, "s": 617, "text": "The idea is to browse through all paths of length k from u to v using the approach discussed in the previous post and return weight of the shortest path. A simple solution is to start from u, go to all adjacent vertices, and recur for adjacent vertices with k as k-1, source as adjacent vertex and destination as v. Following are C++ and Java implementations of this simple solution. " }, { "code": null, "e": 1006, "s": 1002, "text": "C++" }, { "code": null, "e": 1011, "s": 1006, "text": "Java" }, { "code": null, "e": 1019, "s": 1011, "text": "Python3" }, { "code": null, "e": 1022, "s": 1019, "text": "C#" }, { "code": null, "e": 1033, "s": 1022, "text": "Javascript" }, { "code": "// C++ program to find shortest path with exactly k edges#include <bits/stdc++.h>using namespace std; // Define number of vertices in the graph and infinite value#define V 4#define INF INT_MAX // A naive recursive function to count walks from u to v with k edgesint shortestPath(int graph[][V], int u, int v, int k){ // Base cases if (k == 0 && u == v) return 0; if (k == 1 && graph[u][v] != INF) return graph[u][v]; if (k <= 0) return INF; // Initialize result int res = INF; // Go to all adjacents of u and recur for (int i = 0; i < V; i++) { if (graph[u][i] != INF && u != i && v != i) { int rec_res = shortestPath(graph, i, v, k-1); if (rec_res != INF) res = min(res, graph[u][i] + rec_res); } } return res;} // driver program to test above functionint main(){ /* Let us create the graph shown in above diagram*/ int graph[V][V] = { {0, 10, 3, 2}, {INF, 0, INF, 7}, {INF, INF, 0, 6}, {INF, INF, INF, 0} }; int u = 0, v = 3, k = 2; cout << \"Weight of the shortest path is \" << shortestPath(graph, u, v, k); return 0;}", "e": 2278, "s": 1033, "text": null }, { "code": "// Dynamic Programming based Java program to find shortest path// with exactly k edgesimport java.util.*;import java.lang.*;import java.io.*; class ShortestPath{ // Define number of vertices in the graph and infinite value static final int V = 4; static final int INF = Integer.MAX_VALUE; // A naive recursive function to count walks from u to v // with k edges int shortestPath(int graph[][], int u, int v, int k) { // Base cases if (k == 0 && u == v) return 0; if (k == 1 && graph[u][v] != INF) return graph[u][v]; if (k <= 0) return INF; // Initialize result int res = INF; // Go to all adjacents of u and recur for (int i = 0; i < V; i++) { if (graph[u][i] != INF && u != i && v != i) { int rec_res = shortestPath(graph, i, v, k-1); if (rec_res != INF) res = Math.min(res, graph[u][i] + rec_res); } } return res; } public static void main (String[] args) { /* Let us create the graph shown in above diagram*/ int graph[][] = new int[][]{ {0, 10, 3, 2}, {INF, 0, INF, 7}, {INF, INF, 0, 6}, {INF, INF, INF, 0} }; ShortestPath t = new ShortestPath(); int u = 0, v = 3, k = 2; System.out.println(\"Weight of the shortest path is \"+ t.shortestPath(graph, u, v, k)); }}", "e": 3878, "s": 2278, "text": null }, { "code": "# Python3 program to find shortest path# with exactly k edges # Define number of vertices in the graph# and infinite value # A naive recursive function to count# walks from u to v with k edgesdef shortestPath(graph, u, v, k): V = 4 INF = 999999999999 # Base cases if k == 0 and u == v: return 0 if k == 1 and graph[u][v] != INF: return graph[u][v] if k <= 0: return INF # Initialize result res = INF # Go to all adjacents of u and recur for i in range(V): if graph[u][i] != INF and u != i and v != i: rec_res = shortestPath(graph, i, v, k - 1) if rec_res != INF: res = min(res, graph[u][i] + rec_res) return res # Driver Codeif __name__ == '__main__': INF = 999999999999 # Let us create the graph shown # in above diagram graph = [[0, 10, 3, 2], [INF, 0, INF, 7], [INF, INF, 0, 6], [INF, INF, INF, 0]] u = 0 v = 3 k = 2 print(\"Weight of the shortest path is\", shortestPath(graph, u, v, k)) # This code is contributed by PranchalK", "e": 4983, "s": 3878, "text": null }, { "code": "// Dynamic Programming based C# program to// find shortest pathwith exactly k edgesusing System; class GFG{ // Define number of vertices in the// graph and infinite valueconst int V = 4;const int INF = Int32.MaxValue; // A naive recursive function to count// walks from u to v with k edgesint shortestPath(int[,] graph, int u, int v, int k){ // Base cases if (k == 0 && u == v) return 0; if (k == 1 && graph[u, v] != INF) return graph[u, v]; if (k <= 0) return INF; // Initialize result int res = INF; // Go to all adjacents of u and recur for (int i = 0; i < V; i++) { if (graph[u, i] != INF && u != i && v != i) { int rec_res = shortestPath(graph, i, v, k - 1); if (rec_res != INF) res = Math.Min(res, graph[u, i] + rec_res); } } return res;} // Driver Codepublic static void Main (){ /* Let us create the graph shown in above diagram*/ int[,] graph = new int[,]{{0, 10, 3, 2}, {INF, 0, INF, 7}, {INF, INF, 0, 6}, {INF, INF, INF, 0}}; GFG t = new GFG(); int u = 0, v = 3, k = 2; Console.WriteLine(\"Weight of the shortest path is \"+ t.shortestPath(graph, u, v, k));}} // This code is contributed by Akanksha Rai", "e": 6362, "s": 4983, "text": null }, { "code": "<script> // Dynamic Programming based Javascript// program to find shortest path// with exactly k edges // Define number of vertices in the graph and infinite valuelet V = 4;let INF = Number.MAX_VALUE; // A naive recursive function to count walks from u to v// with k edgesfunction shortestPath(graph,u,v,k){ // Base cases if (k == 0 && u == v) return 0; if (k == 1 && graph[u][v] != INF) return graph[u][v]; if (k <= 0) return INF; // Initialize result let res = INF; // Go to all adjacents of u and recur for (let i = 0; i < V; i++) { if (graph[u][i] != INF && u != i && v != i) { let rec_res = shortestPath(graph, i, v, k-1); if (rec_res != INF) res = Math.min(res, graph[u][i] + rec_res); } } return res;} let graph=[[0, 10, 3, 2],[INF, 0, INF, 7], [INF, INF, 0, 6],[INF, INF, INF, 0]]; let u = 0, v = 3, k = 2;document.write(\"Weight of the shortest path is \"+ shortestPath(graph, u, v, k)); // This code is contributed by rag2127 </script>", "e": 7539, "s": 6362, "text": null }, { "code": null, "e": 7572, "s": 7539, "text": "Weight of the shortest path is 9" }, { "code": null, "e": 7881, "s": 7572, "text": "The worst-case time complexity of the above function is O(Vk) where V is the number of vertices in the given graph. We can simply analyze the time complexity by drawing recursion tree. The worst occurs for a complete graph. In worst case, every internal node of recursion tree would have exactly V children. " }, { "code": null, "e": 8331, "s": 7881, "text": "We can optimize the above solution using Dynamic Programming. The idea is to build a 3D table where first dimension is source, second dimension is destination, third dimension is number of edges from source to destination, and the value is the weight of the shortest path having exactly the number of edges, stored in the third dimension, from source to destination. Like other Dynamic Programming problems, we fill the 3D table in bottom-up manner." }, { "code": null, "e": 8335, "s": 8331, "text": "C++" }, { "code": null, "e": 8340, "s": 8335, "text": "Java" }, { "code": null, "e": 8348, "s": 8340, "text": "Python3" }, { "code": null, "e": 8351, "s": 8348, "text": "C#" }, { "code": null, "e": 8362, "s": 8351, "text": "Javascript" }, { "code": "// Dynamic Programming based C++ program to find shortest path with// exactly k edges#include <iostream>#include <climits>using namespace std; // Define number of vertices in the graph and infinite value#define V 4#define INF INT_MAX // A Dynamic programming based function to find the shortest path from// u to v with exactly k edges.int shortestPath(int graph[][V], int u, int v, int k){ // Table to be filled up using DP. The value sp[i][j][e] will store // weight of the shortest path from i to j with exactly k edges int sp[V][V][k+1]; // Loop for number of edges from 0 to k for (int e = 0; e <= k; e++) { for (int i = 0; i < V; i++) // for source { for (int j = 0; j < V; j++) // for destination { // initialize value sp[i][j][e] = INF; // from base cases if (e == 0 && i == j) sp[i][j][e] = 0; if (e == 1 && graph[i][j] != INF) sp[i][j][e] = graph[i][j]; //go to adjacent only when number of edges is more than 1 if (e > 1) { for (int a = 0; a < V; a++) { // There should be an edge from i to a and a // should not be same as either i or j if (graph[i][a] != INF && i != a && j!= a && sp[a][j][e-1] != INF) sp[i][j][e] = min(sp[i][j][e], graph[i][a] + sp[a][j][e-1]); } } } } } return sp[u][v][k];} // driver program to test above functionint main(){ /* Let us create the graph shown in above diagram*/ int graph[V][V] = { {0, 10, 3, 2}, {INF, 0, INF, 7}, {INF, INF, 0, 6}, {INF, INF, INF, 0} }; int u = 0, v = 3, k = 2; cout << shortestPath(graph, u, v, k); return 0;}", "e": 10432, "s": 8362, "text": null }, { "code": "// Dynamic Programming based Java program to find shortest path with// exactly k edgesimport java.util.*;import java.lang.*;import java.io.*; class ShortestPath{ // Define number of vertices in the graph and infinite value static final int V = 4; static final int INF = Integer.MAX_VALUE; // A Dynamic programming based function to find the shortest path // from u to v with exactly k edges. int shortestPath(int graph[][], int u, int v, int k) { // Table to be filled up using DP. The value sp[i][j][e] will // store weight of the shortest path from i to j with exactly // k edges int sp[][][] = new int[V][V][k+1]; // Loop for number of edges from 0 to k for (int e = 0; e <= k; e++) { for (int i = 0; i < V; i++) // for source { for (int j = 0; j < V; j++) // for destination { // initialize value sp[i][j][e] = INF; // from base cases if (e == 0 && i == j) sp[i][j][e] = 0; if (e == 1 && graph[i][j] != INF) sp[i][j][e] = graph[i][j]; // go to adjacent only when number of edges is // more than 1 if (e > 1) { for (int a = 0; a < V; a++) { // There should be an edge from i to a and // a should not be same as either i or j if (graph[i][a] != INF && i != a && j!= a && sp[a][j][e-1] != INF) sp[i][j][e] = Math.min(sp[i][j][e], graph[i][a] + sp[a][j][e-1]); } } } } } return sp[u][v][k]; } public static void main (String[] args) { /* Let us create the graph shown in above diagram*/ int graph[][] = new int[][]{ {0, 10, 3, 2}, {INF, 0, INF, 7}, {INF, INF, 0, 6}, {INF, INF, INF, 0} }; ShortestPath t = new ShortestPath(); int u = 0, v = 3, k = 2; System.out.println(\"Weight of the shortest path is \"+ t.shortestPath(graph, u, v, k)); }}//This code is contributed by Aakash Hasija", "e": 12992, "s": 10432, "text": null }, { "code": "# Dynamic Programming based Python3# program to find shortest path with # A Dynamic programming based function# to find the shortest path from u to v# with exactly k edges.def shortestPath(graph, u, v, k): global V, INF # Table to be filled up using DP. The # value sp[i][j][e] will store weight # of the shortest path from i to j # with exactly k edges sp = [[None] * V for i in range(V)] for i in range(V): for j in range(V): sp[i][j] = [None] * (k + 1) # Loop for number of edges from 0 to k for e in range(k + 1): for i in range(V): # for source for j in range(V): # for destination # initialize value sp[i][j][e] = INF # from base cases if (e == 0 and i == j): sp[i][j][e] = 0 if (e == 1 and graph[i][j] != INF): sp[i][j][e] = graph[i][j] # go to adjacent only when number # of edges is more than 1 if (e > 1): for a in range(V): # There should be an edge from # i to a and a should not be # same as either i or j if (graph[i][a] != INF and i != a and j!= a and sp[a][j][e - 1] != INF): sp[i][j][e] = min(sp[i][j][e], graph[i][a] + sp[a][j][e - 1]) return sp[u][v][k] # Driver Code # Define number of vertices in# the graph and infinite valueV = 4INF = 999999999999 # Let us create the graph shown# in above diagramgraph = [[0, 10, 3, 2], [INF, 0, INF, 7], [INF, INF, 0, 6], [INF, INF, INF, 0]]u = 0v = 3k = 2print(\"Weight of the shortest path is\", shortestPath(graph, u, v, k)) # This code is contributed by PranchalK", "e": 14955, "s": 12992, "text": null }, { "code": "// Dynamic Programming based C# program to find// shortest path with exactly k edgesusing System; class GFG{ // Define number of vertices in the graph// and infinite valuestatic readonly int V = 4;static readonly int INF = int.MaxValue; // A Dynamic programming based function to// find the shortest path from u to v// with exactly k edges.int shortestPath(int [,]graph, int u, int v, int k){ // Table to be filled up using DP. The value // sp[i][j][e] will store weight of the shortest // path from i to j with exactly k edges int [,,]sp = new int[V, V, k + 1]; // Loop for number of edges from 0 to k for (int e = 0; e <= k; e++) { for (int i = 0; i < V; i++) // for source { for (int j = 0; j < V; j++) // for destination { // initialize value sp[i, j, e] = INF; // from base cases if (e == 0 && i == j) sp[i, j, e] = 0; if (e == 1 && graph[i, j] != INF) sp[i, j, e] = graph[i, j]; // go to adjacent only when number of // edges is more than 1 if (e > 1) { for (int a = 0; a < V; a++) { // There should be an edge from i to a and // a should not be same as either i or j if (graph[i, a] != INF && i != a && j!= a && sp[a, j, e - 1] != INF) sp[i, j, e] = Math.Min(sp[i, j, e], graph[i, a] + sp[a, j, e - 1]); } } } } } return sp[u, v, k];} // Driver Codepublic static void Main(String[] args){ /* Let us create the graph shown in above diagram*/ int [,]graph = new int[,]{ {0, 10, 3, 2}, {INF, 0, INF, 7}, {INF, INF, 0, 6}, {INF, INF, INF, 0} }; GFG t = new GFG(); int u = 0, v = 3, k = 2; Console.WriteLine(\"Weight of the shortest path is \"+ t.shortestPath(graph, u, v, k));}} // This code is contributed by 29AjayKumar", "e": 17207, "s": 14955, "text": null }, { "code": "<script>// Dynamic Programming based Javascript program to find shortest path with// exactly k edges // Define number of vertices in the graph and infinite valuelet V = 4;let INF = Number.MAX_VALUE; // A Dynamic programming based function to find the shortest path // from u to v with exactly k edges.function shortestPath(graph, u, v, k){ // Table to be filled up using DP. The value sp[i][j][e] will // store weight of the shortest path from i to j with exactly // k edges let sp = new Array(V); for(let i = 0; i < V; i++) { sp[i] = new Array(V); for(let j = 0; j < V; j++) { sp[i][j] = new Array(k + 1); for(let l = 0; l < (k + 1); l++) { sp[i][j][l] = 0; } } } // Loop for number of edges from 0 to k for (let e = 0; e <= k; e++) { for (let i = 0; i < V; i++) // for source { for (let j = 0; j < V; j++) // for destination { // initialize value sp[i][j][e] = INF; // from base cases if (e == 0 && i == j) sp[i][j][e] = 0; if (e == 1 && graph[i][j] != INF) sp[i][j][e] = graph[i][j]; // go to adjacent only when number of edges is // more than 1 if (e > 1) { for (let a = 0; a < V; a++) { // There should be an edge from i to a and // a should not be same as either i or j if (graph[i][a] != INF && i != a && j!= a && sp[a][j][e-1] != INF) sp[i][j][e] = Math.min(sp[i][j][e], graph[i][a] + sp[a][j][e-1]); } } } } } return sp[u][v][k];} let graph = [[0, 10, 3, 2], [INF, 0, INF, 7], [INF, INF, 0, 6], [INF, INF, INF, 0]];let u = 0, v = 3, k = 2;document.write(\"Weight of the shortest path is \"+ shortestPath(graph, u, v, k)); // This code is contributed by avanitrachhadiya2155</script>", "e": 19615, "s": 17207, "text": null }, { "code": null, "e": 19617, "s": 19615, "text": "9" }, { "code": null, "e": 19720, "s": 19617, "text": "Time complexity of the above DP-based solution is O(V3K) which is much better than the naive solution." }, { "code": null, "e": 19732, "s": 19720, "text": "29AjayKumar" }, { "code": null, "e": 19748, "s": 19732, "text": "PranchalKatiyar" }, { "code": null, "e": 19761, "s": 19748, "text": "Akanksha_Rai" }, { "code": null, "e": 19769, "s": 19761, "text": "rag2127" }, { "code": null, "e": 19790, "s": 19769, "text": "avanitrachhadiya2155" }, { "code": null, "e": 19802, "s": 19790, "text": "anikakapoor" }, { "code": null, "e": 19817, "s": 19802, "text": "eternalLearner" }, { "code": null, "e": 19834, "s": 19817, "text": "hardikkoriintern" }, { "code": null, "e": 19848, "s": 19834, "text": "Shortest Path" }, { "code": null, "e": 19868, "s": 19848, "text": "Dynamic Programming" }, { "code": null, "e": 19874, "s": 19868, "text": "Graph" }, { "code": null, "e": 19894, "s": 19874, "text": "Dynamic Programming" }, { "code": null, "e": 19900, "s": 19894, "text": "Graph" }, { "code": null, "e": 19914, "s": 19900, "text": "Shortest Path" } ]
Number of connected components of a graph ( using Disjoint Set Union )
28 Jun, 2022 Given an undirected graph G with vertices numbered in the range [0, N] and an array Edges[][] consisting of M edges, the task is to find the total number of connected components in the graph using Disjoint Set Union algorithm. Examples: Input: N = 4, Edges[][] = {{1, 0}, {2, 3}, {3, 4}}Output: 2Explanation: There are only 2 connected components as shown below: Input: N = 4, Edges[][] = {{1, 0}, {0, 2}, {3, 5}, {3, 4}, {6, 7}}Output: 3Explanation: There are only 3 connected components as shown below: Approach: The problem can be solved using Disjoint Set Union algorithm. Follow the steps below to solve the problem: In DSU algorithm, there are two main functions, i.e. connect() and root() function. connect(): Connects an edge. root(): Recursively determine the topmost parent of a given edge. For each edge {a, b}, check if a is connected to b or not. If found to be false, connect them by appending their top parents. After completing the above step for every edge, print the total number of the distinct top-most parents for each vertex. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Stores the parent of each vertexint parent[1000000]; // Function to find the topmost// parent of vertex aint root(int a){ // If current vertex is // the topmost vertex if (a == parent[a]) { return a; } // Otherwise, set topmost vertex of // its parent as its topmost vertex return parent[a] = root(parent[a]);} // Function to connect the component// having vertex a with the component// having vertex bvoid connect(int a, int b){ // Connect edges a = root(a); b = root(b); if (a != b) { parent[b] = a; }} // Function to find unique top most parentsvoid connectedComponents(int n){ set<int> s; // Traverse all vertices for (int i = 0; i < n; i++) { // Insert all topmost // vertices obtained s.insert(root(parent[i])); } // Print count of connected components cout << s.size() << '\n';} // Function to print answervoid printAnswer(int N, vector<vector<int> > edges){ // Setting parent to itself for (int i = 0; i <= N; i++) { parent[i] = i; } // Traverse all edges for (int i = 0; i < edges.size(); i++) { connect(edges[i][0], edges[i][1]); } // Print answer connectedComponents(N);} // Driver Codeint main(){ // Given N int N = 8; // Given edges vector<vector<int> > edges = { { 1, 0 }, { 0, 2 }, { 5, 3 }, { 3, 4 }, { 6, 7 } }; // Function call printAnswer(N, edges); return 0;} // Java program for the above approachimport java.util.*;class GFG{ // Stores the parent of each vertexstatic int []parent = new int[1000000]; // Function to find the topmost// parent of vertex astatic int root(int a){ // If current vertex is // the topmost vertex if (a == parent[a]) { return a; } // Otherwise, set topmost vertex of // its parent as its topmost vertex return parent[a] = root(parent[a]);} // Function to connect the component// having vertex a with the component// having vertex bstatic void connect(int a, int b){ // Connect edges a = root(a); b = root(b); if (a != b) { parent[b] = a; }} // Function to find unique top most parentsstatic void connectedComponents(int n){ HashSet<Integer> s = new HashSet<Integer>(); // Traverse all vertices for (int i = 0; i < n; i++) { // Insert all topmost // vertices obtained s.add(parent[i]); } // Print count of connected components System.out.println(s.size());} // Function to print answerstatic void printAnswer(int N,int [][] edges){ // Setting parent to itself for (int i = 0; i <= N; i++) { parent[i] = i; } // Traverse all edges for (int i = 0; i < edges.length; i++) { connect(edges[i][0], edges[i][1]); } // Print answer connectedComponents(N);} // Driver Codepublic static void main(String[] args){ // Given N int N = 8; // Given edges int [][]edges = {{ 1, 0 }, { 0, 2 }, { 5, 3 }, { 3, 4 }, { 6, 7 }}; // Function call printAnswer(N, edges);}} // This code is contributed by 29AjayKumar # Python3 program for the above approachfrom collections import defaultdict# Given NN = 8 # Given edgesedges = [[1, 0 ], [ 0, 2 ], [ 5, 3 ], [ 3, 4 ], [ 6, 7 ]] # Stores the parent of each vertexparent = list(range(N)) # Function to find the topmost# parent of vertex xdef find(x): if x != parent[x]: parent[x] = find(parent[x]) return parent[x] def union(x,y): parent_x = find(x) parent_y = find(y) if parent_x != parent_y: parent[parent_y] = parent_x for x,y in edges: union(x,y) dict_pair = defaultdict(list) for idx, val in enumerate(parent): dict_pair[find(val)].append(idx) print(len(dict_pair.keys())) # This code is contributed by Shivam Dwivedi // C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Stores the parent of each vertex static int[] parent = new int[1000000]; // Function to find the topmost // parent of vertex a static int root(int a) { // If current vertex is // the topmost vertex if (a == parent[a]) { return a; } // Otherwise, set topmost vertex of // its parent as its topmost vertex return parent[a] = root(parent[a]); } // Function to connect the component // having vertex a with the component // having vertex b static void connect(int a, int b) { // Connect edges a = root(a); b = root(b); if (a != b) { parent[b] = a; } } // Function to find unique top most parents static void connectedComponents(int n) { HashSet<int> s = new HashSet<int>(); // Traverse all vertices for (int i = 0; i < n; i++) { // Insert all topmost // vertices obtained s.Add(parent[i]); } // Print count of connected components Console.WriteLine(s.Count); } // Function to print answer static void printAnswer(int N, List<List<int> > edges) { // Setting parent to itself for (int i = 0; i <= N; i++) { parent[i] = i; } // Traverse all edges for (int i = 0; i < edges.Count; i++) { connect(edges[i][0], edges[i][1]); } // Print answer connectedComponents(N); } // Driver code static void Main() { // Given N int N = 8; // Given edges List<List<int>> edges = new List<List<int>>(); edges.Add(new List<int> { 1, 0 }); edges.Add(new List<int> { 0, 2 }); edges.Add(new List<int> { 5, 3 }); edges.Add(new List<int> { 3, 4 }); edges.Add(new List<int> { 6, 7 }); // Function call printAnswer(N, edges); }} // This code is contributed by divyeshrabadiya07 <script> // Javascript program for the above approach // Stores the parent of each vertexvar parent = Array(1000000); // Function to find the topmost// parent of vertex afunction root(a){ // If current vertex is // the topmost vertex if (a == parent[a]) { return a; } // Otherwise, set topmost vertex of // its parent as its topmost vertex return parent[a] = root(parent[a]);} // Function to connect the component// having vertex a with the component// having vertex bfunction connect( a, b){ // Connect edges a = root(a); b = root(b); if (a != b) { parent[b] = a; }} // Function to find unique top most parentsfunction connectedComponents( n){ var s = new Set(); // Traverse all vertices for (var i = 0; i < n; i++) { // Insert all topmost // vertices obtained s.add(parent[i]); } // Print count of connected components document.write( s.size + "<br>");} // Function to print answerfunction printAnswer( N, edges){ // Setting parent to itself for (var i = 0; i <= N; i++) { parent[i] = i; } // Traverse all edges for (var i = 0; i < edges.length; i++) { connect(edges[i][0], edges[i][1]); } // Print answer connectedComponents(N);} // Driver Code// Given Nvar N = 8;// Given edgesvar edges = [ [ 1, 0 ], [ 0, 2 ], [ 5, 3 ], [ 3, 4 ], [ 6, 7 ]]; // Function callprintAnswer(N, edges); </script> 3 Time Complexity: O(NLOGN+M)Auxiliary Space: O(N+M) divyeshrabadiya07 29AjayKumar divyesh072019 itsok saksham29 kirushikesh surinderdawra388 shivampandit lezirtin connected-components cpp-set disjoint-set Graph Hash Searching Searching Hash Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2022" }, { "code": null, "e": 279, "s": 52, "text": "Given an undirected graph G with vertices numbered in the range [0, N] and an array Edges[][] consisting of M edges, the task is to find the total number of connected components in the graph using Disjoint Set Union algorithm." }, { "code": null, "e": 289, "s": 279, "text": "Examples:" }, { "code": null, "e": 415, "s": 289, "text": "Input: N = 4, Edges[][] = {{1, 0}, {2, 3}, {3, 4}}Output: 2Explanation: There are only 2 connected components as shown below:" }, { "code": null, "e": 557, "s": 415, "text": "Input: N = 4, Edges[][] = {{1, 0}, {0, 2}, {3, 5}, {3, 4}, {6, 7}}Output: 3Explanation: There are only 3 connected components as shown below:" }, { "code": null, "e": 674, "s": 557, "text": "Approach: The problem can be solved using Disjoint Set Union algorithm. Follow the steps below to solve the problem:" }, { "code": null, "e": 758, "s": 674, "text": "In DSU algorithm, there are two main functions, i.e. connect() and root() function." }, { "code": null, "e": 787, "s": 758, "text": "connect(): Connects an edge." }, { "code": null, "e": 853, "s": 787, "text": "root(): Recursively determine the topmost parent of a given edge." }, { "code": null, "e": 979, "s": 853, "text": "For each edge {a, b}, check if a is connected to b or not. If found to be false, connect them by appending their top parents." }, { "code": null, "e": 1100, "s": 979, "text": "After completing the above step for every edge, print the total number of the distinct top-most parents for each vertex." }, { "code": null, "e": 1151, "s": 1100, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1155, "s": 1151, "text": "C++" }, { "code": null, "e": 1160, "s": 1155, "text": "Java" }, { "code": null, "e": 1168, "s": 1160, "text": "Python3" }, { "code": null, "e": 1171, "s": 1168, "text": "C#" }, { "code": null, "e": 1182, "s": 1171, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Stores the parent of each vertexint parent[1000000]; // Function to find the topmost// parent of vertex aint root(int a){ // If current vertex is // the topmost vertex if (a == parent[a]) { return a; } // Otherwise, set topmost vertex of // its parent as its topmost vertex return parent[a] = root(parent[a]);} // Function to connect the component// having vertex a with the component// having vertex bvoid connect(int a, int b){ // Connect edges a = root(a); b = root(b); if (a != b) { parent[b] = a; }} // Function to find unique top most parentsvoid connectedComponents(int n){ set<int> s; // Traverse all vertices for (int i = 0; i < n; i++) { // Insert all topmost // vertices obtained s.insert(root(parent[i])); } // Print count of connected components cout << s.size() << '\\n';} // Function to print answervoid printAnswer(int N, vector<vector<int> > edges){ // Setting parent to itself for (int i = 0; i <= N; i++) { parent[i] = i; } // Traverse all edges for (int i = 0; i < edges.size(); i++) { connect(edges[i][0], edges[i][1]); } // Print answer connectedComponents(N);} // Driver Codeint main(){ // Given N int N = 8; // Given edges vector<vector<int> > edges = { { 1, 0 }, { 0, 2 }, { 5, 3 }, { 3, 4 }, { 6, 7 } }; // Function call printAnswer(N, edges); return 0;}", "e": 2733, "s": 1182, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Stores the parent of each vertexstatic int []parent = new int[1000000]; // Function to find the topmost// parent of vertex astatic int root(int a){ // If current vertex is // the topmost vertex if (a == parent[a]) { return a; } // Otherwise, set topmost vertex of // its parent as its topmost vertex return parent[a] = root(parent[a]);} // Function to connect the component// having vertex a with the component// having vertex bstatic void connect(int a, int b){ // Connect edges a = root(a); b = root(b); if (a != b) { parent[b] = a; }} // Function to find unique top most parentsstatic void connectedComponents(int n){ HashSet<Integer> s = new HashSet<Integer>(); // Traverse all vertices for (int i = 0; i < n; i++) { // Insert all topmost // vertices obtained s.add(parent[i]); } // Print count of connected components System.out.println(s.size());} // Function to print answerstatic void printAnswer(int N,int [][] edges){ // Setting parent to itself for (int i = 0; i <= N; i++) { parent[i] = i; } // Traverse all edges for (int i = 0; i < edges.length; i++) { connect(edges[i][0], edges[i][1]); } // Print answer connectedComponents(N);} // Driver Codepublic static void main(String[] args){ // Given N int N = 8; // Given edges int [][]edges = {{ 1, 0 }, { 0, 2 }, { 5, 3 }, { 3, 4 }, { 6, 7 }}; // Function call printAnswer(N, edges);}} // This code is contributed by 29AjayKumar", "e": 4406, "s": 2733, "text": null }, { "code": "# Python3 program for the above approachfrom collections import defaultdict# Given NN = 8 # Given edgesedges = [[1, 0 ], [ 0, 2 ], [ 5, 3 ], [ 3, 4 ], [ 6, 7 ]] # Stores the parent of each vertexparent = list(range(N)) # Function to find the topmost# parent of vertex xdef find(x): if x != parent[x]: parent[x] = find(parent[x]) return parent[x] def union(x,y): parent_x = find(x) parent_y = find(y) if parent_x != parent_y: parent[parent_y] = parent_x for x,y in edges: union(x,y) dict_pair = defaultdict(list) for idx, val in enumerate(parent): dict_pair[find(val)].append(idx) print(len(dict_pair.keys())) # This code is contributed by Shivam Dwivedi", "e": 5084, "s": 4406, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Stores the parent of each vertex static int[] parent = new int[1000000]; // Function to find the topmost // parent of vertex a static int root(int a) { // If current vertex is // the topmost vertex if (a == parent[a]) { return a; } // Otherwise, set topmost vertex of // its parent as its topmost vertex return parent[a] = root(parent[a]); } // Function to connect the component // having vertex a with the component // having vertex b static void connect(int a, int b) { // Connect edges a = root(a); b = root(b); if (a != b) { parent[b] = a; } } // Function to find unique top most parents static void connectedComponents(int n) { HashSet<int> s = new HashSet<int>(); // Traverse all vertices for (int i = 0; i < n; i++) { // Insert all topmost // vertices obtained s.Add(parent[i]); } // Print count of connected components Console.WriteLine(s.Count); } // Function to print answer static void printAnswer(int N, List<List<int> > edges) { // Setting parent to itself for (int i = 0; i <= N; i++) { parent[i] = i; } // Traverse all edges for (int i = 0; i < edges.Count; i++) { connect(edges[i][0], edges[i][1]); } // Print answer connectedComponents(N); } // Driver code static void Main() { // Given N int N = 8; // Given edges List<List<int>> edges = new List<List<int>>(); edges.Add(new List<int> { 1, 0 }); edges.Add(new List<int> { 0, 2 }); edges.Add(new List<int> { 5, 3 }); edges.Add(new List<int> { 3, 4 }); edges.Add(new List<int> { 6, 7 }); // Function call printAnswer(N, edges); }} // This code is contributed by divyeshrabadiya07", "e": 7190, "s": 5084, "text": null }, { "code": "<script> // Javascript program for the above approach // Stores the parent of each vertexvar parent = Array(1000000); // Function to find the topmost// parent of vertex afunction root(a){ // If current vertex is // the topmost vertex if (a == parent[a]) { return a; } // Otherwise, set topmost vertex of // its parent as its topmost vertex return parent[a] = root(parent[a]);} // Function to connect the component// having vertex a with the component// having vertex bfunction connect( a, b){ // Connect edges a = root(a); b = root(b); if (a != b) { parent[b] = a; }} // Function to find unique top most parentsfunction connectedComponents( n){ var s = new Set(); // Traverse all vertices for (var i = 0; i < n; i++) { // Insert all topmost // vertices obtained s.add(parent[i]); } // Print count of connected components document.write( s.size + \"<br>\");} // Function to print answerfunction printAnswer( N, edges){ // Setting parent to itself for (var i = 0; i <= N; i++) { parent[i] = i; } // Traverse all edges for (var i = 0; i < edges.length; i++) { connect(edges[i][0], edges[i][1]); } // Print answer connectedComponents(N);} // Driver Code// Given Nvar N = 8;// Given edgesvar edges = [ [ 1, 0 ], [ 0, 2 ], [ 5, 3 ], [ 3, 4 ], [ 6, 7 ]]; // Function callprintAnswer(N, edges); </script>", "e": 8624, "s": 7190, "text": null }, { "code": null, "e": 8626, "s": 8624, "text": "3" }, { "code": null, "e": 8677, "s": 8626, "text": "Time Complexity: O(NLOGN+M)Auxiliary Space: O(N+M)" }, { "code": null, "e": 8695, "s": 8677, "text": "divyeshrabadiya07" }, { "code": null, "e": 8707, "s": 8695, "text": "29AjayKumar" }, { "code": null, "e": 8721, "s": 8707, "text": "divyesh072019" }, { "code": null, "e": 8727, "s": 8721, "text": "itsok" }, { "code": null, "e": 8737, "s": 8727, "text": "saksham29" }, { "code": null, "e": 8749, "s": 8737, "text": "kirushikesh" }, { "code": null, "e": 8766, "s": 8749, "text": "surinderdawra388" }, { "code": null, "e": 8779, "s": 8766, "text": "shivampandit" }, { "code": null, "e": 8788, "s": 8779, "text": "lezirtin" }, { "code": null, "e": 8809, "s": 8788, "text": "connected-components" }, { "code": null, "e": 8817, "s": 8809, "text": "cpp-set" }, { "code": null, "e": 8830, "s": 8817, "text": "disjoint-set" }, { "code": null, "e": 8836, "s": 8830, "text": "Graph" }, { "code": null, "e": 8841, "s": 8836, "text": "Hash" }, { "code": null, "e": 8851, "s": 8841, "text": "Searching" }, { "code": null, "e": 8861, "s": 8851, "text": "Searching" }, { "code": null, "e": 8866, "s": 8861, "text": "Hash" }, { "code": null, "e": 8872, "s": 8866, "text": "Graph" } ]
Split a BST into two balanced BSTs based on a value K
10 Feb, 2022 Given a Binary Search tree and an integer K, we have to split the tree into two Balanced Binary Search Tree, where BST-1 consists of all the nodes which are less than K and BST-2 consists of all the nodes which are greater than or equal to K.Note: Arrangement of the nodes may be anything but both BST should be Balanced.Examples: Input: 40 / \ 20 50 / \ \ 10 35 60 / / 25 55 K = 35 Output: First BST: 10 20 25 Second BST: 35 40 50 55 60 Explanation: After splitting above BST about given value K = 35 First Balanced Binary Search Tree is 20 / \ 10 25 Second Balanced Binary Search Tree is 50 / \ 35 55 \ \ 40 60 OR 40 / \ 35 55 / \ 50 60 Input: 100 / \ 20 500 / \ 10 30 \ 40 K = 50 Output: First BST: 10 20 30 40 Second BST: 100 500 Explanation: After splitting above BST about given value K = 50 First Balanced Binary Search Tree is 20 / \ 10 30 \ 40 Second Balanced Binary Search Tree is 100 \ 500 Approach: First store the inorder traversal of given BST in an arrayThen, split this array about given value KNow construct first balanced BST by first splitting part and second BST by second splitting part, using the approach used in this article. First store the inorder traversal of given BST in an array Then, split this array about given value K Now construct first balanced BST by first splitting part and second BST by second splitting part, using the approach used in this article. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to split a BST into// two balanced BSTs based on a value K #include <iostream>using namespace std; // Structure of each node of BSTstruct node { int key; struct node *left, *right;}; // A utility function to// create a new BST nodenode* newNode(int item){ node* temp = new node(); temp->key = item; temp->left = temp->right = NULL; return temp;} // A utility function to insert a new// node with given key in BSTstruct node* insert(struct node* node, int key){ // If the tree is empty, return a new node if (node == NULL) return newNode(key); // Otherwise, recur down the tree if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); // return the (unchanged) node pointer return node;} // Function to return the size// of the treeint sizeOfTree(node* root){ if (root == NULL) { return 0; } // Calculate left size recursively int left = sizeOfTree(root->left); // Calculate right size recursively int right = sizeOfTree(root->right); // Return total size recursively return (left + right + 1);} // Function to store inorder// traversal of BSTvoid storeInorder(node* root, int inOrder[], int& index){ // Base condition if (root == NULL) { return; } // Left recursive call storeInorder(root->left, inOrder, index); // Store elements in inorder array inOrder[index++] = root->key; // Right recursive call storeInorder(root->right, inOrder, index);} // Function to return the splitting// index of the arrayint getSplittingIndex(int inOrder[], int index, int k){ for (int i = 0; i < index; i++) { if (inOrder[i] >= k) { return i - 1; } } return index - 1;} // Function to create the Balanced// Binary search treenode* createBST(int inOrder[], int start, int end){ // Base Condition if (start > end) { return NULL; } // Calculate the mid of the array int mid = (start + end) / 2; node* t = newNode(inOrder[mid]); // Recursive call for left child t->left = createBST(inOrder, start, mid - 1); // Recursive call for right child t->right = createBST(inOrder, mid + 1, end); // Return newly created Balanced // Binary Search Tree return t;} // Function to traverse the tree// in inorder fashionvoid inorderTrav(node* root){ if (root == NULL) return; inorderTrav(root->left); cout << root->key << " "; inorderTrav(root->right);} // Function to split the BST// into two Balanced BSTvoid splitBST(node* root, int k){ // Print the original BST cout << "Original BST : "; if (root != NULL) { inorderTrav(root); } else { cout << "NULL"; } cout << endl; // Store the size of BST1 int numNode = sizeOfTree(root); // Take auxiliary array for storing // The inorder traversal of BST1 int inOrder[numNode + 1]; int index = 0; // Function call for storing // inorder traversal of BST1 storeInorder(root, inOrder, index); // Function call for getting // splitting index int splitIndex = getSplittingIndex(inOrder, index, k); node* root1 = NULL; node* root2 = NULL; // Creation of first Balanced // Binary Search Tree if (splitIndex != -1) root1 = createBST(inOrder, 0, splitIndex); // Creation of Second Balanced // Binary Search Tree if (splitIndex != (index - 1)) root2 = createBST(inOrder, splitIndex + 1, index - 1); // Print two Balanced BSTs cout << "First BST : "; if (root1 != NULL) { inorderTrav(root1); } else { cout << "NULL"; } cout << endl; cout << "Second BST : "; if (root2 != NULL) { inorderTrav(root2); } else { cout << "NULL"; }} // Driver codeint main(){ /* BST 5 / \ 3 7 / \ / \ 2 4 6 8 */ struct node* root = NULL; root = insert(root, 5); insert(root, 3); insert(root, 2); insert(root, 4); insert(root, 7); insert(root, 6); insert(root, 8); int k = 5; // Function to split BST splitBST(root, k); return 0;} // Java program to split a BST into// two balanced BSTs based on a value Kimport java.util.*; class GFG{ // Structure of each node of BST static class node { int key; node left, right; }; static int index; // A utility function to // create a new BST node static node newNode(int item) { node temp = new node(); temp.key = item; temp.left = temp.right = null; return temp; } // A utility function to insert a new // node with given key in BST static node insert(node node, int key) { // If the tree is empty, return a new node if (node == null) return newNode(key); // Otherwise, recur down the tree if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // return the (unchanged) node pointer return node; } // Function to return the size // of the tree static int sizeOfTree(node root) { if (root == null) { return 0; } // Calculate left size recursively int left = sizeOfTree(root.left); // Calculate right size recursively int right = sizeOfTree(root.right); // Return total size recursively return (left + right + 1); } // Function to store inorder // traversal of BST static void storeInorder(node root, int inOrder[]) { // Base condition if (root == null) { return; } // Left recursive call storeInorder(root.left, inOrder); // Store elements in inorder array inOrder[index++] = root.key; // Right recursive call storeInorder(root.right, inOrder); } // Function to return the splitting // index of the array static int getSplittingIndex(int inOrder[], int k) { for (int i = 0; i < index; i++) { if (inOrder[i] >= k) { return i - 1; } } return index - 1; } // Function to create the Balanced // Binary search tree static node createBST(int inOrder[], int start, int end) { // Base Condition if (start > end) { return null; } // Calculate the mid of the array int mid = (start + end) / 2; node t = newNode(inOrder[mid]); // Recursive call for left child t.left = createBST(inOrder, start, mid - 1); // Recursive call for right child t.right = createBST(inOrder, mid + 1, end); // Return newly created Balanced // Binary Search Tree return t; } // Function to traverse the tree // in inorder fashion static void inorderTrav(node root) { if (root == null) return; inorderTrav(root.left); System.out.print(root.key+ " "); inorderTrav(root.right); } // Function to split the BST // into two Balanced BST static void splitBST(node root, int k) { // Print the original BST System.out.print("Original BST : "); if (root != null) { inorderTrav(root); } else { System.out.print("null"); } System.out.println(); // Store the size of BST1 int numNode = sizeOfTree(root); // Take auxiliary array for storing // The inorder traversal of BST1 int []inOrder = new int[numNode + 1]; index = 0; // Function call for storing // inorder traversal of BST1 storeInorder(root, inOrder); // Function call for getting // splitting index int splitIndex = getSplittingIndex(inOrder, k); node root1 = null; node root2 = null; // Creation of first Balanced // Binary Search Tree if (splitIndex != -1) root1 = createBST(inOrder, 0, splitIndex); // Creation of Second Balanced // Binary Search Tree if (splitIndex != (index - 1)) root2 = createBST(inOrder, splitIndex + 1, index - 1); // Print two Balanced BSTs System.out.print("First BST : "); if (root1 != null) { inorderTrav(root1); } else { System.out.print("null"); } System.out.println(); System.out.print("Second BST : "); if (root2 != null) { inorderTrav(root2); } else { System.out.print("null"); } } // Driver code public static void main(String[] args) { /* BST 5 / \ 3 7 / \ / \ 2 4 6 8 */ node root = null; root = insert(root, 5); insert(root, 3); insert(root, 2); insert(root, 4); insert(root, 7); insert(root, 6); insert(root, 8); int k = 5; // Function to split BST splitBST(root, k); }} // This code is contributed by Rajput-Ji # Python 3 program to split a# BST into two balanced BSTs# based on a value Kindex = 0 # Structure of each node of BSTclass newNode: def __init__(self, item): # A utility function to # create a new BST node self.key = item self.left = None self.right = None # A utility function to insert# a new node with given key# in BSTdef insert(node, key): # If the tree is empty, # return a new node if (node == None): return newNode(key) # Otherwise, recur down # the tree if (key < node.key): node.left = insert(node.left, key) elif (key > node.key): node.right = insert(node.right, key) # return the (unchanged) # node pointer return node # Function to return the# size of the treedef sizeOfTree(root): if (root == None): return 0 # Calculate left size # recursively left = sizeOfTree(root.left) # Calculate right size # recursively right = sizeOfTree(root.right) # Return total size # recursively return (left + right + 1) # Function to store inorder# traversal of BSTdef storeInorder(root, inOrder): global index # Base condition if (root == None): return # Left recursive call storeInorder(root.left, inOrder) # Store elements in # inorder array inOrder[index] = root.key index += 1 # Right recursive call storeInorder(root.right, inOrder) # Function to return the# splitting index of the# arraydef getSplittingIndex(inOrder, index, k): for i in range(index): if (inOrder[i] >= k): return i - 1 return index - 1 # Function to create the# Balanced Binary search# treedef createBST(inOrder, start, end): # Base Condition if (start > end): return None # Calculate the mid of # the array mid = (start + end) // 2 t = newNode(inOrder[mid]) # Recursive call for # left child t.left = createBST(inOrder, start, mid - 1) # Recursive call for # right child t.right = createBST(inOrder, mid + 1, end) # Return newly created # Balanced Binary Search # Tree return t # Function to traverse# the tree in inorder# fashiondef inorderTrav(root): if (root == None): return inorderTrav(root.left) print(root.key, end = " ") inorderTrav(root.right) # Function to split the BST# into two Balanced BSTdef splitBST(root, k): global index # Print the original BST print("Original BST : ") if (root != None): inorderTrav(root) print("\n", end = "") else: print("NULL") # Store the size of BST1 numNode = sizeOfTree(root) # Take auxiliary array for # storing The inorder traversal # of BST1 inOrder = [0 for i in range(numNode + 1)] index = 0 # Function call for storing # inorder traversal of BST1 storeInorder(root, inOrder) # Function call for getting # splitting index splitIndex = getSplittingIndex(inOrder, index, k) root1 = None root2 = None # Creation of first Balanced # Binary Search Tree if (splitIndex != -1): root1 = createBST(inOrder, 0, splitIndex) # Creation of Second Balanced # Binary Search Tree if (splitIndex != (index - 1)): root2 = createBST(inOrder, splitIndex + 1, index - 1) # Print two Balanced BSTs print("First BST : ") if (root1 != None): inorderTrav(root1) print("\n", end = "") else: print("NULL") print("Second BST : ") if (root2 != None): inorderTrav(root2) print("\n", end = "") else: print("NULL") # Driver codeif __name__ == '__main__': '''/* BST 5 / / 3 7 / / / / 2 4 6 8 */''' root = None root = insert(root, 5) insert(root, 3) insert(root, 2) insert(root, 4) insert(root, 7) insert(root, 6) insert(root, 8) k = 5 # Function to split BST splitBST(root, k) # This code is contributed by Chitranayal // C# program to split a BST into// two balanced BSTs based on a value Kusing System; public class GFG{ // Structure of each node of BST public class node { public int key; public node left, right; }; static int index; // A utility function to // create a new BST node static node newNode(int item) { node temp = new node(); temp.key = item; temp.left = temp.right = null; return temp; } // A utility function to insert a new // node with given key in BST static node insert(node node, int key) { // If the tree is empty, return a new node if (node == null) return newNode(key); // Otherwise, recur down the tree if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // return the (unchanged) node pointer return node; } // Function to return the size // of the tree static int sizeOfTree(node root) { if (root == null) { return 0; } // Calculate left size recursively int left = sizeOfTree(root.left); // Calculate right size recursively int right = sizeOfTree(root.right); // Return total size recursively return (left + right + 1); } // Function to store inorder // traversal of BST static void storeInorder(node root, int []inOrder) { // Base condition if (root == null) { return; } // Left recursive call storeInorder(root.left, inOrder); // Store elements in inorder array inOrder[index++] = root.key; // Right recursive call storeInorder(root.right, inOrder); } // Function to return the splitting // index of the array static int getSplittingIndex(int []inOrder, int k) { for (int i = 0; i < index; i++) { if (inOrder[i] >= k) { return i - 1; } } return index - 1; } // Function to create the Balanced // Binary search tree static node createBST(int []inOrder, int start, int end) { // Base Condition if (start > end) { return null; } // Calculate the mid of the array int mid = (start + end) / 2; node t = newNode(inOrder[mid]); // Recursive call for left child t.left = createBST(inOrder, start, mid - 1); // Recursive call for right child t.right = createBST(inOrder, mid + 1, end); // Return newly created Balanced // Binary Search Tree return t; } // Function to traverse the tree // in inorder fashion static void inorderTrav(node root) { if (root == null) return; inorderTrav(root.left); Console.Write(root.key+ " "); inorderTrav(root.right); } // Function to split the BST // into two Balanced BST static void splitBST(node root, int k) { // Print the original BST Console.Write("Original BST : "); if (root != null) { inorderTrav(root); } else { Console.Write("null"); } Console.WriteLine(); // Store the size of BST1 int numNode = sizeOfTree(root); // Take auxiliary array for storing // The inorder traversal of BST1 int []inOrder = new int[numNode + 1]; index = 0; // Function call for storing // inorder traversal of BST1 storeInorder(root, inOrder); // Function call for getting // splitting index int splitIndex = getSplittingIndex(inOrder, k); node root1 = null; node root2 = null; // Creation of first Balanced // Binary Search Tree if (splitIndex != -1) root1 = createBST(inOrder, 0, splitIndex); // Creation of Second Balanced // Binary Search Tree if (splitIndex != (index - 1)) root2 = createBST(inOrder, splitIndex + 1, index - 1); // Print two Balanced BSTs Console.Write("First BST : "); if (root1 != null) { inorderTrav(root1); } else { Console.Write("null"); } Console.WriteLine(); Console.Write("Second BST : "); if (root2 != null) { inorderTrav(root2); } else { Console.Write("null"); } } // Driver code public static void Main(String[] args) { /* BST 5 / \ 3 7 / \ / \ 2 4 6 8 */ node root = null; root = insert(root, 5); insert(root, 3); insert(root, 2); insert(root, 4); insert(root, 7); insert(root, 6); insert(root, 8); int k = 5; // Function to split BST splitBST(root, k); }} // This code is contributed by Rajput-Ji <script>// javascript program to split a BST into// two balanced BSTs based on a value K // Structure of each node of BST class node { constructor() { this.key = 0; this.left = this.right = null; } } var index = 0; // A utility function to // create a new BST node function newNode(item) { var temp = new node(); temp.key = item; temp.left = temp.right = null; return temp; } // A utility function to insert a new // node with given key in BST function insert( node , key) { // If the tree is empty, return a new node if (node == null) return newNode(key); // Otherwise, recur down the tree if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // return the (unchanged) node pointer return node; } // Function to return the size // of the tree function sizeOfTree( root) { if (root == null) { return 0; } // Calculate left size recursively var left = sizeOfTree(root.left); // Calculate right size recursively var right = sizeOfTree(root.right); // Return total size recursively return (left + right + 1); } // Function to store inorder // traversal of BST function storeInorder( root , inOrder) { // Base condition if (root == null) { return; } // Left recursive call storeInorder(root.left, inOrder); // Store elements in inorder array inOrder[index++] = root.key; // Right recursive call storeInorder(root.right, inOrder); } // Function to return the splitting // index of the array function getSplittingIndex(inOrder , k) { for (i = 0; i < index; i++) { if (inOrder[i] >= k) { return i - 1; } } return index - 1; } // Function to create the Balanced // Binary search tree function createBST(inOrder , start , end) { // Base Condition if (start > end) { return null; } // Calculate the mid of the array var mid = parseInt((start + end) / 2); var t = newNode(inOrder[mid]); // Recursive call for left child t.left = createBST(inOrder, start, mid - 1); // Recursive call for right child t.right = createBST(inOrder, mid + 1, end); // Return newly created Balanced // Binary Search Tree return t; } // Function to traverse the tree // in inorder fashion function inorderTrav( root) { if (root == null) return; inorderTrav(root.left); document.write(root.key + " "); inorderTrav(root.right); } // Function to split the BST // into two Balanced BST function splitBST( root , k) { // Print the original BST document.write("Original BST : "); if (root != null) { inorderTrav(root); } else { document.write("null"); } document.write(); // Store the size of BST1 var numNode = sizeOfTree(root); // Take auxiliary array for storing // The inorder traversal of BST1 var inOrder = Array(numNode + 1).fill(0); index = 0; // Function call for storing // inorder traversal of BST1 storeInorder(root, inOrder); // Function call for getting // splitting index var splitIndex = getSplittingIndex(inOrder, k); var root1 = null; var root2 = null; // Creation of first Balanced // Binary Search Tree if (splitIndex != -1) root1 = createBST(inOrder, 0, splitIndex); // Creation of Second Balanced // Binary Search Tree if (splitIndex != (index - 1)) root2 = createBST(inOrder, splitIndex + 1, index - 1); // Print two Balanced BSTs document.write("<br/>First BST : "); if (root1 != null) { inorderTrav(root1); } else { document.write("null"); } document.write(); document.write("<br/>Second BST : "); if (root2 != null) { inorderTrav(root2); } else { document.write("null"); } } // Driver code /* BST 5 / \ 3 7 / \ / \ 2 4 6 8 */ var root = null; root = insert(root, 5); insert(root, 3); insert(root, 2); insert(root, 4); insert(root, 7); insert(root, 6); insert(root, 8); var k = 5; // Function to split BST splitBST(root, k); // This code contributed by Rajput-Ji</script> Original BST : 2 3 4 5 6 7 8 First BST : 2 3 4 Second BST : 5 6 7 8 ipg2016107 Rajput-Ji simranarora5sos Balanced Binary Search Trees Inorder Traversal Arrays Binary Search Tree Tree Arrays Binary Search Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Feb, 2022" }, { "code": null, "e": 384, "s": 52, "text": "Given a Binary Search tree and an integer K, we have to split the tree into two Balanced Binary Search Tree, where BST-1 consists of all the nodes which are less than K and BST-2 consists of all the nodes which are greater than or equal to K.Note: Arrangement of the nodes may be anything but both BST should be Balanced.Examples: " }, { "code": null, "e": 1666, "s": 384, "text": "Input:\n 40 \n / \\ \n 20 50 \n / \\ \\ \n 10 35 60\n / / \n 25 55 \nK = 35\nOutput:\nFirst BST: 10 20 25\nSecond BST: 35 40 50 55 60\nExplanation:\nAfter splitting above BST\nabout given value K = 35\nFirst Balanced Binary Search Tree is \n 20 \n / \\ \n 10 25 \nSecond Balanced Binary Search Tree is\n 50 \n / \\ \n 35 55 \n \\ \\ \n 40 60\nOR\n 40 \n / \\ \n 35 55 \n / \\ \n 50 60\n\nInput:\n 100 \n / \\ \n 20 500 \n / \\ \n 10 30 \n \\ \n 40 \nK = 50\nOutput:\nFirst BST: 10 20 30 40\nSecond BST: 100 500\nExplanation:\nAfter splitting above BST \nabout given value K = 50\nFirst Balanced Binary Search Tree is \n 20 \n / \\ \n 10 30 \n \\\n 40\nSecond Balanced Binary Search Tree is\n 100 \n \\ \n 500 " }, { "code": null, "e": 1678, "s": 1666, "text": "Approach: " }, { "code": null, "e": 1918, "s": 1678, "text": "First store the inorder traversal of given BST in an arrayThen, split this array about given value KNow construct first balanced BST by first splitting part and second BST by second splitting part, using the approach used in this article. " }, { "code": null, "e": 1977, "s": 1918, "text": "First store the inorder traversal of given BST in an array" }, { "code": null, "e": 2020, "s": 1977, "text": "Then, split this array about given value K" }, { "code": null, "e": 2160, "s": 2020, "text": "Now construct first balanced BST by first splitting part and second BST by second splitting part, using the approach used in this article. " }, { "code": null, "e": 2212, "s": 2160, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 2216, "s": 2212, "text": "C++" }, { "code": null, "e": 2221, "s": 2216, "text": "Java" }, { "code": null, "e": 2229, "s": 2221, "text": "Python3" }, { "code": null, "e": 2232, "s": 2229, "text": "C#" }, { "code": null, "e": 2243, "s": 2232, "text": "Javascript" }, { "code": "// C++ program to split a BST into// two balanced BSTs based on a value K #include <iostream>using namespace std; // Structure of each node of BSTstruct node { int key; struct node *left, *right;}; // A utility function to// create a new BST nodenode* newNode(int item){ node* temp = new node(); temp->key = item; temp->left = temp->right = NULL; return temp;} // A utility function to insert a new// node with given key in BSTstruct node* insert(struct node* node, int key){ // If the tree is empty, return a new node if (node == NULL) return newNode(key); // Otherwise, recur down the tree if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); // return the (unchanged) node pointer return node;} // Function to return the size// of the treeint sizeOfTree(node* root){ if (root == NULL) { return 0; } // Calculate left size recursively int left = sizeOfTree(root->left); // Calculate right size recursively int right = sizeOfTree(root->right); // Return total size recursively return (left + right + 1);} // Function to store inorder// traversal of BSTvoid storeInorder(node* root, int inOrder[], int& index){ // Base condition if (root == NULL) { return; } // Left recursive call storeInorder(root->left, inOrder, index); // Store elements in inorder array inOrder[index++] = root->key; // Right recursive call storeInorder(root->right, inOrder, index);} // Function to return the splitting// index of the arrayint getSplittingIndex(int inOrder[], int index, int k){ for (int i = 0; i < index; i++) { if (inOrder[i] >= k) { return i - 1; } } return index - 1;} // Function to create the Balanced// Binary search treenode* createBST(int inOrder[], int start, int end){ // Base Condition if (start > end) { return NULL; } // Calculate the mid of the array int mid = (start + end) / 2; node* t = newNode(inOrder[mid]); // Recursive call for left child t->left = createBST(inOrder, start, mid - 1); // Recursive call for right child t->right = createBST(inOrder, mid + 1, end); // Return newly created Balanced // Binary Search Tree return t;} // Function to traverse the tree// in inorder fashionvoid inorderTrav(node* root){ if (root == NULL) return; inorderTrav(root->left); cout << root->key << \" \"; inorderTrav(root->right);} // Function to split the BST// into two Balanced BSTvoid splitBST(node* root, int k){ // Print the original BST cout << \"Original BST : \"; if (root != NULL) { inorderTrav(root); } else { cout << \"NULL\"; } cout << endl; // Store the size of BST1 int numNode = sizeOfTree(root); // Take auxiliary array for storing // The inorder traversal of BST1 int inOrder[numNode + 1]; int index = 0; // Function call for storing // inorder traversal of BST1 storeInorder(root, inOrder, index); // Function call for getting // splitting index int splitIndex = getSplittingIndex(inOrder, index, k); node* root1 = NULL; node* root2 = NULL; // Creation of first Balanced // Binary Search Tree if (splitIndex != -1) root1 = createBST(inOrder, 0, splitIndex); // Creation of Second Balanced // Binary Search Tree if (splitIndex != (index - 1)) root2 = createBST(inOrder, splitIndex + 1, index - 1); // Print two Balanced BSTs cout << \"First BST : \"; if (root1 != NULL) { inorderTrav(root1); } else { cout << \"NULL\"; } cout << endl; cout << \"Second BST : \"; if (root2 != NULL) { inorderTrav(root2); } else { cout << \"NULL\"; }} // Driver codeint main(){ /* BST 5 / \\ 3 7 / \\ / \\ 2 4 6 8 */ struct node* root = NULL; root = insert(root, 5); insert(root, 3); insert(root, 2); insert(root, 4); insert(root, 7); insert(root, 6); insert(root, 8); int k = 5; // Function to split BST splitBST(root, k); return 0;}", "e": 6799, "s": 2243, "text": null }, { "code": "// Java program to split a BST into// two balanced BSTs based on a value Kimport java.util.*; class GFG{ // Structure of each node of BST static class node { int key; node left, right; }; static int index; // A utility function to // create a new BST node static node newNode(int item) { node temp = new node(); temp.key = item; temp.left = temp.right = null; return temp; } // A utility function to insert a new // node with given key in BST static node insert(node node, int key) { // If the tree is empty, return a new node if (node == null) return newNode(key); // Otherwise, recur down the tree if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // return the (unchanged) node pointer return node; } // Function to return the size // of the tree static int sizeOfTree(node root) { if (root == null) { return 0; } // Calculate left size recursively int left = sizeOfTree(root.left); // Calculate right size recursively int right = sizeOfTree(root.right); // Return total size recursively return (left + right + 1); } // Function to store inorder // traversal of BST static void storeInorder(node root, int inOrder[]) { // Base condition if (root == null) { return; } // Left recursive call storeInorder(root.left, inOrder); // Store elements in inorder array inOrder[index++] = root.key; // Right recursive call storeInorder(root.right, inOrder); } // Function to return the splitting // index of the array static int getSplittingIndex(int inOrder[], int k) { for (int i = 0; i < index; i++) { if (inOrder[i] >= k) { return i - 1; } } return index - 1; } // Function to create the Balanced // Binary search tree static node createBST(int inOrder[], int start, int end) { // Base Condition if (start > end) { return null; } // Calculate the mid of the array int mid = (start + end) / 2; node t = newNode(inOrder[mid]); // Recursive call for left child t.left = createBST(inOrder, start, mid - 1); // Recursive call for right child t.right = createBST(inOrder, mid + 1, end); // Return newly created Balanced // Binary Search Tree return t; } // Function to traverse the tree // in inorder fashion static void inorderTrav(node root) { if (root == null) return; inorderTrav(root.left); System.out.print(root.key+ \" \"); inorderTrav(root.right); } // Function to split the BST // into two Balanced BST static void splitBST(node root, int k) { // Print the original BST System.out.print(\"Original BST : \"); if (root != null) { inorderTrav(root); } else { System.out.print(\"null\"); } System.out.println(); // Store the size of BST1 int numNode = sizeOfTree(root); // Take auxiliary array for storing // The inorder traversal of BST1 int []inOrder = new int[numNode + 1]; index = 0; // Function call for storing // inorder traversal of BST1 storeInorder(root, inOrder); // Function call for getting // splitting index int splitIndex = getSplittingIndex(inOrder, k); node root1 = null; node root2 = null; // Creation of first Balanced // Binary Search Tree if (splitIndex != -1) root1 = createBST(inOrder, 0, splitIndex); // Creation of Second Balanced // Binary Search Tree if (splitIndex != (index - 1)) root2 = createBST(inOrder, splitIndex + 1, index - 1); // Print two Balanced BSTs System.out.print(\"First BST : \"); if (root1 != null) { inorderTrav(root1); } else { System.out.print(\"null\"); } System.out.println(); System.out.print(\"Second BST : \"); if (root2 != null) { inorderTrav(root2); } else { System.out.print(\"null\"); } } // Driver code public static void main(String[] args) { /* BST 5 / \\ 3 7 / \\ / \\ 2 4 6 8 */ node root = null; root = insert(root, 5); insert(root, 3); insert(root, 2); insert(root, 4); insert(root, 7); insert(root, 6); insert(root, 8); int k = 5; // Function to split BST splitBST(root, k); }} // This code is contributed by Rajput-Ji", "e": 11523, "s": 6799, "text": null }, { "code": "# Python 3 program to split a# BST into two balanced BSTs# based on a value Kindex = 0 # Structure of each node of BSTclass newNode: def __init__(self, item): # A utility function to # create a new BST node self.key = item self.left = None self.right = None # A utility function to insert# a new node with given key# in BSTdef insert(node, key): # If the tree is empty, # return a new node if (node == None): return newNode(key) # Otherwise, recur down # the tree if (key < node.key): node.left = insert(node.left, key) elif (key > node.key): node.right = insert(node.right, key) # return the (unchanged) # node pointer return node # Function to return the# size of the treedef sizeOfTree(root): if (root == None): return 0 # Calculate left size # recursively left = sizeOfTree(root.left) # Calculate right size # recursively right = sizeOfTree(root.right) # Return total size # recursively return (left + right + 1) # Function to store inorder# traversal of BSTdef storeInorder(root, inOrder): global index # Base condition if (root == None): return # Left recursive call storeInorder(root.left, inOrder) # Store elements in # inorder array inOrder[index] = root.key index += 1 # Right recursive call storeInorder(root.right, inOrder) # Function to return the# splitting index of the# arraydef getSplittingIndex(inOrder, index, k): for i in range(index): if (inOrder[i] >= k): return i - 1 return index - 1 # Function to create the# Balanced Binary search# treedef createBST(inOrder, start, end): # Base Condition if (start > end): return None # Calculate the mid of # the array mid = (start + end) // 2 t = newNode(inOrder[mid]) # Recursive call for # left child t.left = createBST(inOrder, start, mid - 1) # Recursive call for # right child t.right = createBST(inOrder, mid + 1, end) # Return newly created # Balanced Binary Search # Tree return t # Function to traverse# the tree in inorder# fashiondef inorderTrav(root): if (root == None): return inorderTrav(root.left) print(root.key, end = \" \") inorderTrav(root.right) # Function to split the BST# into two Balanced BSTdef splitBST(root, k): global index # Print the original BST print(\"Original BST : \") if (root != None): inorderTrav(root) print(\"\\n\", end = \"\") else: print(\"NULL\") # Store the size of BST1 numNode = sizeOfTree(root) # Take auxiliary array for # storing The inorder traversal # of BST1 inOrder = [0 for i in range(numNode + 1)] index = 0 # Function call for storing # inorder traversal of BST1 storeInorder(root, inOrder) # Function call for getting # splitting index splitIndex = getSplittingIndex(inOrder, index, k) root1 = None root2 = None # Creation of first Balanced # Binary Search Tree if (splitIndex != -1): root1 = createBST(inOrder, 0, splitIndex) # Creation of Second Balanced # Binary Search Tree if (splitIndex != (index - 1)): root2 = createBST(inOrder, splitIndex + 1, index - 1) # Print two Balanced BSTs print(\"First BST : \") if (root1 != None): inorderTrav(root1) print(\"\\n\", end = \"\") else: print(\"NULL\") print(\"Second BST : \") if (root2 != None): inorderTrav(root2) print(\"\\n\", end = \"\") else: print(\"NULL\") # Driver codeif __name__ == '__main__': '''/* BST 5 / / 3 7 / / / / 2 4 6 8 */''' root = None root = insert(root, 5) insert(root, 3) insert(root, 2) insert(root, 4) insert(root, 7) insert(root, 6) insert(root, 8) k = 5 # Function to split BST splitBST(root, k) # This code is contributed by Chitranayal", "e": 15843, "s": 11523, "text": null }, { "code": "// C# program to split a BST into// two balanced BSTs based on a value Kusing System; public class GFG{ // Structure of each node of BST public class node { public int key; public node left, right; }; static int index; // A utility function to // create a new BST node static node newNode(int item) { node temp = new node(); temp.key = item; temp.left = temp.right = null; return temp; } // A utility function to insert a new // node with given key in BST static node insert(node node, int key) { // If the tree is empty, return a new node if (node == null) return newNode(key); // Otherwise, recur down the tree if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // return the (unchanged) node pointer return node; } // Function to return the size // of the tree static int sizeOfTree(node root) { if (root == null) { return 0; } // Calculate left size recursively int left = sizeOfTree(root.left); // Calculate right size recursively int right = sizeOfTree(root.right); // Return total size recursively return (left + right + 1); } // Function to store inorder // traversal of BST static void storeInorder(node root, int []inOrder) { // Base condition if (root == null) { return; } // Left recursive call storeInorder(root.left, inOrder); // Store elements in inorder array inOrder[index++] = root.key; // Right recursive call storeInorder(root.right, inOrder); } // Function to return the splitting // index of the array static int getSplittingIndex(int []inOrder, int k) { for (int i = 0; i < index; i++) { if (inOrder[i] >= k) { return i - 1; } } return index - 1; } // Function to create the Balanced // Binary search tree static node createBST(int []inOrder, int start, int end) { // Base Condition if (start > end) { return null; } // Calculate the mid of the array int mid = (start + end) / 2; node t = newNode(inOrder[mid]); // Recursive call for left child t.left = createBST(inOrder, start, mid - 1); // Recursive call for right child t.right = createBST(inOrder, mid + 1, end); // Return newly created Balanced // Binary Search Tree return t; } // Function to traverse the tree // in inorder fashion static void inorderTrav(node root) { if (root == null) return; inorderTrav(root.left); Console.Write(root.key+ \" \"); inorderTrav(root.right); } // Function to split the BST // into two Balanced BST static void splitBST(node root, int k) { // Print the original BST Console.Write(\"Original BST : \"); if (root != null) { inorderTrav(root); } else { Console.Write(\"null\"); } Console.WriteLine(); // Store the size of BST1 int numNode = sizeOfTree(root); // Take auxiliary array for storing // The inorder traversal of BST1 int []inOrder = new int[numNode + 1]; index = 0; // Function call for storing // inorder traversal of BST1 storeInorder(root, inOrder); // Function call for getting // splitting index int splitIndex = getSplittingIndex(inOrder, k); node root1 = null; node root2 = null; // Creation of first Balanced // Binary Search Tree if (splitIndex != -1) root1 = createBST(inOrder, 0, splitIndex); // Creation of Second Balanced // Binary Search Tree if (splitIndex != (index - 1)) root2 = createBST(inOrder, splitIndex + 1, index - 1); // Print two Balanced BSTs Console.Write(\"First BST : \"); if (root1 != null) { inorderTrav(root1); } else { Console.Write(\"null\"); } Console.WriteLine(); Console.Write(\"Second BST : \"); if (root2 != null) { inorderTrav(root2); } else { Console.Write(\"null\"); } } // Driver code public static void Main(String[] args) { /* BST 5 / \\ 3 7 / \\ / \\ 2 4 6 8 */ node root = null; root = insert(root, 5); insert(root, 3); insert(root, 2); insert(root, 4); insert(root, 7); insert(root, 6); insert(root, 8); int k = 5; // Function to split BST splitBST(root, k); }} // This code is contributed by Rajput-Ji", "e": 20547, "s": 15843, "text": null }, { "code": "<script>// javascript program to split a BST into// two balanced BSTs based on a value K // Structure of each node of BST class node { constructor() { this.key = 0; this.left = this.right = null; } } var index = 0; // A utility function to // create a new BST node function newNode(item) { var temp = new node(); temp.key = item; temp.left = temp.right = null; return temp; } // A utility function to insert a new // node with given key in BST function insert( node , key) { // If the tree is empty, return a new node if (node == null) return newNode(key); // Otherwise, recur down the tree if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // return the (unchanged) node pointer return node; } // Function to return the size // of the tree function sizeOfTree( root) { if (root == null) { return 0; } // Calculate left size recursively var left = sizeOfTree(root.left); // Calculate right size recursively var right = sizeOfTree(root.right); // Return total size recursively return (left + right + 1); } // Function to store inorder // traversal of BST function storeInorder( root , inOrder) { // Base condition if (root == null) { return; } // Left recursive call storeInorder(root.left, inOrder); // Store elements in inorder array inOrder[index++] = root.key; // Right recursive call storeInorder(root.right, inOrder); } // Function to return the splitting // index of the array function getSplittingIndex(inOrder , k) { for (i = 0; i < index; i++) { if (inOrder[i] >= k) { return i - 1; } } return index - 1; } // Function to create the Balanced // Binary search tree function createBST(inOrder , start , end) { // Base Condition if (start > end) { return null; } // Calculate the mid of the array var mid = parseInt((start + end) / 2); var t = newNode(inOrder[mid]); // Recursive call for left child t.left = createBST(inOrder, start, mid - 1); // Recursive call for right child t.right = createBST(inOrder, mid + 1, end); // Return newly created Balanced // Binary Search Tree return t; } // Function to traverse the tree // in inorder fashion function inorderTrav( root) { if (root == null) return; inorderTrav(root.left); document.write(root.key + \" \"); inorderTrav(root.right); } // Function to split the BST // into two Balanced BST function splitBST( root , k) { // Print the original BST document.write(\"Original BST : \"); if (root != null) { inorderTrav(root); } else { document.write(\"null\"); } document.write(); // Store the size of BST1 var numNode = sizeOfTree(root); // Take auxiliary array for storing // The inorder traversal of BST1 var inOrder = Array(numNode + 1).fill(0); index = 0; // Function call for storing // inorder traversal of BST1 storeInorder(root, inOrder); // Function call for getting // splitting index var splitIndex = getSplittingIndex(inOrder, k); var root1 = null; var root2 = null; // Creation of first Balanced // Binary Search Tree if (splitIndex != -1) root1 = createBST(inOrder, 0, splitIndex); // Creation of Second Balanced // Binary Search Tree if (splitIndex != (index - 1)) root2 = createBST(inOrder, splitIndex + 1, index - 1); // Print two Balanced BSTs document.write(\"<br/>First BST : \"); if (root1 != null) { inorderTrav(root1); } else { document.write(\"null\"); } document.write(); document.write(\"<br/>Second BST : \"); if (root2 != null) { inorderTrav(root2); } else { document.write(\"null\"); } } // Driver code /* BST 5 / \\ 3 7 / \\ / \\ 2 4 6 8 */ var root = null; root = insert(root, 5); insert(root, 3); insert(root, 2); insert(root, 4); insert(root, 7); insert(root, 6); insert(root, 8); var k = 5; // Function to split BST splitBST(root, k); // This code contributed by Rajput-Ji</script>", "e": 25398, "s": 20547, "text": null }, { "code": null, "e": 25468, "s": 25398, "text": "Original BST : 2 3 4 5 6 7 8 \nFirst BST : 2 3 4 \nSecond BST : 5 6 7 8" }, { "code": null, "e": 25481, "s": 25470, "text": "ipg2016107" }, { "code": null, "e": 25491, "s": 25481, "text": "Rajput-Ji" }, { "code": null, "e": 25507, "s": 25491, "text": "simranarora5sos" }, { "code": null, "e": 25536, "s": 25507, "text": "Balanced Binary Search Trees" }, { "code": null, "e": 25554, "s": 25536, "text": "Inorder Traversal" }, { "code": null, "e": 25561, "s": 25554, "text": "Arrays" }, { "code": null, "e": 25580, "s": 25561, "text": "Binary Search Tree" }, { "code": null, "e": 25585, "s": 25580, "text": "Tree" }, { "code": null, "e": 25592, "s": 25585, "text": "Arrays" }, { "code": null, "e": 25611, "s": 25592, "text": "Binary Search Tree" }, { "code": null, "e": 25616, "s": 25611, "text": "Tree" } ]
How to delete an SMS from the inbox in Android programmatically?
This example demonstrates how do I delete an sms from inbox in Android programmatically. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/bt_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Delete SMS" android:layout_centerInParent="true" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.content.Context; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private Context mContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = this; Button btn = (Button) findViewById(R.id.bt_delete); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (deleteSMS()) { Toast.makeText(mContext, "Your message is deleted.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(mContext, "Sorry we can't delete messages.", Toast.LENGTH_LONG).show(); } } }); } private boolean deleteSMS() { boolean isDeleted = false; try { mContext.getContentResolver().delete(Uri.parse("content://sms/"), null, null); isDeleted = true; } catch (Exception ex) { isDeleted = false; } return isDeleted; } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <uses-permission android:name="android.permission.READ_SMS" /> <uses-permission android:name="android.permission.WRITE_SMS" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1151, "s": 1062, "text": "This example demonstrates how do I delete an sms from inbox in Android programmatically." }, { "code": null, "e": 1280, "s": 1151, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1345, "s": 1280, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1848, "s": 1345, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/bt_delete\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Delete SMS\"\n android:layout_centerInParent=\"true\" />\n</RelativeLayout>" }, { "code": null, "e": 1905, "s": 1848, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3138, "s": 1905, "text": "import android.content.Context;\nimport android.net.Uri;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n private Context mContext;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n mContext = this;\n Button btn = (Button) findViewById(R.id.bt_delete);\n btn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (deleteSMS()) {\n Toast.makeText(mContext, \"Your message is deleted.\", Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(mContext, \"Sorry we can't delete messages.\", Toast.LENGTH_LONG).show();\n }\n }\n });\n }\n private boolean deleteSMS() {\n boolean isDeleted = false;\n try {\n mContext.getContentResolver().delete(Uri.parse(\"content://sms/\"), null, null);\n isDeleted = true;\n } catch (Exception ex) {\n isDeleted = false;\n }\n return isDeleted;\n }\n}" }, { "code": null, "e": 3193, "s": 3138, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3996, "s": 3193, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.READ_SMS\" />\n <uses-permission android:name=\"android.permission.WRITE_SMS\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4343, "s": 3996, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 4384, "s": 4343, "text": "Click here to download the project code." } ]
Best practice to wait for a change with Selenium Webdriver?
The best practice to wait for a change in Selenium is to use the synchronization concept. The implicit and explicit waits can be used to handle a wait. The implicit is a global wait applied to every element on the page. The default value of implicit wait is 0. Also it is a dynamic wait, meaning if there is an implicit wait of 5 seconds and the element becomes available at the 3rd second, then the next step is executed immediately without waiting for the entire 5 seconds. Once the 5 seconds have elapsed, and if element is not found, a timeout error shall be thrown. driver.manage().timeouts().implicitlyWait(); import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class ImpctWt { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.tutorialspoint.com/index.htm"); // wait of 5 seconds driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // findElement() will try to identify element till 5 secs WebElement n=driver.findElement(By.id("gsc−i−id1")); n.sendKeys("Java"); } } The explicit wait is also used and it is applied to a specific element on the page. It is a WebDriverWait that works in association with the Expected Condition class. It is a dynamic wait, meaning if there is an explicit wait of 5 seconds and the element becomes available at the 3rd second, then the next step is executed immediately. Once the 5 seconds have elapsed, and element is not found, timeout error shall be thrown. Some of the expected conditions for explicit waits are − titleContains(String s) titleContains(String s) alertIsPresent() alertIsPresent() invisibilityOfElementLocated(By locator) invisibilityOfElementLocated(By locator) invisibilityOfElementWithText(By locator, String s) invisibilityOfElementWithText(By locator, String s) textToBePresentInElement(By locator, String t) textToBePresentInElement(By locator, String t) visibilityOfElementLocated(By locator) visibilityOfElementLocated(By locator) presenceOfAllElementsLocatedBy(By locator) presenceOfAllElementsLocatedBy(By locator) visibilityOf(WebElement e) visibilityOf(WebElement e) presenceOfElementLocated(By locator) presenceOfElementLocated(By locator) elementToBeClickable(By locator) elementToBeClickable(By locator) stalenessOf(WebElement e) stalenessOf(WebElement e) import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class ExpltWt { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.tutorialspoint.com/index.htm"); // identify element and click() driver.findElement(By.xpath("//*[text()='Library']")).click(); // expected condition − invisibility condition WebDriverWait wt = new WebDriverWait(driver,5); // invisibilityOfElementLocated condition wt.until(ExpectedConditions. invisibilityOfElementLocated(By.xpath("//*[@class='mui−btn']"))); driver.close(); } }
[ { "code": null, "e": 1282, "s": 1062, "text": "The best practice to wait for a change in Selenium is to use the synchronization concept. The implicit and explicit waits can be used to handle a wait. The implicit is a global wait applied to every element on the page." }, { "code": null, "e": 1633, "s": 1282, "text": "The default value of implicit wait is 0. Also it is a dynamic wait, meaning if there is an implicit wait of 5 seconds and the element becomes available at the 3rd second, then the next step is executed immediately without waiting for the entire 5 seconds. Once the 5 seconds have elapsed, and if element is not found, a timeout error shall be thrown." }, { "code": null, "e": 1678, "s": 1633, "text": "driver.manage().timeouts().implicitlyWait();" }, { "code": null, "e": 2413, "s": 1678, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class ImpctWt {\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n // wait of 5 seconds\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // findElement() will try to identify element till 5 secs\n WebElement n=driver.findElement(By.id(\"gsc−i−id1\"));\n n.sendKeys(\"Java\");\n }\n}" }, { "code": null, "e": 2839, "s": 2413, "text": "The explicit wait is also used and it is applied to a specific element on the page. It is a WebDriverWait that works in association with the Expected Condition class. It is a dynamic wait, meaning if there is an explicit wait of 5 seconds and the element becomes available at the 3rd second, then the next step is executed immediately. Once the 5 seconds have elapsed, and element is not found, timeout error shall be thrown." }, { "code": null, "e": 2896, "s": 2839, "text": "Some of the expected conditions for explicit waits are −" }, { "code": null, "e": 2920, "s": 2896, "text": "titleContains(String s)" }, { "code": null, "e": 2944, "s": 2920, "text": "titleContains(String s)" }, { "code": null, "e": 2961, "s": 2944, "text": "alertIsPresent()" }, { "code": null, "e": 2978, "s": 2961, "text": "alertIsPresent()" }, { "code": null, "e": 3019, "s": 2978, "text": "invisibilityOfElementLocated(By locator)" }, { "code": null, "e": 3060, "s": 3019, "text": "invisibilityOfElementLocated(By locator)" }, { "code": null, "e": 3112, "s": 3060, "text": "invisibilityOfElementWithText(By locator, String s)" }, { "code": null, "e": 3164, "s": 3112, "text": "invisibilityOfElementWithText(By locator, String s)" }, { "code": null, "e": 3211, "s": 3164, "text": "textToBePresentInElement(By locator, String t)" }, { "code": null, "e": 3258, "s": 3211, "text": "textToBePresentInElement(By locator, String t)" }, { "code": null, "e": 3297, "s": 3258, "text": "visibilityOfElementLocated(By locator)" }, { "code": null, "e": 3336, "s": 3297, "text": "visibilityOfElementLocated(By locator)" }, { "code": null, "e": 3379, "s": 3336, "text": "presenceOfAllElementsLocatedBy(By locator)" }, { "code": null, "e": 3422, "s": 3379, "text": "presenceOfAllElementsLocatedBy(By locator)" }, { "code": null, "e": 3449, "s": 3422, "text": "visibilityOf(WebElement e)" }, { "code": null, "e": 3476, "s": 3449, "text": "visibilityOf(WebElement e)" }, { "code": null, "e": 3513, "s": 3476, "text": "presenceOfElementLocated(By locator)" }, { "code": null, "e": 3550, "s": 3513, "text": "presenceOfElementLocated(By locator)" }, { "code": null, "e": 3583, "s": 3550, "text": "elementToBeClickable(By locator)" }, { "code": null, "e": 3616, "s": 3583, "text": "elementToBeClickable(By locator)" }, { "code": null, "e": 3642, "s": 3616, "text": "stalenessOf(WebElement e)" }, { "code": null, "e": 3668, "s": 3642, "text": "stalenessOf(WebElement e)" }, { "code": null, "e": 4621, "s": 3668, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.support.ui.ExpectedConditions;\nimport org.openqa.selenium.support.ui.WebDriverWait;\npublic class ExpltWt {\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n // identify element and click()\n driver.findElement(By.xpath(\"//*[text()='Library']\")).click();\n // expected condition − invisibility condition\n WebDriverWait wt = new WebDriverWait(driver,5);\n // invisibilityOfElementLocated condition\n wt.until(ExpectedConditions.\n invisibilityOfElementLocated(By.xpath(\"//*[@class='mui−btn']\")));\n driver.close();\n }\n}" } ]
C++ program to overload addition operator to add two matrices
Suppose we have two matrices mat1 and mat2. We shall have to add these two matrices and form the third matrix. We shall have to do this by overloading the addition operator. So, if the input is like then the output will be To solve this, we will follow these steps − Overload the addition operator, this will take another matrix mat as second argument Overload the addition operator, this will take another matrix mat as second argument define one blank 2d array vv define one blank 2d array vv Define one 2D array vv and load current matrix elements into it Define one 2D array vv and load current matrix elements into it for initialize i := 0, when i < size of vv, update (increase i by 1), do:for initialize j := 0, when j < size of vv[0], update (increase j by 1), do:vv[i, j] := vv[i, j] + mat.a[i, j] for initialize i := 0, when i < size of vv, update (increase i by 1), do: for initialize j := 0, when j < size of vv[0], update (increase j by 1), do:vv[i, j] := vv[i, j] + mat.a[i, j] for initialize j := 0, when j < size of vv[0], update (increase j by 1), do: vv[i, j] := vv[i, j] + mat.a[i, j] return a new matrix using vv Let us see the following implementation to get better understanding − #include <iostream> #include <vector> using namespace std; class Matrix { public: Matrix() {} Matrix(const Matrix& x) : a(x.a) {} Matrix(const vector<vector<int>>& v) : a(v) {} Matrix operator+(const Matrix&); vector<vector<int>> a; void display(){ for(int i = 0; i<a.size(); i++){ for(int j = 0; j<a[i].size(); j++){ cout << a[i][j] << " "; } cout << endl; } } }; Matrix Matrix::operator+(const Matrix& m){ vector<vector<int>> vv = a; for (int i=0; i<vv.size(); i++){ for (int j=0; j<vv[0].size(); j++){ vv[i][j] += m.a[i][j]; } } return Matrix(vv); } int main(){ vector<vector<int>> mat1 = {{5,8},{9,6},{7,9}}; vector<vector<int>> mat2 = {{8,3},{4,7},{6,3}}; int r = mat1.size(); int c = mat1[0].size(); Matrix m1(mat1), m2(mat2), res; res = m1 + m2; res.display(); } {{5,8},{9,6},{7,9}}, {{8,3},{4,7},{6,3}} 13 11 13 13 13 12
[ { "code": null, "e": 1236, "s": 1062, "text": "Suppose we have two matrices mat1 and mat2. We shall have to add these two matrices and form the third matrix. We shall have to do this by overloading the addition operator." }, { "code": null, "e": 1261, "s": 1236, "text": "So, if the input is like" }, { "code": null, "e": 1285, "s": 1261, "text": "then the output will be" }, { "code": null, "e": 1329, "s": 1285, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1414, "s": 1329, "text": "Overload the addition operator, this will take another matrix mat as second argument" }, { "code": null, "e": 1499, "s": 1414, "text": "Overload the addition operator, this will take another matrix mat as second argument" }, { "code": null, "e": 1528, "s": 1499, "text": "define one blank 2d array vv" }, { "code": null, "e": 1557, "s": 1528, "text": "define one blank 2d array vv" }, { "code": null, "e": 1621, "s": 1557, "text": "Define one 2D array vv and load current matrix elements into it" }, { "code": null, "e": 1685, "s": 1621, "text": "Define one 2D array vv and load current matrix elements into it" }, { "code": null, "e": 1869, "s": 1685, "text": "for initialize i := 0, when i < size of vv, update (increase i by 1), do:for initialize j := 0, when j < size of vv[0], update (increase j by 1), do:vv[i, j] := vv[i, j] + mat.a[i, j]" }, { "code": null, "e": 1943, "s": 1869, "text": "for initialize i := 0, when i < size of vv, update (increase i by 1), do:" }, { "code": null, "e": 2054, "s": 1943, "text": "for initialize j := 0, when j < size of vv[0], update (increase j by 1), do:vv[i, j] := vv[i, j] + mat.a[i, j]" }, { "code": null, "e": 2131, "s": 2054, "text": "for initialize j := 0, when j < size of vv[0], update (increase j by 1), do:" }, { "code": null, "e": 2166, "s": 2131, "text": "vv[i, j] := vv[i, j] + mat.a[i, j]" }, { "code": null, "e": 2195, "s": 2166, "text": "return a new matrix using vv" }, { "code": null, "e": 2265, "s": 2195, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3203, "s": 2265, "text": "#include <iostream>\n#include <vector>\nusing namespace std;\nclass Matrix {\n public:\n Matrix() {}\n Matrix(const Matrix& x) : a(x.a) {}\n Matrix(const vector<vector<int>>& v) : a(v) {}\n Matrix operator+(const Matrix&);\n vector<vector<int>> a;\n void display(){\n for(int i = 0; i<a.size(); i++){\n for(int j = 0; j<a[i].size(); j++){\n cout << a[i][j] << \" \";\n } \n cout << endl;\n }\n }\n};\nMatrix Matrix::operator+(const Matrix& m){\n vector<vector<int>> vv = a;\n for (int i=0; i<vv.size(); i++){\n for (int j=0; j<vv[0].size(); j++){\n vv[i][j] += m.a[i][j];\n }\n }\n return Matrix(vv);\n}\nint main(){\n vector<vector<int>> mat1 = {{5,8},{9,6},{7,9}};\n vector<vector<int>> mat2 = {{8,3},{4,7},{6,3}};\n int r = mat1.size();\n int c = mat1[0].size();\n Matrix m1(mat1), m2(mat2), res;\n res = m1 + m2;\n res.display();\n}\n" }, { "code": null, "e": 3244, "s": 3203, "text": "{{5,8},{9,6},{7,9}}, {{8,3},{4,7},{6,3}}" }, { "code": null, "e": 3262, "s": 3244, "text": "13 11\n13 13\n13 12" } ]
How does del operator work on list in Python?
The del operator removes a specific index from given list. For example, if you want to remove the element on index 1 from list a, you'd use: a = [3, "Hello", 2, 1] del a[1] print(a) This will give the output − [3, 2, 1] Note that del removes the elements in place, ie, it doesn't create a new list.
[ { "code": null, "e": 1203, "s": 1062, "text": "The del operator removes a specific index from given list. For example, if you want to remove the element on index 1 from list a, you'd use:" }, { "code": null, "e": 1244, "s": 1203, "text": "a = [3, \"Hello\", 2, 1]\ndel a[1]\nprint(a)" }, { "code": null, "e": 1272, "s": 1244, "text": "This will give the output −" }, { "code": null, "e": 1282, "s": 1272, "text": "[3, 2, 1]" }, { "code": null, "e": 1361, "s": 1282, "text": "Note that del removes the elements in place, ie, it doesn't create a new list." } ]
How to detect Scroll Up & Scroll down in Android ListView using Kotlin?
This example demonstrates how to detect Scroll Up & Scroll down in Android ListView using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" android:padding="8dp" tools:context=".MainActivity"> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.kt import android.os.Bundle import android.widget.* import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { private var scrollView: ScrollView? = null private lateinit var listView: ListView private var numbers = arrayOf( "1", "2", "3", "4", "5", "6", "7", "8", "9", "X", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25" ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" scrollView = findViewById(R.id.scrollView) val adapter: ArrayAdapter<*> = ArrayAdapter( this, R.layout.support_simple_spinner_dropdown_item, numbers ) listView = findViewById(R.id.listView) listView.adapter = adapter listView.setOnScrollListener(object : AbsListView.OnScrollListener { private var lastFirstVisibleItem = 0 override fun onScrollStateChanged(view: AbsListView, scrollState: Int) {} override fun onScroll( view: AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int ) { if (lastFirstVisibleItem < firstVisibleItem) { Toast.makeText( applicationContext, "Scrolling down the listView", Toast.LENGTH_SHORT ).show() } if (lastFirstVisibleItem > firstVisibleItem) { Toast.makeText( applicationContext, "Scrolling up the listView", Toast.LENGTH_SHORT ).show() } lastFirstVisibleItem = firstVisibleItem } }) } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1160, "s": 1062, "text": "This example demonstrates how to detect Scroll Up & Scroll down in Android ListView using Kotlin." }, { "code": null, "e": 1289, "s": 1160, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1354, "s": 1289, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1866, "s": 1354, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n android:orientation=\"vertical\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 1921, "s": 1866, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 3847, "s": 1921, "text": "import android.os.Bundle\nimport android.widget.*\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n private var scrollView: ScrollView? = null\n private lateinit var listView: ListView\n private var numbers = arrayOf(\n \"1\",\n \"2\",\n \"3\",\n \"4\",\n \"5\",\n \"6\",\n \"7\",\n \"8\",\n \"9\",\n \"X\",\n \"11\",\n \"12\",\n \"13\",\n \"14\",\n \"15\",\n \"16\",\n \"17\",\n \"18\",\n \"19\",\n \"20\",\n \"21\",\n \"22\",\n \"23\",\n \"24\",\n \"25\"\n )\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n scrollView = findViewById(R.id.scrollView)\n val adapter: ArrayAdapter<*> = ArrayAdapter(\n this,\n R.layout.support_simple_spinner_dropdown_item, numbers\n )\n listView = findViewById(R.id.listView)\n listView.adapter = adapter\n listView.setOnScrollListener(object : AbsListView.OnScrollListener {\n private var lastFirstVisibleItem = 0\n override fun onScrollStateChanged(view: AbsListView, scrollState: Int) {}\n override fun onScroll(\n view: AbsListView,\n firstVisibleItem: Int,\n visibleItemCount: Int,\n totalItemCount: Int\n )\n {\n if (lastFirstVisibleItem < firstVisibleItem) {\n Toast.makeText(\n applicationContext, \"Scrolling down the listView\",\n Toast.LENGTH_SHORT\n ).show()\n }\n if (lastFirstVisibleItem > firstVisibleItem) {\n Toast.makeText(\n applicationContext, \"Scrolling up the listView\",\n Toast.LENGTH_SHORT\n ).show()\n }\n lastFirstVisibleItem = firstVisibleItem\n }\n })\n }\n}" }, { "code": null, "e": 3902, "s": 3847, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4576, "s": 3902, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4925, "s": 4576, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
Matplotlib - Bar Plot
A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally. A bar graph shows comparisons among discrete categories. One axis of the chart shows the specific categories being compared, and the other axis represents a measured value. Matplotlib API provides the bar() function that can be used in the MATLAB style use as well as object oriented API. The signature of bar() function to be used with axes object is as follows − ax.bar(x, height, width, bottom, align) The function makes a bar plot with the bound rectangle of size (x −width = 2; x + width=2; bottom; bottom + height). The parameters to the function are − The function returns a Matplotlib container object with all bars. Following is a simple example of the Matplotlib bar plot. It shows the number of students enrolled for various courses offered at an institute. import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_axes([0,0,1,1]) langs = ['C', 'C++', 'Java', 'Python', 'PHP'] students = [23,17,35,29,12] ax.bar(langs,students) plt.show() When comparing several quantities and when changing one variable, we might want a bar chart where we have bars of one color for one quantity value. We can plot multiple bar charts by playing with the thickness and the positions of the bars. The data variable contains three series of four values. The following script will show three bar charts of four bars. The bars will have a thickness of 0.25 units. Each bar chart will be shifted 0.25 units from the previous one. The data object is a multidict containing number of students passed in three branches of an engineering college over the last four years. import numpy as np import matplotlib.pyplot as plt data = [[30, 25, 50, 20], [40, 23, 51, 17], [35, 22, 45, 19]] X = np.arange(4) fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.bar(X + 0.00, data[0], color = 'b', width = 0.25) ax.bar(X + 0.25, data[1], color = 'g', width = 0.25) ax.bar(X + 0.50, data[2], color = 'r', width = 0.25) The stacked bar chart stacks bars that represent different groups on top of each other. The height of the resulting bar shows the combined result of the groups. The optional bottom parameter of the pyplot.bar() function allows you to specify a starting value for a bar. Instead of running from zero to a value, it will go from the bottom to the value. The first call to pyplot.bar() plots the blue bars. The second call to pyplot.bar() plots the red bars, with the bottom of the blue bars being at the top of the red bars. import numpy as np import matplotlib.pyplot as plt N = 5 menMeans = (20, 35, 30, 35, 27) womenMeans = (25, 32, 34, 20, 25) ind = np.arange(N) # the x locations for the groups width = 0.35 fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.bar(ind, menMeans, width, color='r') ax.bar(ind, womenMeans, width,bottom=menMeans, color='b') ax.set_ylabel('Scores') ax.set_title('Scores by group and gender') ax.set_xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5')) ax.set_yticks(np.arange(0, 81, 10)) ax.legend(labels=['Men', 'Women']) plt.show() 63 Lectures 6 hours Abhilash Nelson 11 Lectures 4 hours DATAhill Solutions Srinivas Reddy 9 Lectures 2.5 hours DATAhill Solutions Srinivas Reddy 32 Lectures 4 hours Aipython 10 Lectures 2.5 hours Akbar Khan 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2738, "s": 2516, "text": "A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally." }, { "code": null, "e": 2911, "s": 2738, "text": "A bar graph shows comparisons among discrete categories. One axis of the chart shows the specific categories being compared, and the other axis represents a measured value." }, { "code": null, "e": 3103, "s": 2911, "text": "Matplotlib API provides the bar() function that can be used in the MATLAB style use as well as object oriented API. The signature of bar() function to be used with axes object is as follows −" }, { "code": null, "e": 3143, "s": 3103, "text": "ax.bar(x, height, width, bottom, align)" }, { "code": null, "e": 3260, "s": 3143, "text": "The function makes a bar plot with the bound rectangle of size (x −width = 2; x + width=2; bottom; bottom + height)." }, { "code": null, "e": 3297, "s": 3260, "text": "The parameters to the function are −" }, { "code": null, "e": 3363, "s": 3297, "text": "The function returns a Matplotlib container object with all bars." }, { "code": null, "e": 3507, "s": 3363, "text": "Following is a simple example of the Matplotlib bar plot. It shows the number of students enrolled for various courses offered at an institute." }, { "code": null, "e": 3695, "s": 3507, "text": "import matplotlib.pyplot as plt\nfig = plt.figure()\nax = fig.add_axes([0,0,1,1])\nlangs = ['C', 'C++', 'Java', 'Python', 'PHP']\nstudents = [23,17,35,29,12]\nax.bar(langs,students)\nplt.show()" }, { "code": null, "e": 3843, "s": 3695, "text": "When comparing several quantities and when changing one variable, we might want a bar chart where we have bars of one color for one quantity value." }, { "code": null, "e": 4303, "s": 3843, "text": "We can plot multiple bar charts by playing with the thickness and the positions of the bars. The data variable contains three series of four values. The following script will show three bar charts of four bars. The bars will have a thickness of 0.25 units. Each bar chart will be shifted 0.25 units from the previous one. The data object is a multidict containing number of students passed in three branches of an engineering college over the last four years." }, { "code": null, "e": 4640, "s": 4303, "text": "import numpy as np\nimport matplotlib.pyplot as plt\ndata = [[30, 25, 50, 20],\n[40, 23, 51, 17],\n[35, 22, 45, 19]]\nX = np.arange(4)\nfig = plt.figure()\nax = fig.add_axes([0,0,1,1])\nax.bar(X + 0.00, data[0], color = 'b', width = 0.25)\nax.bar(X + 0.25, data[1], color = 'g', width = 0.25)\nax.bar(X + 0.50, data[2], color = 'r', width = 0.25)" }, { "code": null, "e": 4801, "s": 4640, "text": "The stacked bar chart stacks bars that represent different groups on top of each other. The height of the resulting bar shows the combined result of the groups." }, { "code": null, "e": 5163, "s": 4801, "text": "The optional bottom parameter of the pyplot.bar() function allows you to specify a starting value for a bar. Instead of running from zero to a value, it will go from the bottom to the value. The first call to pyplot.bar() plots the blue bars. The second call to pyplot.bar() plots the red bars, with the bottom of the blue bars being at the top of the red bars." }, { "code": null, "e": 5697, "s": 5163, "text": "import numpy as np\nimport matplotlib.pyplot as plt\nN = 5\nmenMeans = (20, 35, 30, 35, 27)\nwomenMeans = (25, 32, 34, 20, 25)\nind = np.arange(N) # the x locations for the groups\nwidth = 0.35\nfig = plt.figure()\nax = fig.add_axes([0,0,1,1])\nax.bar(ind, menMeans, width, color='r')\nax.bar(ind, womenMeans, width,bottom=menMeans, color='b')\nax.set_ylabel('Scores')\nax.set_title('Scores by group and gender')\nax.set_xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))\nax.set_yticks(np.arange(0, 81, 10))\nax.legend(labels=['Men', 'Women'])\nplt.show()" }, { "code": null, "e": 5730, "s": 5697, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5747, "s": 5730, "text": " Abhilash Nelson" }, { "code": null, "e": 5780, "s": 5747, "text": "\n 11 Lectures \n 4 hours \n" }, { "code": null, "e": 5815, "s": 5780, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 5849, "s": 5815, "text": "\n 9 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5884, "s": 5849, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 5917, "s": 5884, "text": "\n 32 Lectures \n 4 hours \n" }, { "code": null, "e": 5927, "s": 5917, "text": " Aipython" }, { "code": null, "e": 5962, "s": 5927, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5974, "s": 5962, "text": " Akbar Khan" }, { "code": null, "e": 6007, "s": 5974, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 6014, "s": 6007, "text": " Anmol" }, { "code": null, "e": 6021, "s": 6014, "text": " Print" }, { "code": null, "e": 6032, "s": 6021, "text": " Add Notes" } ]
Difference Between Vector and List - GeeksforGeeks
28 May, 2020 Vector: Vector is a type of dynamic array which has the ability to resize automatically after insertion or deletion of elements. The elements in vector are placed in contiguous storage so that they can be accessed and traversed using iterators. Element is inserted at the end of the vector.Example: vector v; v.insert(5); v.delete(); List: List is a double linked sequence that supports both forward and backward traversal. The time taken in the insertion and deletion in the beginning, end and middle is constant. It has the non-contiguous memory and there is no pre-allocated memory.Example: list l; l.insert_begin(5); l.delete_end(); Below is a table of differences between Vector and List: Difference Between GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference Between Spark DataFrame and Pandas DataFrame Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Roadmap to Become a Web Developer in 2022 Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Socket Programming in C/C++ DSA Sheet by Love Babbar GET and POST requests using Python
[ { "code": null, "e": 24882, "s": 24854, "text": "\n28 May, 2020" }, { "code": null, "e": 25181, "s": 24882, "text": "Vector: Vector is a type of dynamic array which has the ability to resize automatically after insertion or deletion of elements. The elements in vector are placed in contiguous storage so that they can be accessed and traversed using iterators. Element is inserted at the end of the vector.Example:" }, { "code": null, "e": 25217, "s": 25181, "text": "vector v;\nv.insert(5);\nv.delete();\n" }, { "code": null, "e": 25477, "s": 25217, "text": "List: List is a double linked sequence that supports both forward and backward traversal. The time taken in the insertion and deletion in the beginning, end and middle is constant. It has the non-contiguous memory and there is no pre-allocated memory.Example:" }, { "code": null, "e": 25522, "s": 25477, "text": "list l;\nl.insert_begin(5);\nl.delete_end();\n" }, { "code": null, "e": 25579, "s": 25522, "text": "Below is a table of differences between Vector and List:" }, { "code": null, "e": 25598, "s": 25579, "text": "Difference Between" }, { "code": null, "e": 25604, "s": 25598, "text": "GBlog" }, { "code": null, "e": 25702, "s": 25604, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25711, "s": 25702, "text": "Comments" }, { "code": null, "e": 25724, "s": 25711, "text": "Old Comments" }, { "code": null, "e": 25785, "s": 25724, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 25853, "s": 25785, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 25909, "s": 25853, "text": "Difference Between Spark DataFrame and Pandas DataFrame" }, { "code": null, "e": 25967, "s": 25909, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 26022, "s": 25967, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 26064, "s": 26022, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26138, "s": 26064, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 26166, "s": 26138, "text": "Socket Programming in C/C++" }, { "code": null, "e": 26191, "s": 26166, "text": "DSA Sheet by Love Babbar" } ]
NLP Part 1| Scraping the Web using BeautifulSoup and Python | by Kamil Mysiak | Towards Data Science
Data is at the core of any data science project, yet often we take for granted the availability of data especially when it arrives neatly in a SQL database or better yet in our inbox. That said, sometimes the data you’re looking for isn’t readily available due to its specific nature. One possible solution to this problem is the idea of Web Scraping or the extraction of information from a specific website by carefully reading its HTML. For example, let’s say you’re planning a vacation and you’re on the lookout for when the airfare goes on sale. Yes, you can browse the same travel site each hour hoping the price would drop but a more efficient method would be to scrape the travel site each hour and have an output file provide you with the most current ticket prices. Many websites do not look kindly to having their data scraped, especially if it contains identifiable user information (i.e. Facebook, Linkedin, etc.). Please be considerate of what data you choose to scrape and how often. This short tutorial is the first part of a 3-part series on Natural Language Processing (NLP). In this series, we’ll explore techniques of scraping website data, pre-processing and getting our data ready for analysis, and finally gleaning insights from our NLP data. NLP Part 2 NLP Part 3 In this example, let’s take a stab at scraping indeed.com but specifically company reviews. Let’s target the employees’ ratings, review titles, review descriptions along with the pros and cons. Before we can actually begin scraping information we need to familiarize ourselves with the basic structure of HTML as we’ll actually be using HTML tags to identify what information we wish to scrape. We can access a website’s HTML by opening the developer tools in your current browser. For example, Firefox (options → Web Developer → Inspector). All those blue “div” tags, arrows, classes and ids is the HTML for the website you’re currently on. Before we examine the HTML for indeed.com let’s review the basic structure using the example below. HTML describes the underlying structure of a website. In other words, it identifies that the website will have a header, multiple paragraphs, an embedded video, a closing footer, etc. HTML will not describe how these components will be arranged, their style, size, color, etc. HTML code is hierarchical in nature and indented tags (ie. <div>, <ul>, etc.) identify each new level in the hierarchy. For example, the “<html>” tag is at the top of the hierarchy (also called a container) and it contains all other elements. The body tag is especially important as it contains the vast majority of the information visible on a website. As you can see the body tag houses a variety of other nested tags which in our example stores a paragraph which then contains a link, a review title and the actual review text “Pretty good”. It is important to be able to read and understand the nested trail of tags which lead us to the actual review text “Pretty good” because this is the information we want to scrape. Let’s turn our attention to the python code which drills through this hierarchical structure of tags to pull out the text. First, we’ll need to import the required libraries. from bs4 import BeautifulSoupimport lxmlimport requestsimport pandas as pdimport numpy as np The imported “request” library has a get() function which will request the indeed.com server for the content of the URL and store the server’s response in the “base_url” variable. If we print the “base_url” variable we’ll actually see the entire HTML for the page. base_url = requests.get('https://www.indeed.com/cmp/Google/reviews?fcountry=ALL&start=', timeout=5)print(base_url.text) Let’s begin by defining a function named “parse” requiring one argument which will be the actual URL of the page we are attempting to parse/scrape. Next, we’ll use the BeautifulSoup class creator to parse the content (HTML code) of the provided website. We’ll use the “lxml” parser just in case the HTML is not perfectly formed. For more information about the different parsers available with BeautifulSoup visit this link. Please keep in mind websites will often adjust their HTML script by changing names or parent/child relationships of items in containers. These changes will require you to adjust your function. This function was adjusted 6/20 to fix the newly implemented HTML script for indeed.com def parse(full_url): page_content = BeautifulSoup(full_url.content, 'lxml') containers = page_content.findAll('div', {'class':'cmp-Review-container'}) df = pd.DataFrame(columns = ['rating', 'rating_title', 'rating_description', 'rating_pros', 'rating_cons']) for item in containers: try: rating = item.find('div', {'class': 'cmp-ReviewRating-text'}) .text.replace('\n', '') except: rating = None try: rating_title = item.find('div', {'class': 'cmp-Review-title'}) .text.replace('\n', '') except: rating_title = None try: rating_description = item.find('span', {'itemprop': 'reviewBody'}) .text.replace('\r', '. ') except: rating_description = None try: rating_pros = item.find('div', {'class': 'cmp-ReviewProsCons-prosText'}) .text.replace('\n', '') except: rating_pros = None try: rating_cons = item.find('div', {'class': 'cmp-ReviewProsCons-consText'}) .text.replace('\n', '') except: rating_cons = None df = df.append({'rating': rating, 'rating_title': rating_title, 'rating_description': rating_description, 'rating_pros': rating_pros, 'rating_cons': rating_cons}, ignore_index=True) return df Next, we’ll need to examine the HTML more closely in order to identify which root container (ie. which parent tag) houses the child/nested tags which contain the information we which to scrape. Let’s navigate to “https://www.indeed.com/cmp/Google/reviews?fcountry=ALL&start=” as we’ll be scraping employees’ reviews of google. Open your developer tool in order to observe the HTML for the website. Notice that once you have access to the website’s HTML, moving your mouse cursor around the website causes specific areas to become highlighted and the HTML seems to change right along as you move the cursor. As you move your cursor your developer tools automatically takes you to the HTML section of the highlighted section on the webpage. This is extremely helpful as we can quickly identify which parts of the HTML code we need to examine in more detail. If you recall, in this tutorial we are interested in scraping the employees’ overall rating, review title, review description, pros and cons. We need to identify which HTML tag is the container or home for all this information. By moving our mouse cursor to the appropriate location we see that all the information we wish to scrape is contained neatly inside one root element. By examining the HTML below we can see that the “<div” tag contains all the information we need in a class attribute named “cmp-Review-container”. Now move to a different review and you’ll see the same class attribute named “cmp-Review-container” which stores that review’s data. Therefore, we’ll use the “findall()” method to extract all the “div” containers that have a class attribute of “cmp-Review-container”. Next, we are going to create an empty pandas dataframe named “df” to which we’ll append the scraped data. def parse(full_url): page_content = BeautifulSoup(full_url.content, 'lxml') containers = page_content.findAll('div', {'class':'cmp-Review-container'}) df = pd.DataFrame(columns = ['rating', 'rating_title', 'rating_description', 'rating_pros', 'rating_cons']) for item in containers: try: rating = item.find('div', {'class': 'cmp-ReviewRating-text'}) .text.replace('\n', '') except: rating = None try: rating_title = item.find('div', {'class': 'cmp-Review-title'}) .text.replace('\n', '') except: rating_title = None try: rating_description = item.find('span', {'itemprop': 'reviewBody'}) .text.replace('\r', '. ') except: rating_description = None try: rating_pros = item.find('div', {'class': 'cmp-ReviewProsCons-prosText'}) .text.replace('\n', '') except: rating_pros = None try: rating_cons = item.find('div', {'class': 'cmp-ReviewProsCons-consText'}) .text.replace('\n', '') except: rating_cons = None df = df.append({'rating': rating, 'rating_title': rating_title, 'rating_description': rating_description, 'rating_pros': rating_pros, 'rating_cons': rating_cons}, ignore_index=True) return df Now that we have identified the container for all the data we wish to scrape let’s dive a bit deeper into the HTML to identify the elements which house the actual data. First, the review rating is once again housed in the “cmp-Review-container” container but drilling down a few layers we find the “<div” tag with a class attribute of “cmp-ReviewRating-text which actually stores the “5.0” rating. Let’s make note of the tag and class attribute which stores this data as we’ll need this information for our python script below. We repeat the process for all remaining pieces of data which wish to extract. Here’s a challenge for you. Why are we replacing the carriage return ( “\r”) with (“. “) for our rating_descriptions? Hint: What is the difference between reviews titled “Great work environment” and “Nice place to work”? Post your answers in the comments below! 😉 Once we have identified the appropriate tags for the data let’s turn our attention back to the python code. We can use a try/except block inside a for-loop to search the container for the identified tags using a find() method. We use find() instead of findall() because we only want to return the first match due to the fact we are using a for-loop. Finally, we append the scraped data back into the empty dataframe we created earlier. def parse(full_url): page_content = BeautifulSoup(full_url.content, 'lxml') containers = page_content.findAll('div', {'class':'cmp-Review-container'}) df = pd.DataFrame(columns = ['rating', 'rating_title', 'rating_description', 'rating_pros', 'rating_cons']) for item in containers: try: rating = item.find('div', {'class': 'cmp-ReviewRating-text'}) .text.replace('\n', '') except: rating = None try: rating_title = item.find('div', {'class': 'cmp-Review-title'}) .text.replace('\n', '') except: rating_title = None try: rating_description = item.find('span', {'itemprop': 'reviewBody'}) .text.replace('\r', '. ') except: rating_description = None try: rating_pros = item.find('div', {'class': 'cmp-ReviewProsCons-prosText'}) .text.replace('\n', '') except: rating_pros = None try: rating_cons = item.find('div', {'class': 'cmp-ReviewProsCons-consText'}) .text.replace('\n', '') except: rating_cons = None df = df.append({'rating': rating, 'rating_title': rating_title, 'rating_description': rating_description, 'rating_pros': rating_pros, 'rating_cons': rating_cons}, ignore_index=True) return df We are not done just yet because if you were to execute the “parse()” function you will obtain a dataframe with only 20 records and that’s due to the fact we have only scraped one page. In order to scrape all remaining pages of reviews, we first create a new empty dataframe to collect all the reviews as we iterate over all the pages. Next, we initiate a counter variable of 20 because there are 20 reviews per page. Next, we create a while-loop which will iterate until the number of reviews is equal to or larger than 4000. Why 4000? There are almost 4000 individual reviews across all the pages (*at the time this article was written*). Next, we add the increment of 20 to the end of the base_url as the while-loop iterates through each page. Adding an increment of 20 to the end of the base_url will create a new url specific for the page you wish to visit. For example, “https://www.indeed.com/cmp/Google/reviews?fcountry=ALL&start=40” will take us to the second page of the reviews. Next, we once again request and get the entire HTML for the page the while-loop is iterating over. We apply our parse() function on the page and append the newly scraped reviews into our dataframe. Finally, we increase the counter by 20 in order for the while-loop to iterate on the next page. base_url = 'https://www.indeed.com/cmp/Google/reviews?fcountry=ALL&start='all_reviews_df = pd.DataFrame(columns = ['rating', 'rating_title', 'rating_description','rating_pros', 'rating_cons'])num_reviews = 20# you can adjust this number on how many reviews you which to scrapewhile num_reviews < 3000: full_url = base_url + str(num_reviews) get_url = requests.get(full_url, timeout=5) partial_reviews_df = parse(get_url) all_reviews_df = all_reviews_df.append( partial_reviews_df, ignore_index=True) num_reviews += 20 All that’s left to do is move our dataframe to a csv file. all_reviews_df.to_csv('indeed_scrape.csv') I hope you enjoyed this tutorial. I would love your feedback, feel free to comment below. Don’t forget the challenge!
[ { "code": null, "e": 356, "s": 172, "text": "Data is at the core of any data science project, yet often we take for granted the availability of data especially when it arrives neatly in a SQL database or better yet in our inbox." }, { "code": null, "e": 947, "s": 356, "text": "That said, sometimes the data you’re looking for isn’t readily available due to its specific nature. One possible solution to this problem is the idea of Web Scraping or the extraction of information from a specific website by carefully reading its HTML. For example, let’s say you’re planning a vacation and you’re on the lookout for when the airfare goes on sale. Yes, you can browse the same travel site each hour hoping the price would drop but a more efficient method would be to scrape the travel site each hour and have an output file provide you with the most current ticket prices." }, { "code": null, "e": 1170, "s": 947, "text": "Many websites do not look kindly to having their data scraped, especially if it contains identifiable user information (i.e. Facebook, Linkedin, etc.). Please be considerate of what data you choose to scrape and how often." }, { "code": null, "e": 1437, "s": 1170, "text": "This short tutorial is the first part of a 3-part series on Natural Language Processing (NLP). In this series, we’ll explore techniques of scraping website data, pre-processing and getting our data ready for analysis, and finally gleaning insights from our NLP data." }, { "code": null, "e": 1448, "s": 1437, "text": "NLP Part 2" }, { "code": null, "e": 1459, "s": 1448, "text": "NLP Part 3" }, { "code": null, "e": 1653, "s": 1459, "text": "In this example, let’s take a stab at scraping indeed.com but specifically company reviews. Let’s target the employees’ ratings, review titles, review descriptions along with the pros and cons." }, { "code": null, "e": 1854, "s": 1653, "text": "Before we can actually begin scraping information we need to familiarize ourselves with the basic structure of HTML as we’ll actually be using HTML tags to identify what information we wish to scrape." }, { "code": null, "e": 2101, "s": 1854, "text": "We can access a website’s HTML by opening the developer tools in your current browser. For example, Firefox (options → Web Developer → Inspector). All those blue “div” tags, arrows, classes and ids is the HTML for the website you’re currently on." }, { "code": null, "e": 2201, "s": 2101, "text": "Before we examine the HTML for indeed.com let’s review the basic structure using the example below." }, { "code": null, "e": 2478, "s": 2201, "text": "HTML describes the underlying structure of a website. In other words, it identifies that the website will have a header, multiple paragraphs, an embedded video, a closing footer, etc. HTML will not describe how these components will be arranged, their style, size, color, etc." }, { "code": null, "e": 3326, "s": 2478, "text": "HTML code is hierarchical in nature and indented tags (ie. <div>, <ul>, etc.) identify each new level in the hierarchy. For example, the “<html>” tag is at the top of the hierarchy (also called a container) and it contains all other elements. The body tag is especially important as it contains the vast majority of the information visible on a website. As you can see the body tag houses a variety of other nested tags which in our example stores a paragraph which then contains a link, a review title and the actual review text “Pretty good”. It is important to be able to read and understand the nested trail of tags which lead us to the actual review text “Pretty good” because this is the information we want to scrape. Let’s turn our attention to the python code which drills through this hierarchical structure of tags to pull out the text." }, { "code": null, "e": 3378, "s": 3326, "text": "First, we’ll need to import the required libraries." }, { "code": null, "e": 3471, "s": 3378, "text": "from bs4 import BeautifulSoupimport lxmlimport requestsimport pandas as pdimport numpy as np" }, { "code": null, "e": 3736, "s": 3471, "text": "The imported “request” library has a get() function which will request the indeed.com server for the content of the URL and store the server’s response in the “base_url” variable. If we print the “base_url” variable we’ll actually see the entire HTML for the page." }, { "code": null, "e": 3856, "s": 3736, "text": "base_url = requests.get('https://www.indeed.com/cmp/Google/reviews?fcountry=ALL&start=', timeout=5)print(base_url.text)" }, { "code": null, "e": 4280, "s": 3856, "text": "Let’s begin by defining a function named “parse” requiring one argument which will be the actual URL of the page we are attempting to parse/scrape. Next, we’ll use the BeautifulSoup class creator to parse the content (HTML code) of the provided website. We’ll use the “lxml” parser just in case the HTML is not perfectly formed. For more information about the different parsers available with BeautifulSoup visit this link." }, { "code": null, "e": 4561, "s": 4280, "text": "Please keep in mind websites will often adjust their HTML script by changing names or parent/child relationships of items in containers. These changes will require you to adjust your function. This function was adjusted 6/20 to fix the newly implemented HTML script for indeed.com" }, { "code": null, "e": 6228, "s": 4561, "text": "def parse(full_url): page_content = BeautifulSoup(full_url.content, 'lxml') containers = page_content.findAll('div', {'class':'cmp-Review-container'}) df = pd.DataFrame(columns = ['rating', 'rating_title', 'rating_description', 'rating_pros', 'rating_cons']) for item in containers: try: rating = item.find('div', {'class': 'cmp-ReviewRating-text'}) .text.replace('\\n', '') except: rating = None try: rating_title = item.find('div', {'class': 'cmp-Review-title'}) .text.replace('\\n', '') except: rating_title = None try: rating_description = item.find('span', {'itemprop': 'reviewBody'}) .text.replace('\\r', '. ') except: rating_description = None try: rating_pros = item.find('div', {'class': 'cmp-ReviewProsCons-prosText'}) .text.replace('\\n', '') except: rating_pros = None try: rating_cons = item.find('div', {'class': 'cmp-ReviewProsCons-consText'}) .text.replace('\\n', '') except: rating_cons = None df = df.append({'rating': rating, 'rating_title': rating_title, 'rating_description': rating_description, 'rating_pros': rating_pros, 'rating_cons': rating_cons}, ignore_index=True) return df" }, { "code": null, "e": 7084, "s": 6228, "text": "Next, we’ll need to examine the HTML more closely in order to identify which root container (ie. which parent tag) houses the child/nested tags which contain the information we which to scrape. Let’s navigate to “https://www.indeed.com/cmp/Google/reviews?fcountry=ALL&start=” as we’ll be scraping employees’ reviews of google. Open your developer tool in order to observe the HTML for the website. Notice that once you have access to the website’s HTML, moving your mouse cursor around the website causes specific areas to become highlighted and the HTML seems to change right along as you move the cursor. As you move your cursor your developer tools automatically takes you to the HTML section of the highlighted section on the webpage. This is extremely helpful as we can quickly identify which parts of the HTML code we need to examine in more detail." }, { "code": null, "e": 7742, "s": 7084, "text": "If you recall, in this tutorial we are interested in scraping the employees’ overall rating, review title, review description, pros and cons. We need to identify which HTML tag is the container or home for all this information. By moving our mouse cursor to the appropriate location we see that all the information we wish to scrape is contained neatly inside one root element. By examining the HTML below we can see that the “<div” tag contains all the information we need in a class attribute named “cmp-Review-container”. Now move to a different review and you’ll see the same class attribute named “cmp-Review-container” which stores that review’s data." }, { "code": null, "e": 7983, "s": 7742, "text": "Therefore, we’ll use the “findall()” method to extract all the “div” containers that have a class attribute of “cmp-Review-container”. Next, we are going to create an empty pandas dataframe named “df” to which we’ll append the scraped data." }, { "code": null, "e": 9658, "s": 7983, "text": "def parse(full_url): page_content = BeautifulSoup(full_url.content, 'lxml') containers = page_content.findAll('div', {'class':'cmp-Review-container'}) df = pd.DataFrame(columns = ['rating', 'rating_title', 'rating_description', 'rating_pros', 'rating_cons']) for item in containers: try: rating = item.find('div', {'class': 'cmp-ReviewRating-text'}) .text.replace('\\n', '') except: rating = None try: rating_title = item.find('div', {'class': 'cmp-Review-title'}) .text.replace('\\n', '') except: rating_title = None try: rating_description = item.find('span', {'itemprop': 'reviewBody'}) .text.replace('\\r', '. ') except: rating_description = None try: rating_pros = item.find('div', {'class': 'cmp-ReviewProsCons-prosText'}) .text.replace('\\n', '') except: rating_pros = None try: rating_cons = item.find('div', {'class': 'cmp-ReviewProsCons-consText'}) .text.replace('\\n', '') except: rating_cons = None df = df.append({'rating': rating, 'rating_title': rating_title, 'rating_description': rating_description, 'rating_pros': rating_pros, 'rating_cons': rating_cons}, ignore_index=True) return df" }, { "code": null, "e": 10264, "s": 9658, "text": "Now that we have identified the container for all the data we wish to scrape let’s dive a bit deeper into the HTML to identify the elements which house the actual data. First, the review rating is once again housed in the “cmp-Review-container” container but drilling down a few layers we find the “<div” tag with a class attribute of “cmp-ReviewRating-text which actually stores the “5.0” rating. Let’s make note of the tag and class attribute which stores this data as we’ll need this information for our python script below. We repeat the process for all remaining pieces of data which wish to extract." }, { "code": null, "e": 10528, "s": 10264, "text": "Here’s a challenge for you. Why are we replacing the carriage return ( “\\r”) with (“. “) for our rating_descriptions? Hint: What is the difference between reviews titled “Great work environment” and “Nice place to work”? Post your answers in the comments below! 😉" }, { "code": null, "e": 10964, "s": 10528, "text": "Once we have identified the appropriate tags for the data let’s turn our attention back to the python code. We can use a try/except block inside a for-loop to search the container for the identified tags using a find() method. We use find() instead of findall() because we only want to return the first match due to the fact we are using a for-loop. Finally, we append the scraped data back into the empty dataframe we created earlier." }, { "code": null, "e": 12639, "s": 10964, "text": "def parse(full_url): page_content = BeautifulSoup(full_url.content, 'lxml') containers = page_content.findAll('div', {'class':'cmp-Review-container'}) df = pd.DataFrame(columns = ['rating', 'rating_title', 'rating_description', 'rating_pros', 'rating_cons']) for item in containers: try: rating = item.find('div', {'class': 'cmp-ReviewRating-text'}) .text.replace('\\n', '') except: rating = None try: rating_title = item.find('div', {'class': 'cmp-Review-title'}) .text.replace('\\n', '') except: rating_title = None try: rating_description = item.find('span', {'itemprop': 'reviewBody'}) .text.replace('\\r', '. ') except: rating_description = None try: rating_pros = item.find('div', {'class': 'cmp-ReviewProsCons-prosText'}) .text.replace('\\n', '') except: rating_pros = None try: rating_cons = item.find('div', {'class': 'cmp-ReviewProsCons-consText'}) .text.replace('\\n', '') except: rating_cons = None df = df.append({'rating': rating, 'rating_title': rating_title, 'rating_description': rating_description, 'rating_pros': rating_pros, 'rating_cons': rating_cons}, ignore_index=True) return df" }, { "code": null, "e": 12825, "s": 12639, "text": "We are not done just yet because if you were to execute the “parse()” function you will obtain a dataframe with only 20 records and that’s due to the fact we have only scraped one page." }, { "code": null, "e": 13923, "s": 12825, "text": "In order to scrape all remaining pages of reviews, we first create a new empty dataframe to collect all the reviews as we iterate over all the pages. Next, we initiate a counter variable of 20 because there are 20 reviews per page. Next, we create a while-loop which will iterate until the number of reviews is equal to or larger than 4000. Why 4000? There are almost 4000 individual reviews across all the pages (*at the time this article was written*). Next, we add the increment of 20 to the end of the base_url as the while-loop iterates through each page. Adding an increment of 20 to the end of the base_url will create a new url specific for the page you wish to visit. For example, “https://www.indeed.com/cmp/Google/reviews?fcountry=ALL&start=40” will take us to the second page of the reviews. Next, we once again request and get the entire HTML for the page the while-loop is iterating over. We apply our parse() function on the page and append the newly scraped reviews into our dataframe. Finally, we increase the counter by 20 in order for the while-loop to iterate on the next page." }, { "code": null, "e": 14504, "s": 13923, "text": "base_url = 'https://www.indeed.com/cmp/Google/reviews?fcountry=ALL&start='all_reviews_df = pd.DataFrame(columns = ['rating', 'rating_title', 'rating_description','rating_pros', 'rating_cons'])num_reviews = 20# you can adjust this number on how many reviews you which to scrapewhile num_reviews < 3000: full_url = base_url + str(num_reviews) get_url = requests.get(full_url, timeout=5) partial_reviews_df = parse(get_url) all_reviews_df = all_reviews_df.append( partial_reviews_df, ignore_index=True) num_reviews += 20" }, { "code": null, "e": 14563, "s": 14504, "text": "All that’s left to do is move our dataframe to a csv file." }, { "code": null, "e": 14606, "s": 14563, "text": "all_reviews_df.to_csv('indeed_scrape.csv')" }, { "code": null, "e": 14696, "s": 14606, "text": "I hope you enjoyed this tutorial. I would love your feedback, feel free to comment below." } ]
PHP Using namespaces
Class, function or constant in a namespace can be used in following ways: Using a class in current namespace specifying a namespace relative to current namespace giving a fully qualified name of namespace In this example a namespace is loaded from test1.php. Function or class name referred to without namespace accesses those in current namespace #test1.php <?php namespace myspace\space1; const MAX = 100; function hello() {echo "hello in space1\n";} class myclass{ static function hellomethod() {echo "hello in space1\n";} } ?> Use this file in following code Live Demo <?php namespace myspace; include 'test1.php'; const MAX = 200; function hello() {echo "hello in myspace\n";} class myclass{ static function hellomethod() {echo "hello in myspace\n";} } hello(); myclass::hellomethod(); echo MAX; ?> hello in myspace hello in myspace 200 In following example function and class is accesed with relative namespace <?php namespace myspace; include 'test1.php'; const MAX = 200; function hello() {echo "hello in myspace\n";} class myclass{ static function hellomethod() {echo "hello in myspace\n";} } space1\hello(); space1\myclass::hellomethod(); echo space1\MAX; ?> Above code shows following output hello in space1 hello in space1 100 Functions and classes are given absolute namespace name <?php namespace myspace; include 'test1.php'; const MAX = 200; function hello() {echo "hello in myspace\n";} class myclass{ static function hellomethod() {echo "hello in myspace\n";} } \myspace\hello(); \myspace\space1\hello(); \myspace\myclass::hellomethod(); \myspace\space1\myclass::hellomethod(); echo \myspace\MAX . "\n"; echo \myspace\space1\MAX; ?> Above code shows following output hello in myspace hello in space1 hello in myspace hello in space1 200 100
[ { "code": null, "e": 1136, "s": 1062, "text": "Class, function or constant in a namespace can be used in following ways:" }, { "code": null, "e": 1171, "s": 1136, "text": "Using a class in current namespace" }, { "code": null, "e": 1224, "s": 1171, "text": "specifying a namespace relative to current namespace" }, { "code": null, "e": 1267, "s": 1224, "text": "giving a fully qualified name of namespace" }, { "code": null, "e": 1410, "s": 1267, "text": "In this example a namespace is loaded from test1.php. Function or class name referred to without namespace accesses those in current namespace" }, { "code": null, "e": 1596, "s": 1410, "text": "#test1.php\n<?php\nnamespace myspace\\space1;\nconst MAX = 100;\nfunction hello() {echo \"hello in space1\\n\";}\nclass myclass{\n static function hellomethod() {echo \"hello in space1\\n\";}\n}\n?>" }, { "code": null, "e": 1628, "s": 1596, "text": "Use this file in following code" }, { "code": null, "e": 1639, "s": 1628, "text": " Live Demo" }, { "code": null, "e": 1873, "s": 1639, "text": "<?php\nnamespace myspace;\ninclude 'test1.php';\nconst MAX = 200;\nfunction hello() {echo \"hello in myspace\\n\";}\nclass myclass{\n static function hellomethod() {echo \"hello in myspace\\n\";}\n}\nhello();\nmyclass::hellomethod();\necho MAX;\n?>" }, { "code": null, "e": 1911, "s": 1873, "text": "hello in myspace\nhello in myspace\n200" }, { "code": null, "e": 1986, "s": 1911, "text": "In following example function and class is accesed with relative namespace" }, { "code": null, "e": 2241, "s": 1986, "text": "<?php\nnamespace myspace;\ninclude 'test1.php';\nconst MAX = 200;\nfunction hello() {echo \"hello in myspace\\n\";}\nclass myclass{\n static function hellomethod() {echo \"hello in myspace\\n\";}\n}\nspace1\\hello();\nspace1\\myclass::hellomethod();\necho space1\\MAX;\n?>" }, { "code": null, "e": 2275, "s": 2241, "text": "Above code shows following output" }, { "code": null, "e": 2311, "s": 2275, "text": "hello in space1\nhello in space1\n100" }, { "code": null, "e": 2367, "s": 2311, "text": "Functions and classes are given absolute namespace name" }, { "code": null, "e": 2726, "s": 2367, "text": "<?php\nnamespace myspace;\ninclude 'test1.php';\nconst MAX = 200;\nfunction hello() {echo \"hello in myspace\\n\";}\nclass myclass{\n static function hellomethod() {echo \"hello in myspace\\n\";}\n}\n\\myspace\\hello();\n\\myspace\\space1\\hello();\n\\myspace\\myclass::hellomethod();\n\\myspace\\space1\\myclass::hellomethod();\necho \\myspace\\MAX . \"\\n\";\necho \\myspace\\space1\\MAX;\n?>" }, { "code": null, "e": 2760, "s": 2726, "text": "Above code shows following output" }, { "code": null, "e": 2834, "s": 2760, "text": "hello in myspace\nhello in space1\nhello in myspace\nhello in space1\n200\n100" } ]
Compare Pandas Dataframes using DataComPy - GeeksforGeeks
04 May, 2020 It’s well known that Python is a multi-paradigm, general-purpose language that is widely used for data analytics because of its extensive library support and an active community. The most commonly known methods to compare two Pandas dataframes using python are: Using difflib Using fuzzywuzzy Regex Match These methods are widely in use by seasoned and new developers but what if we require a report to find all of the matching/mismatching columns & rows? Here’s when the DataComPy library comes into the picture. DataComPy is a Pandas library open-sourced by capitalone. It was started with an aim to replace PROC COMPARE for Pandas data frames. It takes two dataframes as input and gives us a human-readable report containing statistics that lets us know the similarities and dissimilarities between the two dataframes. Install via pip3: pip3 install datacompy Example: from io import StringIOimport pandas as pdimport datacompy data1 = """employee_id, name1, rajiv kapoor2, rahul agarwal3, alice johnson""" data2 = """employee_id, name1, rajiv khanna2, rahul aggarwal3, alice tyson""" df1 = pd.read_csv(StringIO(data1))df2 = pd.read_csv(StringIO(data2)) compare = datacompy.Compare( df1, df2, # You can also specify a list # of columns join_columns = 'employee_id', # Optional, defaults to 0 abs_tol = 0, # Optional, defaults to 0 rel_tol = 0, # Optional, defaults to 'df1' df1_name = 'Original', # Optional, defaults to 'df2' df2_name = 'New' ) # if ignore_exra_columns=True, # the function won't return False# in case of non-overlapping # column namescompare.matches(ignore_extra_columns = False) # This method prints out a human-readable # report summarizing and sampling # differencesprint(compare.report()) Output: Explanation: In the above example, we are joining the two data frames on a matching column. We can also pass: on_index = True instead of “join_columns” to join on the index instead. Compare.matches() is a Boolean function. It returns True if there’s a match, else it returns False. DataComPy by default returns True only if there’s a 100% match. We can tweak this by setting the values of abs_tol & rel_tol to non-zero, which empowers us to specify an amount of deviation between numeric values that can be tolerated. They stand for absolute tolerance and relative tolerance respectively. We can see from the above example that DataComPy is a really powerful library & it is extremely helpful in cases when we have to generate a comparison report of 2 dataframes. Python pandas-dataFrame Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Convert integer to string in Python Convert string to integer in Python Python infinity How to set input type date in dd-mm-yyyy format using HTML ? Matplotlib.pyplot.title() in Python
[ { "code": null, "e": 24774, "s": 24746, "text": "\n04 May, 2020" }, { "code": null, "e": 25036, "s": 24774, "text": "It’s well known that Python is a multi-paradigm, general-purpose language that is widely used for data analytics because of its extensive library support and an active community. The most commonly known methods to compare two Pandas dataframes using python are:" }, { "code": null, "e": 25050, "s": 25036, "text": "Using difflib" }, { "code": null, "e": 25067, "s": 25050, "text": "Using fuzzywuzzy" }, { "code": null, "e": 25079, "s": 25067, "text": "Regex Match" }, { "code": null, "e": 25288, "s": 25079, "text": "These methods are widely in use by seasoned and new developers but what if we require a report to find all of the matching/mismatching columns & rows? Here’s when the DataComPy library comes into the picture." }, { "code": null, "e": 25596, "s": 25288, "text": "DataComPy is a Pandas library open-sourced by capitalone. It was started with an aim to replace PROC COMPARE for Pandas data frames. It takes two dataframes as input and gives us a human-readable report containing statistics that lets us know the similarities and dissimilarities between the two dataframes." }, { "code": null, "e": 25614, "s": 25596, "text": "Install via pip3:" }, { "code": null, "e": 25638, "s": 25614, "text": "pip3 install datacompy\n" }, { "code": null, "e": 25647, "s": 25638, "text": "Example:" }, { "code": "from io import StringIOimport pandas as pdimport datacompy data1 = \"\"\"employee_id, name1, rajiv kapoor2, rahul agarwal3, alice johnson\"\"\" data2 = \"\"\"employee_id, name1, rajiv khanna2, rahul aggarwal3, alice tyson\"\"\" df1 = pd.read_csv(StringIO(data1))df2 = pd.read_csv(StringIO(data2)) compare = datacompy.Compare( df1, df2, # You can also specify a list # of columns join_columns = 'employee_id', # Optional, defaults to 0 abs_tol = 0, # Optional, defaults to 0 rel_tol = 0, # Optional, defaults to 'df1' df1_name = 'Original', # Optional, defaults to 'df2' df2_name = 'New' ) # if ignore_exra_columns=True, # the function won't return False# in case of non-overlapping # column namescompare.matches(ignore_extra_columns = False) # This method prints out a human-readable # report summarizing and sampling # differencesprint(compare.report())", "e": 26585, "s": 25647, "text": null }, { "code": null, "e": 26593, "s": 26585, "text": "Output:" }, { "code": null, "e": 26606, "s": 26593, "text": "Explanation:" }, { "code": null, "e": 26775, "s": 26606, "text": "In the above example, we are joining the two data frames on a matching column. We can also pass: on_index = True instead of “join_columns” to join on the index instead." }, { "code": null, "e": 26875, "s": 26775, "text": "Compare.matches() is a Boolean function. It returns True if there’s a match, else it returns False." }, { "code": null, "e": 27182, "s": 26875, "text": "DataComPy by default returns True only if there’s a 100% match. We can tweak this by setting the values of abs_tol & rel_tol to non-zero, which empowers us to specify an amount of deviation between numeric values that can be tolerated. They stand for absolute tolerance and relative tolerance respectively." }, { "code": null, "e": 27357, "s": 27182, "text": "We can see from the above example that DataComPy is a really powerful library & it is extremely helpful in cases when we have to generate a comparison report of 2 dataframes." }, { "code": null, "e": 27381, "s": 27357, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27388, "s": 27381, "text": "Python" }, { "code": null, "e": 27404, "s": 27388, "text": "Write From Home" }, { "code": null, "e": 27502, "s": 27404, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27511, "s": 27502, "text": "Comments" }, { "code": null, "e": 27524, "s": 27511, "text": "Old Comments" }, { "code": null, "e": 27542, "s": 27524, "text": "Python Dictionary" }, { "code": null, "e": 27577, "s": 27542, "text": "Read a file line by line in Python" }, { "code": null, "e": 27599, "s": 27577, "text": "Enumerate() in Python" }, { "code": null, "e": 27631, "s": 27599, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27661, "s": 27631, "text": "Iterate over a list in Python" }, { "code": null, "e": 27697, "s": 27661, "text": "Convert integer to string in Python" }, { "code": null, "e": 27733, "s": 27697, "text": "Convert string to integer in Python" }, { "code": null, "e": 27749, "s": 27733, "text": "Python infinity" }, { "code": null, "e": 27810, "s": 27749, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Java Program for Gnome Sort
Gnome Sort works with one lement at a time and gets it to the actual position. Let us see an example to implement Gnome Sort − Live Demo import java.util.Arrays; public class Demo{ static void gnome_sort(int my_arr[], int n){ int index = 0; while (index < n){ if (index == 0) index++; if (my_arr[index] >= my_arr[index - 1]) index++; else{ int temp = 0; temp = my_arr[index]; my_arr[index] = my_arr[index - 1]; my_arr[index - 1] = temp; index--; } } return; } public static void main(String[] args){ int my_arr[] = { 34, 67, 89, 11, 0 , -21 }; gnome_sort(my_arr, my_arr.length); System.out.println("The array after perfroming gnome sort on it is "); System.out.println(Arrays.toString(my_arr)); } } The array after perfroming gnome sort on it is [-21, 0, 11, 34, 67, 89] A class named Demo contains a static function named ‘gnome_sort’. Here, a variable ‘index’ is assigned to 0. If that index value is less than the length of the array, the index value is checked for 0. If it is 0, it is incremented by 1. Otherwise, if the value at a specific index is greater than the value at array’s ‘index-1’, a variable named ‘temp’ is assigned 0 and the elements are swapped. The ‘index’ value is decremented. In the main function, an array is defined with certain values and the ‘gnome_sort’ function is called on this array and the length of the array. The output is printed on the console.
[ { "code": null, "e": 1189, "s": 1062, "text": "Gnome Sort works with one lement at a time and gets it to the actual position. Let us see an example to implement Gnome Sort −" }, { "code": null, "e": 1200, "s": 1189, "text": " Live Demo" }, { "code": null, "e": 1942, "s": 1200, "text": "import java.util.Arrays;\npublic class Demo{\n static void gnome_sort(int my_arr[], int n){\n int index = 0;\n while (index < n){\n if (index == 0)\n index++;\n if (my_arr[index] >= my_arr[index - 1])\n index++;\n else{\n int temp = 0;\n temp = my_arr[index];\n my_arr[index] = my_arr[index - 1];\n my_arr[index - 1] = temp;\n index--;\n }\n }\n return;\n }\n public static void main(String[] args){\n int my_arr[] = { 34, 67, 89, 11, 0 , -21 };\n gnome_sort(my_arr, my_arr.length);\n System.out.println(\"The array after perfroming gnome sort on it is \");\n System.out.println(Arrays.toString(my_arr));\n }\n}" }, { "code": null, "e": 2014, "s": 1942, "text": "The array after perfroming gnome sort on it is\n[-21, 0, 11, 34, 67, 89]" }, { "code": null, "e": 2445, "s": 2014, "text": "A class named Demo contains a static function named ‘gnome_sort’. Here, a variable ‘index’ is assigned to 0. If that index value is less than the length of the array, the index value is checked for 0. If it is 0, it is incremented by 1. Otherwise, if the value at a specific index is greater than the value at array’s ‘index-1’, a variable named ‘temp’ is assigned 0 and the elements are swapped. The ‘index’ value is decremented." }, { "code": null, "e": 2628, "s": 2445, "text": "In the main function, an array is defined with certain values and the ‘gnome_sort’ function is called on this array and the length of the array. The output is printed on the console." } ]
C library function - wcstombs()
The C library function size_t wcstombs(char *str, const wchar_t *pwcs, size_t n) converts the wide-character string pwcs to a multibyte string starting at str. At most n bytes are written to str. Following is the declaration for wcstombs() function. size_t wcstombs(char *str, const wchar_t *pwcs, size_t n) str − This is the pointer to an array of char elements at least n bytes long. str − This is the pointer to an array of char elements at least n bytes long. pwcs − This is wide-character string to be converted. pwcs − This is wide-character string to be converted. n − This is the maximum number of bytes to be written to str. n − This is the maximum number of bytes to be written to str. This function returns the number of bytes (not characters) converted and written to str, excluding the ending null-character. If an invalid multibyte character is encountered, -1 value is returned. The following example shows the usage of wcstombs() function. #include <stdio.h> #include <stdlib.h> #define BUFFER_SIZE 50 int main () { size_t ret; char *MB = (char *)malloc( BUFFER_SIZE ); wchar_t *WC = L"http://www.tutorialspoint.com"; /* converting wide-character string */ ret = wcstombs(MB, WC, BUFFER_SIZE); printf("Characters converted = %u\n", ret); printf("Multibyte character = %s\n\n", MB); return(0); } Let us compile and run the above program that will produce the following result − Characters converted = 29 Multibyte character = http://www.tutorialspoint.com 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2203, "s": 2007, "text": "The C library function size_t wcstombs(char *str, const wchar_t *pwcs, size_t n) converts the wide-character string pwcs to a multibyte string starting at str. At most n bytes are written to str." }, { "code": null, "e": 2257, "s": 2203, "text": "Following is the declaration for wcstombs() function." }, { "code": null, "e": 2315, "s": 2257, "text": "size_t wcstombs(char *str, const wchar_t *pwcs, size_t n)" }, { "code": null, "e": 2393, "s": 2315, "text": "str − This is the pointer to an array of char elements at least n bytes long." }, { "code": null, "e": 2471, "s": 2393, "text": "str − This is the pointer to an array of char elements at least n bytes long." }, { "code": null, "e": 2525, "s": 2471, "text": "pwcs − This is wide-character string to be converted." }, { "code": null, "e": 2579, "s": 2525, "text": "pwcs − This is wide-character string to be converted." }, { "code": null, "e": 2641, "s": 2579, "text": "n − This is the maximum number of bytes to be written to str." }, { "code": null, "e": 2703, "s": 2641, "text": "n − This is the maximum number of bytes to be written to str." }, { "code": null, "e": 2901, "s": 2703, "text": "This function returns the number of bytes (not characters) converted and written to str, excluding the ending null-character. If an invalid multibyte character is encountered, -1 value is returned." }, { "code": null, "e": 2963, "s": 2901, "text": "The following example shows the usage of wcstombs() function." }, { "code": null, "e": 3353, "s": 2963, "text": "#include <stdio.h>\n#include <stdlib.h>\n\n#define BUFFER_SIZE 50\n\nint main () {\n size_t ret;\n char *MB = (char *)malloc( BUFFER_SIZE );\n wchar_t *WC = L\"http://www.tutorialspoint.com\";\n\n /* converting wide-character string */\n ret = wcstombs(MB, WC, BUFFER_SIZE);\n \n printf(\"Characters converted = %u\\n\", ret);\n printf(\"Multibyte character = %s\\n\\n\", MB);\n \n return(0);\n}" }, { "code": null, "e": 3435, "s": 3353, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 3514, "s": 3435, "text": "Characters converted = 29\nMultibyte character = http://www.tutorialspoint.com\n" }, { "code": null, "e": 3547, "s": 3514, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3562, "s": 3547, "text": " Nishant Malik" }, { "code": null, "e": 3597, "s": 3562, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3612, "s": 3597, "text": " Nishant Malik" }, { "code": null, "e": 3647, "s": 3612, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3661, "s": 3647, "text": " Asif Hussain" }, { "code": null, "e": 3694, "s": 3661, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3712, "s": 3694, "text": " Richa Maheshwari" }, { "code": null, "e": 3747, "s": 3712, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3766, "s": 3747, "text": " Vandana Annavaram" }, { "code": null, "e": 3799, "s": 3766, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3811, "s": 3799, "text": " Amit Diwan" }, { "code": null, "e": 3818, "s": 3811, "text": " Print" }, { "code": null, "e": 3829, "s": 3818, "text": " Add Notes" } ]
C++ Program for Coefficient of variation
We are given with an array of float values of size n and the task is to find the coefficient of variation and display the result. What is the coefficient of variation? In statistic measure, coefficient of variation is used to find the range of variability through the data given. In terms of finance, coefficient of variation is used to find the amount of risk involved with respect to the amount invested. If the ratio between standard deviation and mean is low then the risk involved in the investment is also low. Coefficient of variation is the ratio between standard deviation and mean and it is given by − Coefficient of variation = Standard Deviation / Mean Input-: array[] = { 10.0, 21, 23, 90.0, 10.5, 32.56, 24, 45, 70.0 } Output-: coefficient of variation is : 0.75772 Input-: array[] = { 15.0, 36.0, 53.67, 25.45, 67.8, 56, 78.09} Output-: coefficient of variation is : 0.48177 Approach used in the given program is as follows − Input the array containing float values Calculate the value of mean and standard deviation on the given array Calculate the value of coefficient of variation by dividing the value of standard deviation with mean Display the result as coefficient of variation Start Step 1-> declare function to calculate the value of mean float cal_mean(float arr[], int size) Declare float sum = 0 Loop For i = 0 and i < size and i++ Set sum = sum + arr[i] End return sum / size Step 2-> declare function to calculate the value of standard deviation float StandardDeviation(float arr[], int size) Declare float sum = 0 Loop For i = 0 and i < size and i++ Set sum = sum + (arr[i] - cal_mean(arr, size)) * (arr[i] - End Call cal_mean(arr, size)) return sqrt(sum / (size - 1)) Step 3-> Declare function to calculate coefficient of variation float CoefficientOfVariation(float arr[], int size) return StandardDeviation(arr, size) / cal_mean(arr, size) Step 4-> In main() Declare an array of float arr[] = { 10.0, 21, 23, 90.0, 10.5, 32.56, 24, 45, 70.0} Calculate the size of array as int size = sizeof(arr) / sizeof(arr[0]) Call function as CoefficientOfVariation(arr, size) Stop Live Demo #include <bits/stdc++.h> using namespace std; // function to calculate the mean. float cal_mean(float arr[], int size) { float sum = 0; for (int i = 0; i < size; i++) sum = sum + arr[i]; return sum / size; } //function to calculate the standard deviation float StandardDeviation(float arr[], int size) { float sum = 0; for (int i = 0; i < size; i++) sum = sum + (arr[i] - cal_mean(arr, size)) * (arr[i] - cal_mean(arr, size)); return sqrt(sum / (size - 1)); } // function to calculate the coefficient of variation. float CoefficientOfVariation(float arr[], int size) { return StandardDeviation(arr, size) / cal_mean(arr, size); } int main() { float arr[] = { 10.0, 21, 23, 90.0, 10.5, 32.56, 24, 45, 70.0}; int size = sizeof(arr) / sizeof(arr[0]); cout<<"coefficient of variation is : "<<CoefficientOfVariation(arr, size); return 0; } coefficient of variation is : 0.75772
[ { "code": null, "e": 1192, "s": 1062, "text": "We are given with an array of float values of size n and the task is to find the coefficient of variation and display the result." }, { "code": null, "e": 1230, "s": 1192, "text": "What is the coefficient of variation?" }, { "code": null, "e": 1674, "s": 1230, "text": "In statistic measure, coefficient of variation is used to find the range of variability through the data given. In terms of finance, coefficient of variation is used to find the amount of risk involved with respect to the amount invested. If the ratio between standard deviation and mean is low then the risk involved in the investment is also low. Coefficient of variation is the ratio between standard deviation and mean and it is given by −" }, { "code": null, "e": 1728, "s": 1674, "text": "Coefficient of variation = Standard Deviation / Mean " }, { "code": null, "e": 1954, "s": 1728, "text": "Input-: array[] = { 10.0, 21, 23, 90.0, 10.5, 32.56, 24, 45, 70.0 }\nOutput-: coefficient of variation is : 0.75772\n\nInput-: array[] = { 15.0, 36.0, 53.67, 25.45, 67.8, 56, 78.09}\nOutput-: coefficient of variation is : 0.48177" }, { "code": null, "e": 2005, "s": 1954, "text": "Approach used in the given program is as follows −" }, { "code": null, "e": 2045, "s": 2005, "text": "Input the array containing float values" }, { "code": null, "e": 2115, "s": 2045, "text": "Calculate the value of mean and standard deviation on the given array" }, { "code": null, "e": 2217, "s": 2115, "text": "Calculate the value of coefficient of variation by dividing the value of standard deviation with mean" }, { "code": null, "e": 2265, "s": 2217, "text": "Display the result as coefficient of variation " }, { "code": null, "e": 3227, "s": 2265, "text": "Start\nStep 1-> declare function to calculate the value of mean\n float cal_mean(float arr[], int size)\n Declare float sum = 0\n Loop For i = 0 and i < size and i++\n Set sum = sum + arr[i]\n End\n return sum / size\nStep 2-> declare function to calculate the value of standard deviation\n float StandardDeviation(float arr[], int size)\n Declare float sum = 0\n Loop For i = 0 and i < size and i++\n Set sum = sum + (arr[i] - cal_mean(arr, size)) * (arr[i] -\n End\n Call cal_mean(arr, size))\n return sqrt(sum / (size - 1))\nStep 3-> Declare function to calculate coefficient of variation\n float CoefficientOfVariation(float arr[], int size)\n return StandardDeviation(arr, size) / cal_mean(arr, size)\nStep 4-> In main()\n Declare an array of float arr[] = { 10.0, 21, 23, 90.0, 10.5, 32.56, 24, 45, 70.0}\n Calculate the size of array as int size = sizeof(arr) / sizeof(arr[0])\n Call function as CoefficientOfVariation(arr, size)\nStop" }, { "code": null, "e": 3238, "s": 3227, "text": " Live Demo" }, { "code": null, "e": 4112, "s": 3238, "text": "#include <bits/stdc++.h>\nusing namespace std;\n// function to calculate the mean.\nfloat cal_mean(float arr[], int size) {\n float sum = 0;\n for (int i = 0; i < size; i++)\n sum = sum + arr[i];\n return sum / size;\n}\n//function to calculate the standard deviation\nfloat StandardDeviation(float arr[], int size) {\n float sum = 0;\n for (int i = 0; i < size; i++)\n sum = sum + (arr[i] - cal_mean(arr, size)) * (arr[i] - cal_mean(arr, size));\n return sqrt(sum / (size - 1));\n}\n// function to calculate the coefficient of variation.\nfloat CoefficientOfVariation(float arr[], int size) {\n return StandardDeviation(arr, size) / cal_mean(arr, size);\n}\nint main() {\n float arr[] = { 10.0, 21, 23, 90.0, 10.5, 32.56, 24, 45, 70.0};\n int size = sizeof(arr) / sizeof(arr[0]);\n cout<<\"coefficient of variation is : \"<<CoefficientOfVariation(arr, size);\n return 0;\n}" }, { "code": null, "e": 4150, "s": 4112, "text": "coefficient of variation is : 0.75772" } ]
Flutter - Deleting Data On The Internet - GeeksforGeeks
17 Sep, 2020 In this article, we will explore the process of deleting data on the internet. To, do so we need to follow 3 crucial steps: Import the http packageDelete the data on the serverUpdate the screen after deletion Import the http package Delete the data on the server Update the screen after deletion Now, we will explore them in detail. To install the http package use the below command in your command prompt: pub get or, if you are using the flutter cmd use the below command: flutter pub get After the installation add the dependency to the pubsec.yml file as shown below: Now import the http package in the main.dart file as shown below: import 'package:http/http.dart' as http; Now use the http.delete() method on the JSONPlaceHolder, to delete the Album with id=1 with as shown below: Dart Future<Response> deleteAlbum(String id) async { final http.Response response = await http.delete( 'https://jsonplaceholder.typicode.com/albums/$id', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, ); return response;} Here we will create a delete data button that can verify if a data has been deleted from the server by calling the http.get() method as shown below: Dart Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('${snapshot.data?.title ?? 'Deleted'}'), RaisedButton( child: Text('Delete Data'), onPressed: () { setState(() { _futureAlbum = deleteAlbum(snapshot.data.id.toString()); }); }, ), ],); Now, when you click on the Delete Data button, the deleteAlbum() method is called and the id you are passing is the id of the data that you retrieved from the internet. This means you are going to delete the same data that you fetched from the internet. After the data is deleted we will be needing to send a success or failure response. To do so look at the below response implementation: Dart Future<Album> deleteAlbum(String id) async { final http.Response response = await http.delete( 'https://jsonplaceholder.typicode.com/albums/$id', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, ); if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to delete album.'); }} Complete Source Code: Dart import 'dart:async';import 'dart:convert'; import 'package:flutter/material.dart';import 'package:http/http.dart' as http; Future<Album> fetchAlbum() async { final response = await http.get('https://jsonplaceholder.typicode.com/albums/1'); if (response.statusCode == 200) { // A 200 OK response means // ready to parse the JSON. return Album.fromJson(json.decode(response.body)); } else { // If not a 200 ok response // means throw an exception. throw Exception('Failed to load album'); }} Future<Album> deleteAlbum(String id) async { final http.Response response = await http.delete( 'https://jsonplaceholder.typicode.com/albums/$id', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, ); if (response.statusCode == 200) { return Album.fromJson(jsonDecode(response.body)); } else { throw Exception('Item Not Deleted!'); }} class Album { final int id; final String title; Album({this.id, this.title}); factory Album.fromJson(Map<String, dynamic> json) { return Album( id: json['id'], title: json['title'], ); }} void main() { runApp(MyApp());} class MyApp extends StatefulWidget { MyApp({Key key}) : super(key: key); @override _MyAppState createState() { return _MyAppState(); }} class _MyAppState extends State<MyApp> { Future<Album> _futureAlbum; @override void initState() { super.initState(); _futureAlbum = fetchAlbum(); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Data Deletion', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Center( child: FutureBuilder<Album>( future: _futureAlbum, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasData) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('${snapshot.data?.title ?? 'Deleted'}'), RaisedButton( child: Text('Delete Data'), onPressed: () { setState(() { _futureAlbum = deleteAlbum(snapshot.data.id.toString()); }); }, ), ], ); } else if (snapshot.hasError) { return Text("${snapshot.error}"); } } return CircularProgressIndicator(); }, ), ), ), ); }} Output: android Flutter Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Listview.builder in Flutter Flutter - Asset Image Splash Screen in Flutter Flutter - Custom Bottom Navigation Bar Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget Flutter - Flexible Widget Flutter - BoxShadow Widget
[ { "code": null, "e": 27269, "s": 27241, "text": "\n17 Sep, 2020" }, { "code": null, "e": 27393, "s": 27269, "text": "In this article, we will explore the process of deleting data on the internet. To, do so we need to follow 3 crucial steps:" }, { "code": null, "e": 27478, "s": 27393, "text": "Import the http packageDelete the data on the serverUpdate the screen after deletion" }, { "code": null, "e": 27502, "s": 27478, "text": "Import the http package" }, { "code": null, "e": 27532, "s": 27502, "text": "Delete the data on the server" }, { "code": null, "e": 27565, "s": 27532, "text": "Update the screen after deletion" }, { "code": null, "e": 27602, "s": 27565, "text": "Now, we will explore them in detail." }, { "code": null, "e": 27676, "s": 27602, "text": "To install the http package use the below command in your command prompt:" }, { "code": null, "e": 27684, "s": 27676, "text": "pub get" }, { "code": null, "e": 27744, "s": 27684, "text": "or, if you are using the flutter cmd use the below command:" }, { "code": null, "e": 27760, "s": 27744, "text": "flutter pub get" }, { "code": null, "e": 27841, "s": 27760, "text": "After the installation add the dependency to the pubsec.yml file as shown below:" }, { "code": null, "e": 27907, "s": 27841, "text": "Now import the http package in the main.dart file as shown below:" }, { "code": null, "e": 27951, "s": 27907, "text": "import 'package:http/http.dart' as http;\n\n\n" }, { "code": null, "e": 28060, "s": 27951, "text": "Now use the http.delete() method on the JSONPlaceHolder, to delete the Album with id=1 with as shown below:" }, { "code": null, "e": 28065, "s": 28060, "text": "Dart" }, { "code": "Future<Response> deleteAlbum(String id) async { final http.Response response = await http.delete( 'https://jsonplaceholder.typicode.com/albums/$id', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, ); return response;}", "e": 28337, "s": 28065, "text": null }, { "code": null, "e": 28486, "s": 28337, "text": "Here we will create a delete data button that can verify if a data has been deleted from the server by calling the http.get() method as shown below:" }, { "code": null, "e": 28491, "s": 28486, "text": "Dart" }, { "code": "Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('${snapshot.data?.title ?? 'Deleted'}'), RaisedButton( child: Text('Delete Data'), onPressed: () { setState(() { _futureAlbum = deleteAlbum(snapshot.data.id.toString()); }); }, ), ],);", "e": 28799, "s": 28491, "text": null }, { "code": null, "e": 29053, "s": 28799, "text": "Now, when you click on the Delete Data button, the deleteAlbum() method is called and the id you are passing is the id of the data that you retrieved from the internet. This means you are going to delete the same data that you fetched from the internet." }, { "code": null, "e": 29189, "s": 29053, "text": "After the data is deleted we will be needing to send a success or failure response. To do so look at the below response implementation:" }, { "code": null, "e": 29194, "s": 29189, "text": "Dart" }, { "code": "Future<Album> deleteAlbum(String id) async { final http.Response response = await http.delete( 'https://jsonplaceholder.typicode.com/albums/$id', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, ); if (response.statusCode == 200) { return Album.fromJson(json.decode(response.body)); } else { throw Exception('Failed to delete album.'); }}", "e": 29592, "s": 29194, "text": null }, { "code": null, "e": 29614, "s": 29592, "text": "Complete Source Code:" }, { "code": null, "e": 29619, "s": 29614, "text": "Dart" }, { "code": "import 'dart:async';import 'dart:convert'; import 'package:flutter/material.dart';import 'package:http/http.dart' as http; Future<Album> fetchAlbum() async { final response = await http.get('https://jsonplaceholder.typicode.com/albums/1'); if (response.statusCode == 200) { // A 200 OK response means // ready to parse the JSON. return Album.fromJson(json.decode(response.body)); } else { // If not a 200 ok response // means throw an exception. throw Exception('Failed to load album'); }} Future<Album> deleteAlbum(String id) async { final http.Response response = await http.delete( 'https://jsonplaceholder.typicode.com/albums/$id', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, ); if (response.statusCode == 200) { return Album.fromJson(jsonDecode(response.body)); } else { throw Exception('Item Not Deleted!'); }} class Album { final int id; final String title; Album({this.id, this.title}); factory Album.fromJson(Map<String, dynamic> json) { return Album( id: json['id'], title: json['title'], ); }} void main() { runApp(MyApp());} class MyApp extends StatefulWidget { MyApp({Key key}) : super(key: key); @override _MyAppState createState() { return _MyAppState(); }} class _MyAppState extends State<MyApp> { Future<Album> _futureAlbum; @override void initState() { super.initState(); _futureAlbum = fetchAlbum(); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Data Deletion', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Center( child: FutureBuilder<Album>( future: _futureAlbum, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasData) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('${snapshot.data?.title ?? 'Deleted'}'), RaisedButton( child: Text('Delete Data'), onPressed: () { setState(() { _futureAlbum = deleteAlbum(snapshot.data.id.toString()); }); }, ), ], ); } else if (snapshot.hasError) { return Text(\"${snapshot.error}\"); } } return CircularProgressIndicator(); }, ), ), ), ); }}", "e": 32463, "s": 29619, "text": null }, { "code": null, "e": 32471, "s": 32463, "text": "Output:" }, { "code": null, "e": 32479, "s": 32471, "text": "android" }, { "code": null, "e": 32487, "s": 32479, "text": "Flutter" }, { "code": null, "e": 32492, "s": 32487, "text": "Dart" }, { "code": null, "e": 32500, "s": 32492, "text": "Flutter" }, { "code": null, "e": 32598, "s": 32500, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32630, "s": 32598, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 32658, "s": 32630, "text": "Listview.builder in Flutter" }, { "code": null, "e": 32680, "s": 32658, "text": "Flutter - Asset Image" }, { "code": null, "e": 32705, "s": 32680, "text": "Splash Screen in Flutter" }, { "code": null, "e": 32744, "s": 32705, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 32776, "s": 32744, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 32815, "s": 32776, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 32841, "s": 32815, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 32867, "s": 32841, "text": "Flutter - Flexible Widget" } ]
GATE | GATE-CS-2015 (Set 1) | Question 45 - GeeksforGeeks
28 Jun, 2021 What is the output of the following C code? Assume that the address of x is 2000 (in decimal) and an integer requires four bytes of memory. #include <stdio.h>int main(){ unsigned int x[4][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}; printf("%u, %u, %u", x+3, *(x+3), *(x+2)+3);} (A) 2036, 2036, 2036(B) 2012, 4, 2204(C) 2036, 10, 10(D) 2012, 4, 6Answer: (A)Explanation: x = 2000 Since x is considered as a pointer to an array of 3 integers and an integer takes 4 bytes, value of x + 3 = 2000 + 3*3*4 = 2036 The expression, *(x + 3) also prints same address as x is 2D array. The expression *(x + 2) + 3 = 2000 + 2*3*4 + 3*4 = 2036 Quiz of this Question GATE-CS-2015 (Set 1) GATE-GATE-CS-2015 (Set 1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2015 (Set 1) | Question 53 GATE | GATE CS 2010 | Question 28 GATE | GATE-IT-2004 | Question 13
[ { "code": null, "e": 25715, "s": 25687, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25855, "s": 25715, "text": "What is the output of the following C code? Assume that the address of x is 2000 (in decimal) and an integer requires four bytes of memory." }, { "code": "#include <stdio.h>int main(){ unsigned int x[4][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}; printf(\"%u, %u, %u\", x+3, *(x+3), *(x+2)+3);}", "e": 26035, "s": 25855, "text": null }, { "code": null, "e": 26126, "s": 26035, "text": "(A) 2036, 2036, 2036(B) 2012, 4, 2204(C) 2036, 10, 10(D) 2012, 4, 6Answer: (A)Explanation:" }, { "code": null, "e": 26422, "s": 26126, "text": "x = 2000\n\nSince x is considered as a pointer to an \narray of 3 integers and an integer takes 4\nbytes, value of x + 3 = 2000 + 3*3*4 = 2036\n\nThe expression, *(x + 3) also prints same \naddress as x is 2D array.\n\n\nThe expression *(x + 2) + 3 = 2000 + 2*3*4 + 3*4\n = 2036\n" }, { "code": null, "e": 26444, "s": 26422, "text": "Quiz of this Question" }, { "code": null, "e": 26465, "s": 26444, "text": "GATE-CS-2015 (Set 1)" }, { "code": null, "e": 26491, "s": 26465, "text": "GATE-GATE-CS-2015 (Set 1)" }, { "code": null, "e": 26496, "s": 26491, "text": "GATE" }, { "code": null, "e": 26594, "s": 26496, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26628, "s": 26594, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26662, "s": 26628, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26695, "s": 26662, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26731, "s": 26695, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26765, "s": 26731, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26801, "s": 26765, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26835, "s": 26801, "text": "GATE | GATE-CS-2009 | Question 38" }, { "code": null, "e": 26877, "s": 26835, "text": "GATE | GATE-CS-2015 (Set 1) | Question 53" }, { "code": null, "e": 26911, "s": 26877, "text": "GATE | GATE CS 2010 | Question 28" } ]
Building a ResNet in Keras. Using Keras Functional API to construct... | by Dorian Lazar | Towards Data Science
In principle, neural networks should get better results as they have more layers. A deeper network can learn anything a shallower version of itself can, plus (possibly) more than that. If, for a given dataset, there are no more things a network can learn by adding more layers to it, then it can just learn the identity mapping for those additional layers. In this way, it preserves the information in the previous layers and can not do worse than shallower ones. A network should be able to learn at least the identity mapping if it doesn’t find something better than that. But in practice, things are not like that. Deeper networks are harder to optimize. With each extra layer that we add to a network, we add more difficulty in the process of training; it becomes harder for the optimization algorithm that we use to find the right parameters. As we add more layers, the network gets better results until at some point; then as we continue to add extra layers, the accuracy starts to drop. Residual Networks attempt to solve this issue by adding the so-called skip connections. A skip connection is depicted in the image above. As I said previously, deeper networks should be able to learn at least identity mappings; this is what skip connections do: they add identity mappings from one point in the network to a forward point, and then lets the network to learn just that extra F(x). If there are no more things the network can learn, then it just learns F(x) as being 0. It turns out that it is easier for the network to learn a mapping closer to 0 than the identity mapping. A block with a skip connection as in the image above is called a residual block, and a Residual Neural Network (ResNet) is just a concatenation of such blocks. An interesting fact is that our brains have structures similar to residual networks, for example, cortical layer VI neurons get input from layer I, skipping intermediary layers. If you are reading this, probably you are already familiar with the Sequential class which allows one to easily construct a neural network by just stacking layers one after another, like this: from keras.models import Sequentialfrom keras.layers import Dense, Activationmodel = Sequential([ Dense(32, input_shape=(784,)), Activation('relu'), Dense(10), Activation('softmax'),]) But this way of building neural networks is not sufficient for our needs. With the Sequential class, we can’t add skip connections. Keras also has the Model class, which can be used along with the functional API for creating layers to build more complex network architectures.When constructed, the class keras.layers.Input returns a tensor object. A layer object in Keras can also be used like a function, calling it with a tensor object as a parameter. The returned object is a tensor that can then be passed as input to another layer, and so on. As an example: from keras.layers import Input, Densefrom keras.models import Modelinputs = Input(shape=(784,))output_1 = Dense(64, activation='relu')(inputs)output_2 = Dense(64, activation='relu')(output_1)predictions = Dense(10, activation='softmax')(output_2)model = Model(inputs=inputs, outputs=predictions)model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])model.fit(data, labels) But the above code still constructs a network that is sequential, so no real use for this fancy functional syntax so far. The real use of this syntax is when using the so called Merge layers with which one can combine more input tensors. A few examples of these layers are: Add, Subtract, Multiply, Average. The one that we will need in building residual blocks is Add. An example that uses Add: from keras.layers import Input, Dense, Addfrom keras.models import Modelinput1 = Input(shape=(16,))x1 = Dense(8, activation='relu')(input1)input2 = Input(shape=(32,))x2 = Dense(8, activation='relu')(input2)added = Add()([x1, x2])out = Dense(4)(added)model = Model(inputs=[input1, input2], outputs=out) This is by no means a comprehensive guide to Keras functional API. If you want to learn more please refer to the docs. Next, we will implement a ResNet along with its plain (without skip connections) counterpart, for comparison. The ResNet that we will build here has the following structure: Input with shape (32, 32, 3) 1 Conv2D layer, with 64 filters 2, 5, 5, 2 residual blocks with 64, 128, 256, and 512 filters AveragePooling2D layer with pool size = 4 Flatten layer Dense layer with 10 output nodes It has a total of 30 conv+dense layers. All the kernel sizes are 3x3. We use ReLU activation and BatchNormalization after conv layers.The plain version is the same except for the skip connections. We create first a helper function that takes a tensor as input and adds relu and batch normalization to it: def relu_bn(inputs: Tensor) -> Tensor: relu = ReLU()(inputs) bn = BatchNormalization()(relu) return bn Then we create a function for constructing a residual block. It takes a tensor x as input and passes it through 2 conv layers; let's call the output of these 2 conv layers as y. Then adds the input x to y, adds relu and batch normalization, and then returns the resulting tensor. When parameter downsample == True the first conv layer uses strides=2 to halve the output size and we use a conv layer with kernel_size=1 on input x to make it the same shape as y. The Add layer requires the input tensors to be of the same shape. def residual_block(x: Tensor, downsample: bool, filters: int, kernel_size: int = 3) -> Tensor: y = Conv2D(kernel_size=kernel_size, strides= (1 if not downsample else 2), filters=filters, padding="same")(x) y = relu_bn(y) y = Conv2D(kernel_size=kernel_size, strides=1, filters=filters, padding="same")(y) if downsample: x = Conv2D(kernel_size=1, strides=2, filters=filters, padding="same")(x) out = Add()([x, y]) out = relu_bn(out) return out create_res_net() function puts everything together.Here is the full code for this: The plain network is constructed in a similar way, but it doesn’t have skip connections and we don’t use the residual_block() helper function; everything is done inside create_plain_net().The code for the plain network: CIFAR-10 is a dataset of 32x32 rgb images over 10 categories. It contains 50k train images and 10k test images.Below is a sample of 10 random images from each class: We will train both ResNet and PlainNet on this dataset for 20 epochs, and then compare the results. The training took about 55 min for each ResNet and PlainNet on a machine with 1 NVIDIA Tesla K80. There is no significant difference in training time between ResNet and PlainNet.The results that we got are shown below. So, we got an increase of 1.59% in validation accuracy by using a ResNet on this dataset. The difference should be bigger on deeper networks. Feel free to experiment and see the results that you get. Deep Residual Learning for Image RecognitionResidual neural network — WikipediaGuide to the Functional API — Keras documentationModel (functional API) — Keras documentationMerge Layers — Keras documentationCIFAR-10 and CIFAR-100 datasets Deep Residual Learning for Image Recognition Residual neural network — Wikipedia Guide to the Functional API — Keras documentation Model (functional API) — Keras documentation Merge Layers — Keras documentation CIFAR-10 and CIFAR-100 datasets I hope you found this information useful and thanks for reading! This article is also posted on my own website here. Feel free to have a look!
[ { "code": null, "e": 746, "s": 171, "text": "In principle, neural networks should get better results as they have more layers. A deeper network can learn anything a shallower version of itself can, plus (possibly) more than that. If, for a given dataset, there are no more things a network can learn by adding more layers to it, then it can just learn the identity mapping for those additional layers. In this way, it preserves the information in the previous layers and can not do worse than shallower ones. A network should be able to learn at least the identity mapping if it doesn’t find something better than that." }, { "code": null, "e": 1165, "s": 746, "text": "But in practice, things are not like that. Deeper networks are harder to optimize. With each extra layer that we add to a network, we add more difficulty in the process of training; it becomes harder for the optimization algorithm that we use to find the right parameters. As we add more layers, the network gets better results until at some point; then as we continue to add extra layers, the accuracy starts to drop." }, { "code": null, "e": 1754, "s": 1165, "text": "Residual Networks attempt to solve this issue by adding the so-called skip connections. A skip connection is depicted in the image above. As I said previously, deeper networks should be able to learn at least identity mappings; this is what skip connections do: they add identity mappings from one point in the network to a forward point, and then lets the network to learn just that extra F(x). If there are no more things the network can learn, then it just learns F(x) as being 0. It turns out that it is easier for the network to learn a mapping closer to 0 than the identity mapping." }, { "code": null, "e": 1914, "s": 1754, "text": "A block with a skip connection as in the image above is called a residual block, and a Residual Neural Network (ResNet) is just a concatenation of such blocks." }, { "code": null, "e": 2092, "s": 1914, "text": "An interesting fact is that our brains have structures similar to residual networks, for example, cortical layer VI neurons get input from layer I, skipping intermediary layers." }, { "code": null, "e": 2285, "s": 2092, "text": "If you are reading this, probably you are already familiar with the Sequential class which allows one to easily construct a neural network by just stacking layers one after another, like this:" }, { "code": null, "e": 2482, "s": 2285, "text": "from keras.models import Sequentialfrom keras.layers import Dense, Activationmodel = Sequential([ Dense(32, input_shape=(784,)), Activation('relu'), Dense(10), Activation('softmax'),])" }, { "code": null, "e": 3030, "s": 2482, "text": "But this way of building neural networks is not sufficient for our needs. With the Sequential class, we can’t add skip connections. Keras also has the Model class, which can be used along with the functional API for creating layers to build more complex network architectures.When constructed, the class keras.layers.Input returns a tensor object. A layer object in Keras can also be used like a function, calling it with a tensor object as a parameter. The returned object is a tensor that can then be passed as input to another layer, and so on." }, { "code": null, "e": 3045, "s": 3030, "text": "As an example:" }, { "code": null, "e": 3476, "s": 3045, "text": "from keras.layers import Input, Densefrom keras.models import Modelinputs = Input(shape=(784,))output_1 = Dense(64, activation='relu')(inputs)output_2 = Dense(64, activation='relu')(output_1)predictions = Dense(10, activation='softmax')(output_2)model = Model(inputs=inputs, outputs=predictions)model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])model.fit(data, labels)" }, { "code": null, "e": 3846, "s": 3476, "text": "But the above code still constructs a network that is sequential, so no real use for this fancy functional syntax so far. The real use of this syntax is when using the so called Merge layers with which one can combine more input tensors. A few examples of these layers are: Add, Subtract, Multiply, Average. The one that we will need in building residual blocks is Add." }, { "code": null, "e": 3872, "s": 3846, "text": "An example that uses Add:" }, { "code": null, "e": 4174, "s": 3872, "text": "from keras.layers import Input, Dense, Addfrom keras.models import Modelinput1 = Input(shape=(16,))x1 = Dense(8, activation='relu')(input1)input2 = Input(shape=(32,))x2 = Dense(8, activation='relu')(input2)added = Add()([x1, x2])out = Dense(4)(added)model = Model(inputs=[input1, input2], outputs=out)" }, { "code": null, "e": 4293, "s": 4174, "text": "This is by no means a comprehensive guide to Keras functional API. If you want to learn more please refer to the docs." }, { "code": null, "e": 4403, "s": 4293, "text": "Next, we will implement a ResNet along with its plain (without skip connections) counterpart, for comparison." }, { "code": null, "e": 4467, "s": 4403, "text": "The ResNet that we will build here has the following structure:" }, { "code": null, "e": 4496, "s": 4467, "text": "Input with shape (32, 32, 3)" }, { "code": null, "e": 4528, "s": 4496, "text": "1 Conv2D layer, with 64 filters" }, { "code": null, "e": 4590, "s": 4528, "text": "2, 5, 5, 2 residual blocks with 64, 128, 256, and 512 filters" }, { "code": null, "e": 4632, "s": 4590, "text": "AveragePooling2D layer with pool size = 4" }, { "code": null, "e": 4646, "s": 4632, "text": "Flatten layer" }, { "code": null, "e": 4679, "s": 4646, "text": "Dense layer with 10 output nodes" }, { "code": null, "e": 4876, "s": 4679, "text": "It has a total of 30 conv+dense layers. All the kernel sizes are 3x3. We use ReLU activation and BatchNormalization after conv layers.The plain version is the same except for the skip connections." }, { "code": null, "e": 4984, "s": 4876, "text": "We create first a helper function that takes a tensor as input and adds relu and batch normalization to it:" }, { "code": null, "e": 5096, "s": 4984, "text": "def relu_bn(inputs: Tensor) -> Tensor: relu = ReLU()(inputs) bn = BatchNormalization()(relu) return bn" }, { "code": null, "e": 5623, "s": 5096, "text": "Then we create a function for constructing a residual block. It takes a tensor x as input and passes it through 2 conv layers; let's call the output of these 2 conv layers as y. Then adds the input x to y, adds relu and batch normalization, and then returns the resulting tensor. When parameter downsample == True the first conv layer uses strides=2 to halve the output size and we use a conv layer with kernel_size=1 on input x to make it the same shape as y. The Add layer requires the input tensors to be of the same shape." }, { "code": null, "e": 6270, "s": 5623, "text": "def residual_block(x: Tensor, downsample: bool, filters: int, kernel_size: int = 3) -> Tensor: y = Conv2D(kernel_size=kernel_size, strides= (1 if not downsample else 2), filters=filters, padding=\"same\")(x) y = relu_bn(y) y = Conv2D(kernel_size=kernel_size, strides=1, filters=filters, padding=\"same\")(y) if downsample: x = Conv2D(kernel_size=1, strides=2, filters=filters, padding=\"same\")(x) out = Add()([x, y]) out = relu_bn(out) return out" }, { "code": null, "e": 6353, "s": 6270, "text": "create_res_net() function puts everything together.Here is the full code for this:" }, { "code": null, "e": 6573, "s": 6353, "text": "The plain network is constructed in a similar way, but it doesn’t have skip connections and we don’t use the residual_block() helper function; everything is done inside create_plain_net().The code for the plain network:" }, { "code": null, "e": 6739, "s": 6573, "text": "CIFAR-10 is a dataset of 32x32 rgb images over 10 categories. It contains 50k train images and 10k test images.Below is a sample of 10 random images from each class:" }, { "code": null, "e": 6839, "s": 6739, "text": "We will train both ResNet and PlainNet on this dataset for 20 epochs, and then compare the results." }, { "code": null, "e": 7058, "s": 6839, "text": "The training took about 55 min for each ResNet and PlainNet on a machine with 1 NVIDIA Tesla K80. There is no significant difference in training time between ResNet and PlainNet.The results that we got are shown below." }, { "code": null, "e": 7258, "s": 7058, "text": "So, we got an increase of 1.59% in validation accuracy by using a ResNet on this dataset. The difference should be bigger on deeper networks. Feel free to experiment and see the results that you get." }, { "code": null, "e": 7496, "s": 7258, "text": "Deep Residual Learning for Image RecognitionResidual neural network — WikipediaGuide to the Functional API — Keras documentationModel (functional API) — Keras documentationMerge Layers — Keras documentationCIFAR-10 and CIFAR-100 datasets" }, { "code": null, "e": 7541, "s": 7496, "text": "Deep Residual Learning for Image Recognition" }, { "code": null, "e": 7577, "s": 7541, "text": "Residual neural network — Wikipedia" }, { "code": null, "e": 7627, "s": 7577, "text": "Guide to the Functional API — Keras documentation" }, { "code": null, "e": 7672, "s": 7627, "text": "Model (functional API) — Keras documentation" }, { "code": null, "e": 7707, "s": 7672, "text": "Merge Layers — Keras documentation" }, { "code": null, "e": 7739, "s": 7707, "text": "CIFAR-10 and CIFAR-100 datasets" }, { "code": null, "e": 7804, "s": 7739, "text": "I hope you found this information useful and thanks for reading!" } ]
Create An API To Deploy Machine Learning Models Using Flask and Heroku | by Elizabeth Ter Sahakyan | Towards Data Science
Machine Learning models are powerful tools to make predictions based on available data. To make these models useful, they need to be deployed so that other’s can easily access them through an API (application programming interface) to make predictions. This can be done using Flask and Heroku — Flask is a micro web framework that does not require particular tools or libraries to create web applications and Heroku is a cloud platform that can host web applications. To successfully deploy a machine learning model with Flask and Heroku, you will need the files: model.pkl, app.py, requirements.txt, and a Procfile. This article will go through how to create each of these required files and finally deploy the app on Heroku. The main sections of this post are as follows: Create GitHub Repository (optional) Create and Pickle a Model Using Titanic Data Create Flask App Test Flask App Locally (optional) Deploy to Heroku Test Working App Feel free to skip over any of them depending on where you are at in your process! For easier deploying on Heroku later, you’ll want to create a github repository for this project and clone it for local use. To create a new repository, click on your profile icon in the top right corner, click repositories, and then click new. Give your repository a name, initialize the repository with a README and add a license like my example below: To clone the repository, go to the repository page, click “clone or download” and copy the link. In your terminal, go to the folder where you want to clone the repository and type the command: git clone link_to_repository Running this command will clone the repository to your local machine and you can check to make sure that the folder was created in the right location. Now that the repo is set up, we can create the machine learning model and pickle it. First, let’s create a simple Logistic Regression model using the Titanic dataset. This model will predict whether someone survived the Titanic given information about class, age, number of siblings, and fare. If you’d like to follow along with my examples, you can find the csv file for the dataset here. Create a Jupyter notebook inside your working directory and create the model by running the code below: import pandas as pdfrom sklearn.linear_model import LogisticRegression# create dftrain = pd.read_csv('titanic.csv') # change file path# drop null valuestrain.dropna(inplace=True)# features and targettarget = 'Survived'features = ['Pclass', 'Age', 'SibSp', 'Fare']# X matrix, y vectorX = train[features]y = train[target]# model model = LogisticRegression()model.fit(X, y)model.score(X, y) The code above creates a pandas dataframe from the csv data, drops null values, defines the features and target for the model, splits the data into a matrix with just the features and a vector with the target, and fits a logistic regression model, then scores it. This creates a model that can predict the survivorship of Titanic passengers with ~70% accuracy which can then be pickled using: import picklepickle.dump(model, open(‘model.pkl’, ‘wb’)) The pickle file can be found inside the same directory as your Jupyter notebook. Open up your IDE (I use PyCharm) and create a new .py file inside the working directory named app.py The code for the flask application can be found below (python v3.7). import pandas as pdfrom flask import Flask, jsonify, requestimport pickle# load modelmodel = pickle.load(open('model.pkl','rb'))# appapp = Flask(__name__)# [email protected]('/', methods=['POST'])def predict(): # get data data = request.get_json(force=True) # convert data into dataframe data.update((x, [y]) for x, y in data.items()) data_df = pd.DataFrame.from_dict(data) # predictions result = model.predict(data_df) # send back to browser output = {'results': int(result[0])} # return data return jsonify(results=output)if __name__ == '__main__': app.run(port = 5000, debug=True) The structure of the code follows: Load pickled model Name flask app Create a route that receives JSON inputs, uses the trained model to make a prediction, and returns that prediction in a JSON format, which can be accessed through the API endpoint. Inside the route, I converted the JSON data to a pandas dataframe object because I found that this works with most (not all!) types of models that you will want to use to make a prediction. You can choose to convert the inputs using your preferred method as long as it works with the .predict() method for your model. The order of inputs must match the order of columns in the dataframe that you used to train your model otherwise you will get an error when you try to make a prediction. If the inputs you are receiving are not in the correct order you can easily reorder them after you create the dataframe. The takeaway here is that you need to convert the JSON data that you get from the request to a data structure that the model can use to make a prediction. However you get there is up to you. Once you paste this into your app.py file you can run the flask app from the command line (or if you’re using PyCharm just run the code). To run the app from the command line use: python app.py If done correctly, you will see something like this: Note on errors: If this is your first time creating a flask app you might get an error that you need to install flask into your python environment. Use !pip install flask and try again. When your flask app is up and running, click on the link in blue and you should see this — it’s normal: Import requests and json in your Jupyter notebook, then create a variable with your local server if it’s different from below: # local urlurl = 'http://127.0.0.1:5000' # change to your url Create sample data and convert to JSON: # sample datadata = {'Pclass': 3 , 'Age': 2 , 'SibSp': 1 , 'Fare': 50}data = json.dumps(data) Post sample data and check response code using requests.post(url, data). You want to get a response code of 200 to make sure that the app is working: Then you can print the JSON of the request to see the model’s prediction: The model predicted 1 which means the passenger survived 🙌 Shut down the flask app by typing ctrl+c when you’re done testing. A Procfile specifies the commands that are executed by a Heroku app on startup. To create one, open up a new file named Procfile (no extension) in the working directory and paste the following. web: gunicorn app:app And that’s it. Save and close. ✅ The requirements.txt file will contain all of the dependencies for the flask app. To create a requirements.txt, run the following in your terminal from the working directory: pip freeze > requirements.txt If you’re not working from a new environment, this file will contain all requirements from your current environment. If you get errors later when deploying the app, you can just delete the requirements that give you an error. At the bare minimum for this project, your requirements.txt should contain: Flask==1.1.1gunicorn==19.9.0pandas==0.25.0requests==2.22.0scikit-learn==0.21.2scipy==1.3.1 Run the following commands to commit the files to git: # add all files from the working directorygit add . then commit with your message: git commit -m 'add flask files' and finally, push changes to Github using the following command. You may be asked to enter your github username and password. If you have 2FA set up, you will need your key as the password. git push origin master At minimum, your Github repo should now contain: app.py model.pkl Procfile requirements.txt Note: all of these files should be at the working directory level and not in another folder If you don’t have one already, create a free account at www.heroku.com. Create a new app simply by choosing a name and clicking “create app”. This name doesn’t matter but it does have to be unique. You have a few options for the way you can deploy the app. I’ve tried both the Heroku CLI and GitHub and I personally prefer GitHub....but I’ll show both so pick whichever one you want to follow. Connect your github account by clicking the github icon below: Search for the correct repository and click connect: And then just scroll to the bottom of the page and click “Deploy Branch” If everything worked correctly you should see this message 🎉🎉 If something went wrong, check your requirements.txt, delete and dependencies that are giving you problems, and try again ̄\_(ツ)_/ ̄ In the Heroku CLI section, you will see these instructions to follow for deployment. Paste each command into your terminal and follow any prompts like logging in. Pay attention to any commands you will need to modify, such as cd my-project/ — where my-project/ should actually be your project directory. The git remote should be set to the app name from Heroku EXACTLY. If you were successful in following these instructions, you should see build succeeded on the overview page 🎉🎉 If not, you can check to see what went wrong by running heroku logs --tail from the command line. If you already tested your flask app, these instructions will be very similar, except now with the Heroku app url. Import requests and json in your Jupyter notebook, then create a variable to store the Heroku app url (you can find this by clicking “open app” in the top right corner of the app page on Heroku). Then create some sample data and convert it to JSON: # heroku urlheroku_url = 'https://titanic-flask-model.herokuapp.com' # change to your app name# sample datadata = { 'Pclass': 3 , 'Age': 2 , 'SibSp': 1 , 'Fare': 50}data = json.dumps(data) Check the response code using the following code. A response code of 200 means everything is running correctly. send_request = requests.post(heroku_url, data)print(send_request) Output: <Response [200]> And finally, look at the model’s prediction: print(send_request.json()) Output: {‘results’: {‘results’: 1}} Your output results will vary if you’re using different sample data. The result of 1 in this case means that the model predicts the passenger survived — and more importantly the API works! Now people can access your API endpoint with the Heroku URL and use your model to make predictions in the real world 🌐 Here is the github repo containing all files and code required to deploy this API. Find me on twitter @elizabethets or connect with me on LinkedIn!
[ { "code": null, "e": 640, "s": 172, "text": "Machine Learning models are powerful tools to make predictions based on available data. To make these models useful, they need to be deployed so that other’s can easily access them through an API (application programming interface) to make predictions. This can be done using Flask and Heroku — Flask is a micro web framework that does not require particular tools or libraries to create web applications and Heroku is a cloud platform that can host web applications." }, { "code": null, "e": 946, "s": 640, "text": "To successfully deploy a machine learning model with Flask and Heroku, you will need the files: model.pkl, app.py, requirements.txt, and a Procfile. This article will go through how to create each of these required files and finally deploy the app on Heroku. The main sections of this post are as follows:" }, { "code": null, "e": 982, "s": 946, "text": "Create GitHub Repository (optional)" }, { "code": null, "e": 1027, "s": 982, "text": "Create and Pickle a Model Using Titanic Data" }, { "code": null, "e": 1044, "s": 1027, "text": "Create Flask App" }, { "code": null, "e": 1078, "s": 1044, "text": "Test Flask App Locally (optional)" }, { "code": null, "e": 1095, "s": 1078, "text": "Deploy to Heroku" }, { "code": null, "e": 1112, "s": 1095, "text": "Test Working App" }, { "code": null, "e": 1194, "s": 1112, "text": "Feel free to skip over any of them depending on where you are at in your process!" }, { "code": null, "e": 1549, "s": 1194, "text": "For easier deploying on Heroku later, you’ll want to create a github repository for this project and clone it for local use. To create a new repository, click on your profile icon in the top right corner, click repositories, and then click new. Give your repository a name, initialize the repository with a README and add a license like my example below:" }, { "code": null, "e": 1742, "s": 1549, "text": "To clone the repository, go to the repository page, click “clone or download” and copy the link. In your terminal, go to the folder where you want to clone the repository and type the command:" }, { "code": null, "e": 1771, "s": 1742, "text": "git clone link_to_repository" }, { "code": null, "e": 2007, "s": 1771, "text": "Running this command will clone the repository to your local machine and you can check to make sure that the folder was created in the right location. Now that the repo is set up, we can create the machine learning model and pickle it." }, { "code": null, "e": 2416, "s": 2007, "text": "First, let’s create a simple Logistic Regression model using the Titanic dataset. This model will predict whether someone survived the Titanic given information about class, age, number of siblings, and fare. If you’d like to follow along with my examples, you can find the csv file for the dataset here. Create a Jupyter notebook inside your working directory and create the model by running the code below:" }, { "code": null, "e": 2804, "s": 2416, "text": "import pandas as pdfrom sklearn.linear_model import LogisticRegression# create dftrain = pd.read_csv('titanic.csv') # change file path# drop null valuestrain.dropna(inplace=True)# features and targettarget = 'Survived'features = ['Pclass', 'Age', 'SibSp', 'Fare']# X matrix, y vectorX = train[features]y = train[target]# model model = LogisticRegression()model.fit(X, y)model.score(X, y)" }, { "code": null, "e": 3068, "s": 2804, "text": "The code above creates a pandas dataframe from the csv data, drops null values, defines the features and target for the model, splits the data into a matrix with just the features and a vector with the target, and fits a logistic regression model, then scores it." }, { "code": null, "e": 3197, "s": 3068, "text": "This creates a model that can predict the survivorship of Titanic passengers with ~70% accuracy which can then be pickled using:" }, { "code": null, "e": 3254, "s": 3197, "text": "import picklepickle.dump(model, open(‘model.pkl’, ‘wb’))" }, { "code": null, "e": 3335, "s": 3254, "text": "The pickle file can be found inside the same directory as your Jupyter notebook." }, { "code": null, "e": 3436, "s": 3335, "text": "Open up your IDE (I use PyCharm) and create a new .py file inside the working directory named app.py" }, { "code": null, "e": 3505, "s": 3436, "text": "The code for the flask application can be found below (python v3.7)." }, { "code": null, "e": 4124, "s": 3505, "text": "import pandas as pdfrom flask import Flask, jsonify, requestimport pickle# load modelmodel = pickle.load(open('model.pkl','rb'))# appapp = Flask(__name__)# [email protected]('/', methods=['POST'])def predict(): # get data data = request.get_json(force=True) # convert data into dataframe data.update((x, [y]) for x, y in data.items()) data_df = pd.DataFrame.from_dict(data) # predictions result = model.predict(data_df) # send back to browser output = {'results': int(result[0])} # return data return jsonify(results=output)if __name__ == '__main__': app.run(port = 5000, debug=True)" }, { "code": null, "e": 4159, "s": 4124, "text": "The structure of the code follows:" }, { "code": null, "e": 4178, "s": 4159, "text": "Load pickled model" }, { "code": null, "e": 4193, "s": 4178, "text": "Name flask app" }, { "code": null, "e": 4374, "s": 4193, "text": "Create a route that receives JSON inputs, uses the trained model to make a prediction, and returns that prediction in a JSON format, which can be accessed through the API endpoint." }, { "code": null, "e": 4983, "s": 4374, "text": "Inside the route, I converted the JSON data to a pandas dataframe object because I found that this works with most (not all!) types of models that you will want to use to make a prediction. You can choose to convert the inputs using your preferred method as long as it works with the .predict() method for your model. The order of inputs must match the order of columns in the dataframe that you used to train your model otherwise you will get an error when you try to make a prediction. If the inputs you are receiving are not in the correct order you can easily reorder them after you create the dataframe." }, { "code": null, "e": 5174, "s": 4983, "text": "The takeaway here is that you need to convert the JSON data that you get from the request to a data structure that the model can use to make a prediction. However you get there is up to you." }, { "code": null, "e": 5354, "s": 5174, "text": "Once you paste this into your app.py file you can run the flask app from the command line (or if you’re using PyCharm just run the code). To run the app from the command line use:" }, { "code": null, "e": 5368, "s": 5354, "text": "python app.py" }, { "code": null, "e": 5421, "s": 5368, "text": "If done correctly, you will see something like this:" }, { "code": null, "e": 5607, "s": 5421, "text": "Note on errors: If this is your first time creating a flask app you might get an error that you need to install flask into your python environment. Use !pip install flask and try again." }, { "code": null, "e": 5711, "s": 5607, "text": "When your flask app is up and running, click on the link in blue and you should see this — it’s normal:" }, { "code": null, "e": 5838, "s": 5711, "text": "Import requests and json in your Jupyter notebook, then create a variable with your local server if it’s different from below:" }, { "code": null, "e": 5900, "s": 5838, "text": "# local urlurl = 'http://127.0.0.1:5000' # change to your url" }, { "code": null, "e": 5940, "s": 5900, "text": "Create sample data and convert to JSON:" }, { "code": null, "e": 6049, "s": 5940, "text": "# sample datadata = {'Pclass': 3 , 'Age': 2 , 'SibSp': 1 , 'Fare': 50}data = json.dumps(data)" }, { "code": null, "e": 6199, "s": 6049, "text": "Post sample data and check response code using requests.post(url, data). You want to get a response code of 200 to make sure that the app is working:" }, { "code": null, "e": 6273, "s": 6199, "text": "Then you can print the JSON of the request to see the model’s prediction:" }, { "code": null, "e": 6332, "s": 6273, "text": "The model predicted 1 which means the passenger survived 🙌" }, { "code": null, "e": 6399, "s": 6332, "text": "Shut down the flask app by typing ctrl+c when you’re done testing." }, { "code": null, "e": 6593, "s": 6399, "text": "A Procfile specifies the commands that are executed by a Heroku app on startup. To create one, open up a new file named Procfile (no extension) in the working directory and paste the following." }, { "code": null, "e": 6615, "s": 6593, "text": "web: gunicorn app:app" }, { "code": null, "e": 6648, "s": 6615, "text": "And that’s it. Save and close. ✅" }, { "code": null, "e": 6823, "s": 6648, "text": "The requirements.txt file will contain all of the dependencies for the flask app. To create a requirements.txt, run the following in your terminal from the working directory:" }, { "code": null, "e": 6853, "s": 6823, "text": "pip freeze > requirements.txt" }, { "code": null, "e": 7079, "s": 6853, "text": "If you’re not working from a new environment, this file will contain all requirements from your current environment. If you get errors later when deploying the app, you can just delete the requirements that give you an error." }, { "code": null, "e": 7155, "s": 7079, "text": "At the bare minimum for this project, your requirements.txt should contain:" }, { "code": null, "e": 7246, "s": 7155, "text": "Flask==1.1.1gunicorn==19.9.0pandas==0.25.0requests==2.22.0scikit-learn==0.21.2scipy==1.3.1" }, { "code": null, "e": 7301, "s": 7246, "text": "Run the following commands to commit the files to git:" }, { "code": null, "e": 7353, "s": 7301, "text": "# add all files from the working directorygit add ." }, { "code": null, "e": 7384, "s": 7353, "text": "then commit with your message:" }, { "code": null, "e": 7416, "s": 7384, "text": "git commit -m 'add flask files'" }, { "code": null, "e": 7606, "s": 7416, "text": "and finally, push changes to Github using the following command. You may be asked to enter your github username and password. If you have 2FA set up, you will need your key as the password." }, { "code": null, "e": 7629, "s": 7606, "text": "git push origin master" }, { "code": null, "e": 7678, "s": 7629, "text": "At minimum, your Github repo should now contain:" }, { "code": null, "e": 7685, "s": 7678, "text": "app.py" }, { "code": null, "e": 7695, "s": 7685, "text": "model.pkl" }, { "code": null, "e": 7704, "s": 7695, "text": "Procfile" }, { "code": null, "e": 7721, "s": 7704, "text": "requirements.txt" }, { "code": null, "e": 7813, "s": 7721, "text": "Note: all of these files should be at the working directory level and not in another folder" }, { "code": null, "e": 7885, "s": 7813, "text": "If you don’t have one already, create a free account at www.heroku.com." }, { "code": null, "e": 8011, "s": 7885, "text": "Create a new app simply by choosing a name and clicking “create app”. This name doesn’t matter but it does have to be unique." }, { "code": null, "e": 8207, "s": 8011, "text": "You have a few options for the way you can deploy the app. I’ve tried both the Heroku CLI and GitHub and I personally prefer GitHub....but I’ll show both so pick whichever one you want to follow." }, { "code": null, "e": 8270, "s": 8207, "text": "Connect your github account by clicking the github icon below:" }, { "code": null, "e": 8323, "s": 8270, "text": "Search for the correct repository and click connect:" }, { "code": null, "e": 8396, "s": 8323, "text": "And then just scroll to the bottom of the page and click “Deploy Branch”" }, { "code": null, "e": 8458, "s": 8396, "text": "If everything worked correctly you should see this message 🎉🎉" }, { "code": null, "e": 8592, "s": 8458, "text": "If something went wrong, check your requirements.txt, delete and dependencies that are giving you problems, and try again ̄\\_(ツ)_/ ̄" }, { "code": null, "e": 8962, "s": 8592, "text": "In the Heroku CLI section, you will see these instructions to follow for deployment. Paste each command into your terminal and follow any prompts like logging in. Pay attention to any commands you will need to modify, such as cd my-project/ — where my-project/ should actually be your project directory. The git remote should be set to the app name from Heroku EXACTLY." }, { "code": null, "e": 9073, "s": 8962, "text": "If you were successful in following these instructions, you should see build succeeded on the overview page 🎉🎉" }, { "code": null, "e": 9171, "s": 9073, "text": "If not, you can check to see what went wrong by running heroku logs --tail from the command line." }, { "code": null, "e": 9286, "s": 9171, "text": "If you already tested your flask app, these instructions will be very similar, except now with the Heroku app url." }, { "code": null, "e": 9535, "s": 9286, "text": "Import requests and json in your Jupyter notebook, then create a variable to store the Heroku app url (you can find this by clicking “open app” in the top right corner of the app page on Heroku). Then create some sample data and convert it to JSON:" }, { "code": null, "e": 9761, "s": 9535, "text": "# heroku urlheroku_url = 'https://titanic-flask-model.herokuapp.com' # change to your app name# sample datadata = { 'Pclass': 3 , 'Age': 2 , 'SibSp': 1 , 'Fare': 50}data = json.dumps(data)" }, { "code": null, "e": 9873, "s": 9761, "text": "Check the response code using the following code. A response code of 200 means everything is running correctly." }, { "code": null, "e": 9939, "s": 9873, "text": "send_request = requests.post(heroku_url, data)print(send_request)" }, { "code": null, "e": 9964, "s": 9939, "text": "Output: <Response [200]>" }, { "code": null, "e": 10009, "s": 9964, "text": "And finally, look at the model’s prediction:" }, { "code": null, "e": 10036, "s": 10009, "text": "print(send_request.json())" }, { "code": null, "e": 10072, "s": 10036, "text": "Output: {‘results’: {‘results’: 1}}" }, { "code": null, "e": 10261, "s": 10072, "text": "Your output results will vary if you’re using different sample data. The result of 1 in this case means that the model predicts the passenger survived — and more importantly the API works!" }, { "code": null, "e": 10380, "s": 10261, "text": "Now people can access your API endpoint with the Heroku URL and use your model to make predictions in the real world 🌐" }, { "code": null, "e": 10463, "s": 10380, "text": "Here is the github repo containing all files and code required to deploy this API." } ]
MySQL query to divide column by 100?
Let us first create a table − mysql> create table DemoTable ( Number float ); Query OK, 0 rows affected (0.47 sec) Insert records in the table using insert command − mysql> insert into DemoTable values(1000); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values(1); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.30 sec) mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable values(390); Query OK, 1 row affected (0.09 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output− +--------+ | Number | +--------+ | 1000 | | 1 | | 10 | | 100 | | 390 | +--------+ 5 rows in set (0.00 sec) Following is the query to divide column by 100− mysql> update DemoTable set Number=Number/100; Query OK, 5 rows affected (0.09 sec) Rows matched: 5 Changed: 5 Warnings: 0 Let us display table records once again − mysql> select * from DemoTable; This will produce the following output − +--------+ | Number | +--------+ | 10 | | 0.01 | | 0.1 | | 1 | | 3.9 | +--------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1186, "s": 1092, "text": "mysql> create table DemoTable\n (\n Number float\n );\nQuery OK, 0 rows affected (0.47 sec)" }, { "code": null, "e": 1237, "s": 1186, "text": "Insert records in the table using insert command −" }, { "code": null, "e": 1625, "s": 1237, "text": "mysql> insert into DemoTable values(1000);\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable values(1);\nQuery OK, 1 row affected (0.27 sec)\nmysql> insert into DemoTable values(10);\nQuery OK, 1 row affected (0.30 sec)\nmysql> insert into DemoTable values(100);\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into DemoTable values(390);\nQuery OK, 1 row affected (0.09 sec)" }, { "code": null, "e": 1685, "s": 1625, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1716, "s": 1685, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1756, "s": 1716, "text": "This will produce the following output−" }, { "code": null, "e": 1880, "s": 1756, "text": "+--------+\n| Number |\n+--------+\n| 1000 |\n| 1 |\n| 10 |\n| 100 |\n| 390 |\n+--------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 1928, "s": 1880, "text": "Following is the query to divide column by 100−" }, { "code": null, "e": 2051, "s": 1928, "text": "mysql> update DemoTable set Number=Number/100;\nQuery OK, 5 rows affected (0.09 sec)\nRows matched: 5 Changed: 5 Warnings: 0" }, { "code": null, "e": 2093, "s": 2051, "text": "Let us display table records once again −" }, { "code": null, "e": 2125, "s": 2093, "text": "mysql> select * from DemoTable;" }, { "code": null, "e": 2166, "s": 2125, "text": "This will produce the following output −" }, { "code": null, "e": 2290, "s": 2166, "text": "+--------+\n| Number |\n+--------+\n| 10 |\n| 0.01 |\n| 0.1 |\n| 1 |\n| 3.9 |\n+--------+\n5 rows in set (0.00 sec)" } ]
Application to get live USD/INR rate Using Python - GeeksforGeeks
04 Dec, 2021 In this article, we are going to write a python scripts to get live information of USD/INR rate and bind with it GUI application. bs4: Beautiful Soup is a Python library for pulling data out of HTML and XML files. Installation: pip install bs4 requests: This module allows you to send HTTP/1.1 requests very easily. Installation: pip install requests Extract data from the given URL. Copy the URL, after selecting the desired location. Scrape the data with the help of requests and the Beautiful Soup module. Convert that data into HTML code. Find the required details and filter them. Step 1: Import all the modules required. Python3 # Import required modulesimport requestsfrom bs4 import BeautifulSoup Step 2: Create a URL get function Python3 # Function to extract html datadef getdata(url): r=requests.get(url) return r.text Step 3: Now pass the URL into the getdata() function and convert that data(currency details) into HTML code. The URL used here is https://finance.yahoo.com/quote/usdinr=X?ltr=1 Python3 # Extract and converthtmldata = getdata("https://finance.yahoo.com/quote/usdinr=X?ltr=1")soup = BeautifulSoup(htmldata, 'html.parser')result = (soup.find_all("div", class_="D(ib) Va(m) Maw(65%) Ov(h)") Output: Step 4: Filter the currency details and quality(increment/decrement) according to the given data. Python3 mydatastr = '' # Filter converted datafor table in soup.find_all("div", class_="D(ib) Va(m) Maw(65%) Ov(h)"): mydatastr += table.get_text() # Display outputprint(mydatastr) Output: '73.2610-0.2790 (-0.38%)As of 3:30PM BST. Market open.' Below is the complete program implemented using tkinter module. Python # Import required modulesfrom tkinter import *import requestsfrom bs4 import BeautifulSoup # user defined function# to extract currency detailsdef getdata(url): r = requests.get(url) return r.text # Function to compute and display currency detalisdef get_info(): try: htmldata = getdata("https://finance.yahoo.com/quote/usdinr=X?ltr=1") soup = BeautifulSoup(htmldata, 'html.parser') mydatastr = '' for table in soup.find_all("div", class_="D(ib) Va(m) Maw(65%) Ov(h)"): mydatastr += table.get_text() list_data = mydatastr.split() temp = list_data[0].split("-") rate.set(temp[0]) inc.set(temp[1]) per_rate.set(list_data[1]) time.set(list_data[3]) result.set("success") except: result.set("Opps! something wrong") # Driver Code # Create tkinter objectmaster = Tk() # Set background colormaster.configure(bg='light grey') # Variable Classes in tkinterresult = StringVar()rate = StringVar()per_rate = StringVar()time = StringVar()inc = StringVar() # Creating label for each informationLabel(master, text="Status :", bg="light grey").grid(row=2, sticky=W)Label(master, text="Current rate of INR :", bg="light grey").grid(row=3, sticky=W)Label(master, text="Increase/decrease by :", bg="light grey").grid(row=4, sticky=W)Label(master, text="Rate change :", bg="light grey").grid(row=5, sticky=W)Label(master, text="Rate of time :", bg="light grey").grid(row=6, sticky=W) # Creating label for class variableLabel(master, text="", textvariable=result, bg="light grey").grid(row=2, column=1, sticky=W)Label(master, text="", textvariable=rate, bg="light grey").grid(row=3, column=1, sticky=W)Label(master, text="", textvariable=inc, bg="light grey").grid( row=4, column=1, sticky=W)Label(master, text="", textvariable=per_rate, bg="light grey").grid(row=5, column=1, sticky=W)Label(master, text="", textvariable=time, bg="light grey").grid(row=6, column=1, sticky=W) # Create submit buttonb = Button(master, text="Show", command=get_info, bg="Blue").grid(row=0) mainloop() Output: abhigoya akshaysingh98088 simmytarika5 nnr223442 Python Tkinter-exercises Python-tkinter python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n04 Dec, 2021" }, { "code": null, "e": 24422, "s": 24292, "text": "In this article, we are going to write a python scripts to get live information of USD/INR rate and bind with it GUI application." }, { "code": null, "e": 24506, "s": 24422, "text": "bs4: Beautiful Soup is a Python library for pulling data out of HTML and XML files." }, { "code": null, "e": 24520, "s": 24506, "text": "Installation:" }, { "code": null, "e": 24536, "s": 24520, "text": "pip install bs4" }, { "code": null, "e": 24608, "s": 24536, "text": "requests: This module allows you to send HTTP/1.1 requests very easily." }, { "code": null, "e": 24622, "s": 24608, "text": "Installation:" }, { "code": null, "e": 24643, "s": 24622, "text": "pip install requests" }, { "code": null, "e": 24728, "s": 24643, "text": "Extract data from the given URL. Copy the URL, after selecting the desired location." }, { "code": null, "e": 24801, "s": 24728, "text": "Scrape the data with the help of requests and the Beautiful Soup module." }, { "code": null, "e": 24835, "s": 24801, "text": "Convert that data into HTML code." }, { "code": null, "e": 24878, "s": 24835, "text": "Find the required details and filter them." }, { "code": null, "e": 24919, "s": 24878, "text": "Step 1: Import all the modules required." }, { "code": null, "e": 24927, "s": 24919, "text": "Python3" }, { "code": "# Import required modulesimport requestsfrom bs4 import BeautifulSoup", "e": 24997, "s": 24927, "text": null }, { "code": null, "e": 25033, "s": 24997, "text": " Step 2: Create a URL get function " }, { "code": null, "e": 25041, "s": 25033, "text": "Python3" }, { "code": "# Function to extract html datadef getdata(url): r=requests.get(url) return r.text", "e": 25130, "s": 25041, "text": null }, { "code": null, "e": 25240, "s": 25130, "text": " Step 3: Now pass the URL into the getdata() function and convert that data(currency details) into HTML code." }, { "code": null, "e": 25309, "s": 25240, "text": "The URL used here is https://finance.yahoo.com/quote/usdinr=X?ltr=1 " }, { "code": null, "e": 25317, "s": 25309, "text": "Python3" }, { "code": "# Extract and converthtmldata = getdata(\"https://finance.yahoo.com/quote/usdinr=X?ltr=1\")soup = BeautifulSoup(htmldata, 'html.parser')result = (soup.find_all(\"div\", class_=\"D(ib) Va(m) Maw(65%) Ov(h)\")", "e": 25519, "s": 25317, "text": null }, { "code": null, "e": 25527, "s": 25519, "text": "Output:" }, { "code": null, "e": 25625, "s": 25527, "text": "Step 4: Filter the currency details and quality(increment/decrement) according to the given data." }, { "code": null, "e": 25633, "s": 25625, "text": "Python3" }, { "code": "mydatastr = '' # Filter converted datafor table in soup.find_all(\"div\", class_=\"D(ib) Va(m) Maw(65%) Ov(h)\"): mydatastr += table.get_text() # Display outputprint(mydatastr)", "e": 25809, "s": 25633, "text": null }, { "code": null, "e": 25817, "s": 25809, "text": "Output:" }, { "code": null, "e": 25874, "s": 25817, "text": "'73.2610-0.2790 (-0.38%)As of 3:30PM BST. Market open.'" }, { "code": null, "e": 25938, "s": 25874, "text": "Below is the complete program implemented using tkinter module." }, { "code": null, "e": 25945, "s": 25938, "text": "Python" }, { "code": "# Import required modulesfrom tkinter import *import requestsfrom bs4 import BeautifulSoup # user defined function# to extract currency detailsdef getdata(url): r = requests.get(url) return r.text # Function to compute and display currency detalisdef get_info(): try: htmldata = getdata(\"https://finance.yahoo.com/quote/usdinr=X?ltr=1\") soup = BeautifulSoup(htmldata, 'html.parser') mydatastr = '' for table in soup.find_all(\"div\", class_=\"D(ib) Va(m) Maw(65%) Ov(h)\"): mydatastr += table.get_text() list_data = mydatastr.split() temp = list_data[0].split(\"-\") rate.set(temp[0]) inc.set(temp[1]) per_rate.set(list_data[1]) time.set(list_data[3]) result.set(\"success\") except: result.set(\"Opps! something wrong\") # Driver Code # Create tkinter objectmaster = Tk() # Set background colormaster.configure(bg='light grey') # Variable Classes in tkinterresult = StringVar()rate = StringVar()per_rate = StringVar()time = StringVar()inc = StringVar() # Creating label for each informationLabel(master, text=\"Status :\", bg=\"light grey\").grid(row=2, sticky=W)Label(master, text=\"Current rate of INR :\", bg=\"light grey\").grid(row=3, sticky=W)Label(master, text=\"Increase/decrease by :\", bg=\"light grey\").grid(row=4, sticky=W)Label(master, text=\"Rate change :\", bg=\"light grey\").grid(row=5, sticky=W)Label(master, text=\"Rate of time :\", bg=\"light grey\").grid(row=6, sticky=W) # Creating label for class variableLabel(master, text=\"\", textvariable=result, bg=\"light grey\").grid(row=2, column=1, sticky=W)Label(master, text=\"\", textvariable=rate, bg=\"light grey\").grid(row=3, column=1, sticky=W)Label(master, text=\"\", textvariable=inc, bg=\"light grey\").grid( row=4, column=1, sticky=W)Label(master, text=\"\", textvariable=per_rate, bg=\"light grey\").grid(row=5, column=1, sticky=W)Label(master, text=\"\", textvariable=time, bg=\"light grey\").grid(row=6, column=1, sticky=W) # Create submit buttonb = Button(master, text=\"Show\", command=get_info, bg=\"Blue\").grid(row=0) mainloop()", "e": 28064, "s": 25945, "text": null }, { "code": null, "e": 28072, "s": 28064, "text": "Output:" }, { "code": null, "e": 28081, "s": 28072, "text": "abhigoya" }, { "code": null, "e": 28098, "s": 28081, "text": "akshaysingh98088" }, { "code": null, "e": 28111, "s": 28098, "text": "simmytarika5" }, { "code": null, "e": 28121, "s": 28111, "text": "nnr223442" }, { "code": null, "e": 28146, "s": 28121, "text": "Python Tkinter-exercises" }, { "code": null, "e": 28161, "s": 28146, "text": "Python-tkinter" }, { "code": null, "e": 28176, "s": 28161, "text": "python-utility" }, { "code": null, "e": 28183, "s": 28176, "text": "Python" }, { "code": null, "e": 28281, "s": 28183, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28313, "s": 28281, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28369, "s": 28313, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28411, "s": 28369, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28453, "s": 28411, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28475, "s": 28453, "text": "Defaultdict in Python" }, { "code": null, "e": 28514, "s": 28475, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28545, "s": 28514, "text": "Python | os.path.join() method" }, { "code": null, "e": 28600, "s": 28545, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28629, "s": 28600, "text": "Create a directory in Python" } ]
Metrics to Evaluate your Semantic Segmentation Model | by Ekin Tiu | Towards Data Science
Semantic segmentation. My absolute favorite task. I would make a deep learning model, have it all nice and trained... but wait. How do I know my model is performing well? In other words, what are the most common metrics for semantic segmentation? Here’s a clear cut guide to the essential metrics that you need to know to ensure your model performs well. I have also included Keras implementations below. If you want to learn more about Semantic Segmentation with Deep Learning, check out this Medium article by George Seif. towardsdatascience.com Contents: Pixel AccuracyIntersection-Over-Union (Jaccard Index)Dice Coefficient (F1 Score)Conclusion, Notes, Summary Pixel Accuracy Intersection-Over-Union (Jaccard Index) Dice Coefficient (F1 Score) Conclusion, Notes, Summary Pixel accuracy is perhaps the easiest to understand conceptually. It is the percent of pixels in your image that are classified correctly. While it is easy to understand, it is in no way the best metric. At first glance, it might be difficult to see the issue with this metric. To expose this metric for what it really is, here’s a scenario: Let’s say you ran the following image(Left)through your segmentation model. The image on the right is the ground truth, or annotation (what the model is supposed to segment). In this case, our model is trying to segment ships in a satellite image. You see that your segmentation accuracy is 95%. That’s awesome! Let’s see how your segmentation looks like! Not exactly what you were hoping for, huh. Is there something wrong with our calculation? Nope. It’s exactly right. It’s just that one class was 95% of the original image. So if the model classifies all pixels as that class, 95% of pixels are classified accurately while the other 5% are not. As a result, although your accuracy is a whopping 95%, your model is returning a completely useless prediction. This is meant to illustrate that high pixel accuracy doesn’t always imply superior segmentation ability. This issue is called class imbalance. When our classes are extremely imbalanced, it means that a class or some classes dominate the image, while some other classes make up only a small portion of the image. Unfortunately, class imbalance is prevalent in many real world data sets, so it can’t be ignored. Therefore, I present to you two alternative metrics that are better at dealing with this issue: The Intersection-Over-Union (IoU), also known as the Jaccard Index, is one of the most commonly used metrics in semantic segmentation... and for good reason. The IoU is a very straightforward metric that’s extremely effective. Before reading the following statement, take a look at the image to the left. Simply put, the IoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union between the predicted segmentation and the ground truth, as shown on the image to the left. This metric ranges from 0–1 (0–100%) with 0 signifying no overlap and 1 signifying perfectly overlapping segmentation. For binary (two classes) or multi-class segmentation, the mean IoU of the image is calculated by taking the IoU of each class and averaging them. (It’s implemented slightly differently in code). Now let’s try to understand why this metric is better than pixel accuracy by using the same scenario as section 1. For the sake of simplicity, let’s assume all the ships (colored boxes) are part of the same class. But wait, what exactly is overlap and union in our context? The image above shows a pretty clear picture, but I found it a bit difficult to understand in the context of predicted vs. ground truth because they aren’t necessarily overlapping like the image depicts above. Let’s take a look at the predicted segmentation and the ground truth side-by-side. Let’s calculate the ship IoU first. We assume the total area of the image is 100 (100 pixels). First, let’s think about the ships’ overlap. We can pretend that we move the predicted segmentation (left) directly above the ground truth (right), and see if there are any ship pixels that overlap. Since there are no pixels that are classified as ships by the model, there are 0 overlapping ship pixels. Union consists of all of the pixels classified as ships from both images, minus the overlap/intersection. In this case, there are 5 pixels (this is an arbitrary number choice) that are classified as ships total. Subtract the overlap/intersection which is 0 to get 5 as the area of union. After doing the calculations, we learn that the IoU is merely 47.5%! See the calculation below. Here is the detailed calculation: Ships: Area of Overlap = 0, Area of Union = (5+0)-0 =5 Area of Overlap/Area of Union = 0% Now for the black background, we do the same thing. Background: Area of Overlap = 95, Area of Union = (95+100)–95 = 100 Area of Overlap/Area of Union =95% Mean IoU = (Ships + Background)/2 = (0%+95%)/2 = 47.5% Wow. That’s a lot lower than the 95% pixel accuracy we calculated. It is obvious that 47.5 is a much better indication of the success of our segmentation, or more appropriately, the lack thereof. Here is a great Keras implementation that I used in my own projects: from keras import backend as Kdef iou_coef(y_true, y_pred, smooth=1): intersection = K.sum(K.abs(y_true * y_pred), axis=[1,2,3]) union = K.sum(y_true,[1,2,3])+K.sum(y_pred,[1,2,3])-intersection iou = K.mean((intersection + smooth) / (union + smooth), axis=0) return iou Both y_true and y_pred are m x r x c x n where m is the number of images, r is the number of rows, c is the number of columns, and n is the number of classes. Simply put, the Dice Coefficient is 2 * the Area of Overlap divided by the total number of pixels in both images. (See explanation of area of union in section 2). So for the same scenario used in 1 and 2, we would perform the following calculations: Total Number of Pixels for both images combined = 200 Ships: Area of Overlap = 0 (2 * Area of Overlap)/(total pixels combined) = 0/200 = 0 Background: Area of Overlap = 95 (2 * Area of Overlap)/(total pixels combined) = 95*2/200 = 0.95 Dice = (Ships + Background)/2 = (0%+95%)/2 = 47.5% In this case, we got the same value as the IoU, but this will not always be the case. The Dice coefficient is very similar to the IoU. They are positively correlated, meaning if one says model A is better than model B at segmenting an image, then the other will say the same. Like the IoU, they both range from 0 to 1, with 1 signifying the greatest similarity between predicted and truth. To better understand the differences between them, I recommend reading the following Stack Exchange answer: stats.stackexchange.com Here’s an implementation for the Dice Coefficient with the same input conditions specified in section 2: def dice_coef(y_true, y_pred, smooth=1): intersection = K.sum(y_true * y_pred, axis=[1,2,3]) union = K.sum(y_true, axis=[1,2,3]) + K.sum(y_pred, axis=[1,2,3]) dice = K.mean((2. * intersection + smooth)/(union + smooth), axis=0) return dice In conclusion, the most commonly used metrics for semantic segmentation are the IoU and the Dice Coefficient. I have included code implementations in Keras, and will explain them in greater depth in an upcoming article. As some of you may have noticed, I have purposely excluded discussions and explanations regarding true positives, true negatives, false positives and false negatives. Though important, I believe they obfuscate the clear conceptual understanding of these metrics that I tried to emphasize in this article. I hope this article imparts a greater insight about each metric so that you may have a deeper understanding during implementation or when reading literature.
[ { "code": null, "e": 576, "s": 171, "text": "Semantic segmentation. My absolute favorite task. I would make a deep learning model, have it all nice and trained... but wait. How do I know my model is performing well? In other words, what are the most common metrics for semantic segmentation? Here’s a clear cut guide to the essential metrics that you need to know to ensure your model performs well. I have also included Keras implementations below." }, { "code": null, "e": 696, "s": 576, "text": "If you want to learn more about Semantic Segmentation with Deep Learning, check out this Medium article by George Seif." }, { "code": null, "e": 719, "s": 696, "text": "towardsdatascience.com" }, { "code": null, "e": 729, "s": 719, "text": "Contents:" }, { "code": null, "e": 836, "s": 729, "text": "Pixel AccuracyIntersection-Over-Union (Jaccard Index)Dice Coefficient (F1 Score)Conclusion, Notes, Summary" }, { "code": null, "e": 851, "s": 836, "text": "Pixel Accuracy" }, { "code": null, "e": 891, "s": 851, "text": "Intersection-Over-Union (Jaccard Index)" }, { "code": null, "e": 919, "s": 891, "text": "Dice Coefficient (F1 Score)" }, { "code": null, "e": 946, "s": 919, "text": "Conclusion, Notes, Summary" }, { "code": null, "e": 1085, "s": 946, "text": "Pixel accuracy is perhaps the easiest to understand conceptually. It is the percent of pixels in your image that are classified correctly." }, { "code": null, "e": 1150, "s": 1085, "text": "While it is easy to understand, it is in no way the best metric." }, { "code": null, "e": 1536, "s": 1150, "text": "At first glance, it might be difficult to see the issue with this metric. To expose this metric for what it really is, here’s a scenario: Let’s say you ran the following image(Left)through your segmentation model. The image on the right is the ground truth, or annotation (what the model is supposed to segment). In this case, our model is trying to segment ships in a satellite image." }, { "code": null, "e": 1644, "s": 1536, "text": "You see that your segmentation accuracy is 95%. That’s awesome! Let’s see how your segmentation looks like!" }, { "code": null, "e": 2154, "s": 1644, "text": "Not exactly what you were hoping for, huh. Is there something wrong with our calculation? Nope. It’s exactly right. It’s just that one class was 95% of the original image. So if the model classifies all pixels as that class, 95% of pixels are classified accurately while the other 5% are not. As a result, although your accuracy is a whopping 95%, your model is returning a completely useless prediction. This is meant to illustrate that high pixel accuracy doesn’t always imply superior segmentation ability." }, { "code": null, "e": 2555, "s": 2154, "text": "This issue is called class imbalance. When our classes are extremely imbalanced, it means that a class or some classes dominate the image, while some other classes make up only a small portion of the image. Unfortunately, class imbalance is prevalent in many real world data sets, so it can’t be ignored. Therefore, I present to you two alternative metrics that are better at dealing with this issue:" }, { "code": null, "e": 2782, "s": 2555, "text": "The Intersection-Over-Union (IoU), also known as the Jaccard Index, is one of the most commonly used metrics in semantic segmentation... and for good reason. The IoU is a very straightforward metric that’s extremely effective." }, { "code": null, "e": 3199, "s": 2782, "text": "Before reading the following statement, take a look at the image to the left. Simply put, the IoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union between the predicted segmentation and the ground truth, as shown on the image to the left. This metric ranges from 0–1 (0–100%) with 0 signifying no overlap and 1 signifying perfectly overlapping segmentation." }, { "code": null, "e": 3394, "s": 3199, "text": "For binary (two classes) or multi-class segmentation, the mean IoU of the image is calculated by taking the IoU of each class and averaging them. (It’s implemented slightly differently in code)." }, { "code": null, "e": 3608, "s": 3394, "text": "Now let’s try to understand why this metric is better than pixel accuracy by using the same scenario as section 1. For the sake of simplicity, let’s assume all the ships (colored boxes) are part of the same class." }, { "code": null, "e": 3961, "s": 3608, "text": "But wait, what exactly is overlap and union in our context? The image above shows a pretty clear picture, but I found it a bit difficult to understand in the context of predicted vs. ground truth because they aren’t necessarily overlapping like the image depicts above. Let’s take a look at the predicted segmentation and the ground truth side-by-side." }, { "code": null, "e": 4361, "s": 3961, "text": "Let’s calculate the ship IoU first. We assume the total area of the image is 100 (100 pixels). First, let’s think about the ships’ overlap. We can pretend that we move the predicted segmentation (left) directly above the ground truth (right), and see if there are any ship pixels that overlap. Since there are no pixels that are classified as ships by the model, there are 0 overlapping ship pixels." }, { "code": null, "e": 4745, "s": 4361, "text": "Union consists of all of the pixels classified as ships from both images, minus the overlap/intersection. In this case, there are 5 pixels (this is an arbitrary number choice) that are classified as ships total. Subtract the overlap/intersection which is 0 to get 5 as the area of union. After doing the calculations, we learn that the IoU is merely 47.5%! See the calculation below." }, { "code": null, "e": 4779, "s": 4745, "text": "Here is the detailed calculation:" }, { "code": null, "e": 4834, "s": 4779, "text": "Ships: Area of Overlap = 0, Area of Union = (5+0)-0 =5" }, { "code": null, "e": 4869, "s": 4834, "text": "Area of Overlap/Area of Union = 0%" }, { "code": null, "e": 4921, "s": 4869, "text": "Now for the black background, we do the same thing." }, { "code": null, "e": 4989, "s": 4921, "text": "Background: Area of Overlap = 95, Area of Union = (95+100)–95 = 100" }, { "code": null, "e": 5024, "s": 4989, "text": "Area of Overlap/Area of Union =95%" }, { "code": null, "e": 5079, "s": 5024, "text": "Mean IoU = (Ships + Background)/2 = (0%+95%)/2 = 47.5%" }, { "code": null, "e": 5275, "s": 5079, "text": "Wow. That’s a lot lower than the 95% pixel accuracy we calculated. It is obvious that 47.5 is a much better indication of the success of our segmentation, or more appropriately, the lack thereof." }, { "code": null, "e": 5344, "s": 5275, "text": "Here is a great Keras implementation that I used in my own projects:" }, { "code": null, "e": 5618, "s": 5344, "text": "from keras import backend as Kdef iou_coef(y_true, y_pred, smooth=1): intersection = K.sum(K.abs(y_true * y_pred), axis=[1,2,3]) union = K.sum(y_true,[1,2,3])+K.sum(y_pred,[1,2,3])-intersection iou = K.mean((intersection + smooth) / (union + smooth), axis=0) return iou" }, { "code": null, "e": 5777, "s": 5618, "text": "Both y_true and y_pred are m x r x c x n where m is the number of images, r is the number of rows, c is the number of columns, and n is the number of classes." }, { "code": null, "e": 5940, "s": 5777, "text": "Simply put, the Dice Coefficient is 2 * the Area of Overlap divided by the total number of pixels in both images. (See explanation of area of union in section 2)." }, { "code": null, "e": 6027, "s": 5940, "text": "So for the same scenario used in 1 and 2, we would perform the following calculations:" }, { "code": null, "e": 6081, "s": 6027, "text": "Total Number of Pixels for both images combined = 200" }, { "code": null, "e": 6108, "s": 6081, "text": "Ships: Area of Overlap = 0" }, { "code": null, "e": 6166, "s": 6108, "text": "(2 * Area of Overlap)/(total pixels combined) = 0/200 = 0" }, { "code": null, "e": 6199, "s": 6166, "text": "Background: Area of Overlap = 95" }, { "code": null, "e": 6263, "s": 6199, "text": "(2 * Area of Overlap)/(total pixels combined) = 95*2/200 = 0.95" }, { "code": null, "e": 6314, "s": 6263, "text": "Dice = (Ships + Background)/2 = (0%+95%)/2 = 47.5%" }, { "code": null, "e": 6400, "s": 6314, "text": "In this case, we got the same value as the IoU, but this will not always be the case." }, { "code": null, "e": 6704, "s": 6400, "text": "The Dice coefficient is very similar to the IoU. They are positively correlated, meaning if one says model A is better than model B at segmenting an image, then the other will say the same. Like the IoU, they both range from 0 to 1, with 1 signifying the greatest similarity between predicted and truth." }, { "code": null, "e": 6812, "s": 6704, "text": "To better understand the differences between them, I recommend reading the following Stack Exchange answer:" }, { "code": null, "e": 6836, "s": 6812, "text": "stats.stackexchange.com" }, { "code": null, "e": 6941, "s": 6836, "text": "Here’s an implementation for the Dice Coefficient with the same input conditions specified in section 2:" }, { "code": null, "e": 7185, "s": 6941, "text": "def dice_coef(y_true, y_pred, smooth=1): intersection = K.sum(y_true * y_pred, axis=[1,2,3]) union = K.sum(y_true, axis=[1,2,3]) + K.sum(y_pred, axis=[1,2,3]) dice = K.mean((2. * intersection + smooth)/(union + smooth), axis=0) return dice" }, { "code": null, "e": 7405, "s": 7185, "text": "In conclusion, the most commonly used metrics for semantic segmentation are the IoU and the Dice Coefficient. I have included code implementations in Keras, and will explain them in greater depth in an upcoming article." }, { "code": null, "e": 7710, "s": 7405, "text": "As some of you may have noticed, I have purposely excluded discussions and explanations regarding true positives, true negatives, false positives and false negatives. Though important, I believe they obfuscate the clear conceptual understanding of these metrics that I tried to emphasize in this article." } ]
6 Python Container Data Types You Should Know | by Christopher Tao | Towards Data Science
I’m sure that you must know the basic collection data types in Python, such as list, tuple and dictionary. There are too many resources online regarding these data structures already. However, have you noticed that there are 6 “high-level” data structure tools in the collection module that is built-in Python? Named Tuple Ordered Dict (Ordered Dictionary) Chain Map Counter Deque (Double-Ended Queue) Don’t be scared by their names. I promise that these are something you are already familiar with, but provide you with some extremely convenient features out-of-the-box. Let’s walk through these container data types to see what they are and what they can do. For convenience purposes, all the demonstration code are supposing all the collection types are imported. from collections import * A tuple is an important sequence data type in Python. As long as you have ever used Python, you should know it already. However, what is the “Named Tuple”? Suppose we are developing an application that needs to use coordinates (latitude and longitude), which is the two decimal numbers to represent a place on the earth that we usually see on the Google Map. It is naturally can be represented in a tuple as follows. c1 = (-37.814288, 144.963122) However, if we’re dealing with coordinates all over the world, sometimes it might not be easy to identify which number is latitude or longitude. This could result in extra difficulty of the code readability. Rather than the values only, named tuples assign meaningful names to each position in a tuple and allow for more readable, self-documenting code. They can be used wherever regular tuples are used, and they add the ability to access fields by name instead of position index. Before using the named tuple, we can define it as follows. Coordinate = namedtuple('Coordinate', ['latitude', 'longitude']) Then, we can use the defined named tuple to define coordinate now. c1 = Coordinate(-37.814288, 144.963122) It is not only for the readability but also the convenience of usage, such as accessing the values by names. print(f'The latitude is {c1.latitude} and the longitude is {c1.longitude}') If we want to get the field names, we can simply call its _fields() function. c1._fields() You may start to think this somehow overlaps with the class and dictionary. However, this is much simpler and neater than defining a class if you don’t need any class methods. Also, if necessary, you can easily convert a named tuple to a dictionary anytime. c1._asdict() Hold on, what is the OrderedDict? It is indeed a dictionary, but a little bit different. Please refer to the next section. An ordered dictionary is a sub-class of the dictionary that inherits everything from it. The only difference is that the items in an ordered dictionary are “order sensitive”. We have got an ordered dictionary from the previous section already. Let’s keep using this as an example. od = c1._asdict() Because it inherits everything from a normal dictionary, we can expect it has all the features that a normal dictionary should have, such as accessing value by key. print(f"The latitude is {od['latitude']} and the longitude is {od['longitude']}") However, because it is order-sensitive, it has some particular features that a normal dictionary wouldn’t have. For example, we can change the order of the items by calling move_to_end() function. od.move_to_end('latitude') So, the latitude was moved to the end of the ordered dictionary. Also, we can pop the last item out of the ordered dictionary. lat = od.popitem() An ordered dictionary could be very useful in some circumstances. For example, we can use it to memorise the order of the keys that were last inserted. Next, let’s have a look at the Chain Map. A Chain Map is very useful when we want to combine multiple dictionaries together as a whole, but without physically combining them that may consume more resource and have to resolve key conflicts when there are duplicated keys. Suppose we are developing an application that relies on some configurations. We define the system default configurations in the app, while users are allowed to pass some specific settings to overwrite the default ones. Just make up the example as follows. usr_config = {'name': 'Chris', 'language': 'Python'}sys_config = {'name': 'admin', 'language': 'Shell Script', 'editor': 'vm'} What would you do? Write a for-loop to update the sys_config based on the usr_config? What if there are hundreds of items, or there are multiple layers rather than only two of them? It is quite common we have multi-layer configurations such as user-level > application-level > system-level and so on. Use Chain Map can solve this problem on the fly. cm = ChainMap(usr_config, sys_config) From the output, it looks like the Chain map just simply put the dictionaries together. In fact, there is some magic behind it. If we try to convert it into a list, we can see that there are only 3 keys. Indeed, there are 3 unique keys out of the 5. What if we try to access the value of the “name” key? Let’s also try the “editor” key. OK. The magic is that the usr_config always overwrites the settings in the sys_config. However, if the key we are accessing is not defined in usr_config, the one in the sys_config will be used. That is exactly what we want. What if we want to update the key “editor” in the Chain Map? It can be seen that the usr_config is actually updated. This makes sense because it will overwrite the same item in the sys_config. Of course, if we delete the “editor” key, it will be deleted from the usr_config and the default one in the sys_config will be used again. del cm['editor']cm['editor'] See, using a container type in Python correctly can save us a huge amount of time! The next one is “Counter”. It doesn’t sound like a container type, but it is kind of similar to a dictionary in terms of its presentation. However, it is more like a tool for “counting problems”. Suppose we have a list with many items in it. Some items are identical and we want to count the number of repeated times for each of them. The list is as follows. my_list = ['a', 'b', 'c', 'a', 'c', 'a', 'a', 'a', 'c', 'b', 'c', 'c', 'b', 'b', 'c'] Then, we can use Counter to perform this task very easily. counter = Counter()for letter in my_list: counter[letter] += 1 It tells us there are 5 “a”, 4 “b” and 6 “c” in the list. Counter also provides a number of convenient features that are related. For example, we can get the “n” most common ones. counter.most_common(2) We can still get all the elements back into a list. list(counter.elements()) Also, we can define a Counter on the fly. another_counter = Counter(a=1, b=4, c=3) When we have two counters, we can even perform operations between them. counter - another_counter Finally, if we want to know the total number, we can always sum them up. sum(counter.values()) Don’t look down at such a small tool in Python. In some circumstances, it can simplify problems to a very large extent. If you are interested in the recipes of this tool, please keep an eye on my updates. If you have a computer science background, you must know many common data structures such as queue and stack. Their difference is FIFO (first in, first out) and LIFO (last in, first out). There is another data structure manipulation called deque, which is an abbreviation of the double-ended queue. It is implemented in Python and ready to be used out-of-the-box. Let’s define a deque first. dq = deque('bcd') Because it is a “double-ended” queue, we can append either from the left or the right side. dq.append('e')dq.appendleft('a') We can also append multiple elements at one time use the extend() or extendleft() function. Please be noticed that the order when we append to the left, you will understand why “210” became “012”. Just thinking we are appending them one by one on the left side. dq.extend('fgh')dq.extendleft('210') There are also some very useful manipulations that are particularly in a deque structure, such as rotation. It rotates the element from the right end to the left end or the other way around. Please be noticed that the argument of the rotate() function can be any integers. dq.rotate()dq.rotate(-1) Of course, we can let the element “out” of either end of the deque. dq.pop()dq.popleft() Finally, the default dictionary is a bit difficult to understand from its name. However, it doesn’t prevent it becomes a useful tool. Of course, after you really understand it :) A default dictionary is a sub-class of a dictionary. The default does not mean default values but “default factory”. Default factory indicates the default data type that the dictionary will be constructed. The most important one, the default dictionary is used for collecting objects (of the default data type) based on some common keys. Don’t be confused. Let me show you an example. Suppose we have a list of names as follows. my_list = ['Alice', 'Bob', 'Chris', 'Bill', 'Ashley', 'Anna'] What we want to do is to collect the names with the same starting letters together in a list. For example, ['Alice', 'Ashley', 'Anna'] should be one of the lists because they are all start with “A”. In this case, we want the value to be “list”. So, the default factory will be “list”. dd = defaultdict(list)for name in my_list: dd[name[0]].append(name)dd.items() We have used the default dictionary to separate the names very easily! Then, of course, we can use it as a normal dictionary to get the values. print(f'''Names start with "A":{dd["A"]}Names start with "B":{dd["B"]}Names start with "C":{dd["C"]}''') The default dictionary is very flexible because the default factory can be any data types. For example, we can define the default factory as integer and use it for counting the number of names for each starting letter. dd = defaultdict(int)for name in my_list: dd[name[0]] += 1dd.items() We have re-invented the wheel that the Counter does. Take it easy, this is just an example :) In this article, I have introduced 6 container types in the collection module of Python. The named tuple helps us to write more readable code, the ordered dictionary helps us to define an item order-sensitive dictionary, the chain map helps us to define a multi-layered dictionary, the counter helps us to count everything easily, the deque defines a double-ended queue and finally, the default dictionary helps us to collect objects based on some common keys. medium.com If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)
[ { "code": null, "e": 483, "s": 172, "text": "I’m sure that you must know the basic collection data types in Python, such as list, tuple and dictionary. There are too many resources online regarding these data structures already. However, have you noticed that there are 6 “high-level” data structure tools in the collection module that is built-in Python?" }, { "code": null, "e": 495, "s": 483, "text": "Named Tuple" }, { "code": null, "e": 529, "s": 495, "text": "Ordered Dict (Ordered Dictionary)" }, { "code": null, "e": 539, "s": 529, "text": "Chain Map" }, { "code": null, "e": 547, "s": 539, "text": "Counter" }, { "code": null, "e": 574, "s": 547, "text": "Deque (Double-Ended Queue)" }, { "code": null, "e": 744, "s": 574, "text": "Don’t be scared by their names. I promise that these are something you are already familiar with, but provide you with some extremely convenient features out-of-the-box." }, { "code": null, "e": 939, "s": 744, "text": "Let’s walk through these container data types to see what they are and what they can do. For convenience purposes, all the demonstration code are supposing all the collection types are imported." }, { "code": null, "e": 965, "s": 939, "text": "from collections import *" }, { "code": null, "e": 1121, "s": 965, "text": "A tuple is an important sequence data type in Python. As long as you have ever used Python, you should know it already. However, what is the “Named Tuple”?" }, { "code": null, "e": 1382, "s": 1121, "text": "Suppose we are developing an application that needs to use coordinates (latitude and longitude), which is the two decimal numbers to represent a place on the earth that we usually see on the Google Map. It is naturally can be represented in a tuple as follows." }, { "code": null, "e": 1412, "s": 1382, "text": "c1 = (-37.814288, 144.963122)" }, { "code": null, "e": 1620, "s": 1412, "text": "However, if we’re dealing with coordinates all over the world, sometimes it might not be easy to identify which number is latitude or longitude. This could result in extra difficulty of the code readability." }, { "code": null, "e": 1894, "s": 1620, "text": "Rather than the values only, named tuples assign meaningful names to each position in a tuple and allow for more readable, self-documenting code. They can be used wherever regular tuples are used, and they add the ability to access fields by name instead of position index." }, { "code": null, "e": 1953, "s": 1894, "text": "Before using the named tuple, we can define it as follows." }, { "code": null, "e": 2018, "s": 1953, "text": "Coordinate = namedtuple('Coordinate', ['latitude', 'longitude'])" }, { "code": null, "e": 2085, "s": 2018, "text": "Then, we can use the defined named tuple to define coordinate now." }, { "code": null, "e": 2125, "s": 2085, "text": "c1 = Coordinate(-37.814288, 144.963122)" }, { "code": null, "e": 2234, "s": 2125, "text": "It is not only for the readability but also the convenience of usage, such as accessing the values by names." }, { "code": null, "e": 2310, "s": 2234, "text": "print(f'The latitude is {c1.latitude} and the longitude is {c1.longitude}')" }, { "code": null, "e": 2388, "s": 2310, "text": "If we want to get the field names, we can simply call its _fields() function." }, { "code": null, "e": 2401, "s": 2388, "text": "c1._fields()" }, { "code": null, "e": 2659, "s": 2401, "text": "You may start to think this somehow overlaps with the class and dictionary. However, this is much simpler and neater than defining a class if you don’t need any class methods. Also, if necessary, you can easily convert a named tuple to a dictionary anytime." }, { "code": null, "e": 2672, "s": 2659, "text": "c1._asdict()" }, { "code": null, "e": 2795, "s": 2672, "text": "Hold on, what is the OrderedDict? It is indeed a dictionary, but a little bit different. Please refer to the next section." }, { "code": null, "e": 2970, "s": 2795, "text": "An ordered dictionary is a sub-class of the dictionary that inherits everything from it. The only difference is that the items in an ordered dictionary are “order sensitive”." }, { "code": null, "e": 3076, "s": 2970, "text": "We have got an ordered dictionary from the previous section already. Let’s keep using this as an example." }, { "code": null, "e": 3094, "s": 3076, "text": "od = c1._asdict()" }, { "code": null, "e": 3259, "s": 3094, "text": "Because it inherits everything from a normal dictionary, we can expect it has all the features that a normal dictionary should have, such as accessing value by key." }, { "code": null, "e": 3341, "s": 3259, "text": "print(f\"The latitude is {od['latitude']} and the longitude is {od['longitude']}\")" }, { "code": null, "e": 3538, "s": 3341, "text": "However, because it is order-sensitive, it has some particular features that a normal dictionary wouldn’t have. For example, we can change the order of the items by calling move_to_end() function." }, { "code": null, "e": 3565, "s": 3538, "text": "od.move_to_end('latitude')" }, { "code": null, "e": 3630, "s": 3565, "text": "So, the latitude was moved to the end of the ordered dictionary." }, { "code": null, "e": 3692, "s": 3630, "text": "Also, we can pop the last item out of the ordered dictionary." }, { "code": null, "e": 3711, "s": 3692, "text": "lat = od.popitem()" }, { "code": null, "e": 3863, "s": 3711, "text": "An ordered dictionary could be very useful in some circumstances. For example, we can use it to memorise the order of the keys that were last inserted." }, { "code": null, "e": 4134, "s": 3863, "text": "Next, let’s have a look at the Chain Map. A Chain Map is very useful when we want to combine multiple dictionaries together as a whole, but without physically combining them that may consume more resource and have to resolve key conflicts when there are duplicated keys." }, { "code": null, "e": 4390, "s": 4134, "text": "Suppose we are developing an application that relies on some configurations. We define the system default configurations in the app, while users are allowed to pass some specific settings to overwrite the default ones. Just make up the example as follows." }, { "code": null, "e": 4517, "s": 4390, "text": "usr_config = {'name': 'Chris', 'language': 'Python'}sys_config = {'name': 'admin', 'language': 'Shell Script', 'editor': 'vm'}" }, { "code": null, "e": 4818, "s": 4517, "text": "What would you do? Write a for-loop to update the sys_config based on the usr_config? What if there are hundreds of items, or there are multiple layers rather than only two of them? It is quite common we have multi-layer configurations such as user-level > application-level > system-level and so on." }, { "code": null, "e": 4867, "s": 4818, "text": "Use Chain Map can solve this problem on the fly." }, { "code": null, "e": 4905, "s": 4867, "text": "cm = ChainMap(usr_config, sys_config)" }, { "code": null, "e": 5155, "s": 4905, "text": "From the output, it looks like the Chain map just simply put the dictionaries together. In fact, there is some magic behind it. If we try to convert it into a list, we can see that there are only 3 keys. Indeed, there are 3 unique keys out of the 5." }, { "code": null, "e": 5209, "s": 5155, "text": "What if we try to access the value of the “name” key?" }, { "code": null, "e": 5242, "s": 5209, "text": "Let’s also try the “editor” key." }, { "code": null, "e": 5466, "s": 5242, "text": "OK. The magic is that the usr_config always overwrites the settings in the sys_config. However, if the key we are accessing is not defined in usr_config, the one in the sys_config will be used. That is exactly what we want." }, { "code": null, "e": 5527, "s": 5466, "text": "What if we want to update the key “editor” in the Chain Map?" }, { "code": null, "e": 5798, "s": 5527, "text": "It can be seen that the usr_config is actually updated. This makes sense because it will overwrite the same item in the sys_config. Of course, if we delete the “editor” key, it will be deleted from the usr_config and the default one in the sys_config will be used again." }, { "code": null, "e": 5827, "s": 5798, "text": "del cm['editor']cm['editor']" }, { "code": null, "e": 5910, "s": 5827, "text": "See, using a container type in Python correctly can save us a huge amount of time!" }, { "code": null, "e": 6106, "s": 5910, "text": "The next one is “Counter”. It doesn’t sound like a container type, but it is kind of similar to a dictionary in terms of its presentation. However, it is more like a tool for “counting problems”." }, { "code": null, "e": 6269, "s": 6106, "text": "Suppose we have a list with many items in it. Some items are identical and we want to count the number of repeated times for each of them. The list is as follows." }, { "code": null, "e": 6355, "s": 6269, "text": "my_list = ['a', 'b', 'c', 'a', 'c', 'a', 'a', 'a', 'c', 'b', 'c', 'c', 'b', 'b', 'c']" }, { "code": null, "e": 6414, "s": 6355, "text": "Then, we can use Counter to perform this task very easily." }, { "code": null, "e": 6480, "s": 6414, "text": "counter = Counter()for letter in my_list: counter[letter] += 1" }, { "code": null, "e": 6538, "s": 6480, "text": "It tells us there are 5 “a”, 4 “b” and 6 “c” in the list." }, { "code": null, "e": 6660, "s": 6538, "text": "Counter also provides a number of convenient features that are related. For example, we can get the “n” most common ones." }, { "code": null, "e": 6683, "s": 6660, "text": "counter.most_common(2)" }, { "code": null, "e": 6735, "s": 6683, "text": "We can still get all the elements back into a list." }, { "code": null, "e": 6760, "s": 6735, "text": "list(counter.elements())" }, { "code": null, "e": 6802, "s": 6760, "text": "Also, we can define a Counter on the fly." }, { "code": null, "e": 6843, "s": 6802, "text": "another_counter = Counter(a=1, b=4, c=3)" }, { "code": null, "e": 6915, "s": 6843, "text": "When we have two counters, we can even perform operations between them." }, { "code": null, "e": 6941, "s": 6915, "text": "counter - another_counter" }, { "code": null, "e": 7014, "s": 6941, "text": "Finally, if we want to know the total number, we can always sum them up." }, { "code": null, "e": 7036, "s": 7014, "text": "sum(counter.values())" }, { "code": null, "e": 7241, "s": 7036, "text": "Don’t look down at such a small tool in Python. In some circumstances, it can simplify problems to a very large extent. If you are interested in the recipes of this tool, please keep an eye on my updates." }, { "code": null, "e": 7429, "s": 7241, "text": "If you have a computer science background, you must know many common data structures such as queue and stack. Their difference is FIFO (first in, first out) and LIFO (last in, first out)." }, { "code": null, "e": 7605, "s": 7429, "text": "There is another data structure manipulation called deque, which is an abbreviation of the double-ended queue. It is implemented in Python and ready to be used out-of-the-box." }, { "code": null, "e": 7633, "s": 7605, "text": "Let’s define a deque first." }, { "code": null, "e": 7651, "s": 7633, "text": "dq = deque('bcd')" }, { "code": null, "e": 7743, "s": 7651, "text": "Because it is a “double-ended” queue, we can append either from the left or the right side." }, { "code": null, "e": 7776, "s": 7743, "text": "dq.append('e')dq.appendleft('a')" }, { "code": null, "e": 8038, "s": 7776, "text": "We can also append multiple elements at one time use the extend() or extendleft() function. Please be noticed that the order when we append to the left, you will understand why “210” became “012”. Just thinking we are appending them one by one on the left side." }, { "code": null, "e": 8075, "s": 8038, "text": "dq.extend('fgh')dq.extendleft('210')" }, { "code": null, "e": 8348, "s": 8075, "text": "There are also some very useful manipulations that are particularly in a deque structure, such as rotation. It rotates the element from the right end to the left end or the other way around. Please be noticed that the argument of the rotate() function can be any integers." }, { "code": null, "e": 8373, "s": 8348, "text": "dq.rotate()dq.rotate(-1)" }, { "code": null, "e": 8441, "s": 8373, "text": "Of course, we can let the element “out” of either end of the deque." }, { "code": null, "e": 8462, "s": 8441, "text": "dq.pop()dq.popleft()" }, { "code": null, "e": 8641, "s": 8462, "text": "Finally, the default dictionary is a bit difficult to understand from its name. However, it doesn’t prevent it becomes a useful tool. Of course, after you really understand it :)" }, { "code": null, "e": 8979, "s": 8641, "text": "A default dictionary is a sub-class of a dictionary. The default does not mean default values but “default factory”. Default factory indicates the default data type that the dictionary will be constructed. The most important one, the default dictionary is used for collecting objects (of the default data type) based on some common keys." }, { "code": null, "e": 9070, "s": 8979, "text": "Don’t be confused. Let me show you an example. Suppose we have a list of names as follows." }, { "code": null, "e": 9132, "s": 9070, "text": "my_list = ['Alice', 'Bob', 'Chris', 'Bill', 'Ashley', 'Anna']" }, { "code": null, "e": 9331, "s": 9132, "text": "What we want to do is to collect the names with the same starting letters together in a list. For example, ['Alice', 'Ashley', 'Anna'] should be one of the lists because they are all start with “A”." }, { "code": null, "e": 9417, "s": 9331, "text": "In this case, we want the value to be “list”. So, the default factory will be “list”." }, { "code": null, "e": 9498, "s": 9417, "text": "dd = defaultdict(list)for name in my_list: dd[name[0]].append(name)dd.items()" }, { "code": null, "e": 9642, "s": 9498, "text": "We have used the default dictionary to separate the names very easily! Then, of course, we can use it as a normal dictionary to get the values." }, { "code": null, "e": 9747, "s": 9642, "text": "print(f'''Names start with \"A\":{dd[\"A\"]}Names start with \"B\":{dd[\"B\"]}Names start with \"C\":{dd[\"C\"]}''')" }, { "code": null, "e": 9966, "s": 9747, "text": "The default dictionary is very flexible because the default factory can be any data types. For example, we can define the default factory as integer and use it for counting the number of names for each starting letter." }, { "code": null, "e": 10038, "s": 9966, "text": "dd = defaultdict(int)for name in my_list: dd[name[0]] += 1dd.items()" }, { "code": null, "e": 10132, "s": 10038, "text": "We have re-invented the wheel that the Counter does. Take it easy, this is just an example :)" }, { "code": null, "e": 10593, "s": 10132, "text": "In this article, I have introduced 6 container types in the collection module of Python. The named tuple helps us to write more readable code, the ordered dictionary helps us to define an item order-sensitive dictionary, the chain map helps us to define a multi-layered dictionary, the counter helps us to count everything easily, the deque defines a double-ended queue and finally, the default dictionary helps us to collect objects based on some common keys." }, { "code": null, "e": 10604, "s": 10593, "text": "medium.com" } ]
priority_queue emplace() in C++ STL - GeeksforGeeks
06 Jul, 2021 Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is the greatest of all elements in the queue. This function is used to insert a new element into the priority queue container, the new element is added to the top of the priority queue. Syntax : priorityqueuename.emplace(value) Parameters : The element to be inserted into the priority queue is passed as the parameter. Result : The parameter is added to the priority queue at the top position. Examples: Input : mypqueue{5, 4}; mypqueue.emplace(6); Output : mypqueue = 6, 5, 4 Input : mypqueue{}; mypqueue.emplace(4); Output : mypqueue = 4 Note: In priority_queue container, the elements are printed in reverse order because the top is printed first then moving on to other elements. Errors and Exceptions 1. It has a strong exception guarantee, therefore, no changes are made if an exception is thrown. 2. Parameter should be of same type as that of the container, otherwise an error is thrown. C++ // INTEGER PRIORITY QUEUE// CPP program to illustrate// Implementation of emplace() function#include <iostream>#include <queue>using namespace std; int main(){ priority_queue<int> mypqueue; mypqueue.emplace(1); mypqueue.emplace(2); mypqueue.emplace(3); mypqueue.emplace(4); mypqueue.emplace(5); mypqueue.emplace(6); // queue becomes 1, 2, 3, 4, 5, 6 // printing the priority queue cout << "mypqueue = "; while (!mypqueue.empty()) { cout << mypqueue.top() << " "; mypqueue.pop(); } return 0;} mypqueue = 6 5 4 3 2 1 C++ // CHARACTER PRIORITY QUEUE// CPP program to illustrate// Implementation of emplace() function#include <iostream>#include <queue>using namespace std; int main(){ priority_queue<char> mypqueue; mypqueue.emplace('A'); mypqueue.emplace('b'); mypqueue.emplace('C'); mypqueue.emplace('d'); mypqueue.emplace('E'); mypqueue.emplace('f'); // queue becomes A, b, C, d, E, f // printing the priority queue cout << "mypqueue = "; while (!mypqueue.empty()) { cout << mypqueue.top() << " "; mypqueue.pop(); } return 0;} mypqueue = f d b E C A C++ // STRING PRIORITY QUEUE// CPP program to illustrate// Implementation of emplace() function#include <iostream>#include <queue>#include <string>using namespace std; int main(){ priority_queue<string> mypqueue; mypqueue.emplace("portal"); mypqueue.emplace("computer science"); mypqueue.emplace("is a"); mypqueue.emplace("GEEKSFORGEEKS"); // queue becomes portal, computer science, // is a, GEEKSFORGEEKS // printing the priority queue cout << "mypqueue = "; while (!mypqueue.empty()) { cout << mypqueue.top() << " "; mypqueue.pop(); } return 0;} mypqueue = portal is a computer science GEEKSFORGEEKS Application : Given a number of integers, add them to the priority queue using emplace() and find the size of the priority queue. Input : 5, 13, 0, 9, 4 Output: 5 Algorithm 1. Insert the given elements to the priority queue container one by one using emplace(). 2. Keep popping the elements of priority queue until it becomes empty, and increment the counter variable. 3. Print the counter variable. C++ // CPP program to illustrate// Application of emplace() function#include <iostream>#include <queue>using namespace std; int main(){ int c = 0; // Empty Priority Queue priority_queue<int> pqueue; // inserting elements into priority_queue pqueue.emplace(5); pqueue.emplace(13); pqueue.emplace(0); pqueue.emplace(9); pqueue.emplace(4); // Priority queue becomes 13, 9, 5, 4, 0 // Counting number of elements in queue while (!pqueue.empty()) { pqueue.pop(); c++; } cout << c;} 5 Time Complexity : O(1) emplace() vs push() When we use push(), we create an object and then insert it into the priority_queue. With emplace(), the object is constructed in-place and saves an unnecessary copy. Please see emplace vs insert in C++ STL for details. C++ // C++ code to demonstrate difference between// emplace and insert#include<bits/stdc++.h>using namespace std; int main(){ // declaring priority queue priority_queue<pair<char, int>> pqueue; // using emplace() to insert pair in-place pqueue.emplace('a', 24); // Below line would not compile // pqueue.push('b', 25); // using push() to insert pair pqueue.push(make_pair('b', 25)); // printing the priority_queue while (!pqueue.empty()) { pair<char, int> p = pqueue.top(); cout << p.first << " " << p.second << endl; pqueue.pop(); } return 0;} b 25 a 24 clintra cpp-priority-queue STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Bitwise Operators in C/C++ Virtual Function in C++ Templates in C++ with Examples Constructors in C++ Operator Overloading in C++ Socket Programming in C/C++ vector erase() and clear() in C++
[ { "code": null, "e": 25403, "s": 25375, "text": "\n06 Jul, 2021" }, { "code": null, "e": 25562, "s": 25403, "text": "Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is the greatest of all elements in the queue." }, { "code": null, "e": 25703, "s": 25562, "text": "This function is used to insert a new element into the priority queue container, the new element is added to the top of the priority queue. " }, { "code": null, "e": 25714, "s": 25703, "text": "Syntax : " }, { "code": null, "e": 25914, "s": 25714, "text": "priorityqueuename.emplace(value)\nParameters :\nThe element to be inserted into the priority\nqueue is passed as the parameter.\nResult :\nThe parameter is added to the\npriority queue at the top position." }, { "code": null, "e": 25925, "s": 25914, "text": "Examples: " }, { "code": null, "e": 26082, "s": 25925, "text": "Input : mypqueue{5, 4};\n mypqueue.emplace(6);\nOutput : mypqueue = 6, 5, 4\n\nInput : mypqueue{};\n mypqueue.emplace(4);\nOutput : mypqueue = 4" }, { "code": null, "e": 26226, "s": 26082, "text": "Note: In priority_queue container, the elements are printed in reverse order because the top is printed first then moving on to other elements." }, { "code": null, "e": 26438, "s": 26226, "text": "Errors and Exceptions 1. It has a strong exception guarantee, therefore, no changes are made if an exception is thrown. 2. Parameter should be of same type as that of the container, otherwise an error is thrown." }, { "code": null, "e": 26442, "s": 26438, "text": "C++" }, { "code": "// INTEGER PRIORITY QUEUE// CPP program to illustrate// Implementation of emplace() function#include <iostream>#include <queue>using namespace std; int main(){ priority_queue<int> mypqueue; mypqueue.emplace(1); mypqueue.emplace(2); mypqueue.emplace(3); mypqueue.emplace(4); mypqueue.emplace(5); mypqueue.emplace(6); // queue becomes 1, 2, 3, 4, 5, 6 // printing the priority queue cout << \"mypqueue = \"; while (!mypqueue.empty()) { cout << mypqueue.top() << \" \"; mypqueue.pop(); } return 0;}", "e": 26989, "s": 26442, "text": null }, { "code": null, "e": 27012, "s": 26989, "text": "mypqueue = 6 5 4 3 2 1" }, { "code": null, "e": 27018, "s": 27014, "text": "C++" }, { "code": "// CHARACTER PRIORITY QUEUE// CPP program to illustrate// Implementation of emplace() function#include <iostream>#include <queue>using namespace std; int main(){ priority_queue<char> mypqueue; mypqueue.emplace('A'); mypqueue.emplace('b'); mypqueue.emplace('C'); mypqueue.emplace('d'); mypqueue.emplace('E'); mypqueue.emplace('f'); // queue becomes A, b, C, d, E, f // printing the priority queue cout << \"mypqueue = \"; while (!mypqueue.empty()) { cout << mypqueue.top() << \" \"; mypqueue.pop(); } return 0;}", "e": 27580, "s": 27018, "text": null }, { "code": null, "e": 27603, "s": 27580, "text": "mypqueue = f d b E C A" }, { "code": null, "e": 27609, "s": 27605, "text": "C++" }, { "code": "// STRING PRIORITY QUEUE// CPP program to illustrate// Implementation of emplace() function#include <iostream>#include <queue>#include <string>using namespace std; int main(){ priority_queue<string> mypqueue; mypqueue.emplace(\"portal\"); mypqueue.emplace(\"computer science\"); mypqueue.emplace(\"is a\"); mypqueue.emplace(\"GEEKSFORGEEKS\"); // queue becomes portal, computer science, // is a, GEEKSFORGEEKS // printing the priority queue cout << \"mypqueue = \"; while (!mypqueue.empty()) { cout << mypqueue.top() << \" \"; mypqueue.pop(); } return 0;}", "e": 28205, "s": 27609, "text": null }, { "code": null, "e": 28259, "s": 28205, "text": "mypqueue = portal is a computer science GEEKSFORGEEKS" }, { "code": null, "e": 28392, "s": 28261, "text": "Application : Given a number of integers, add them to the priority queue using emplace() and find the size of the priority queue. " }, { "code": null, "e": 28425, "s": 28392, "text": "Input : 5, 13, 0, 9, 4\nOutput: 5" }, { "code": null, "e": 28662, "s": 28425, "text": "Algorithm 1. Insert the given elements to the priority queue container one by one using emplace(). 2. Keep popping the elements of priority queue until it becomes empty, and increment the counter variable. 3. Print the counter variable." }, { "code": null, "e": 28666, "s": 28662, "text": "C++" }, { "code": "// CPP program to illustrate// Application of emplace() function#include <iostream>#include <queue>using namespace std; int main(){ int c = 0; // Empty Priority Queue priority_queue<int> pqueue; // inserting elements into priority_queue pqueue.emplace(5); pqueue.emplace(13); pqueue.emplace(0); pqueue.emplace(9); pqueue.emplace(4); // Priority queue becomes 13, 9, 5, 4, 0 // Counting number of elements in queue while (!pqueue.empty()) { pqueue.pop(); c++; } cout << c;}", "e": 29199, "s": 28666, "text": null }, { "code": null, "e": 29201, "s": 29199, "text": "5" }, { "code": null, "e": 29226, "s": 29203, "text": "Time Complexity : O(1)" }, { "code": null, "e": 29465, "s": 29226, "text": "emplace() vs push() When we use push(), we create an object and then insert it into the priority_queue. With emplace(), the object is constructed in-place and saves an unnecessary copy. Please see emplace vs insert in C++ STL for details." }, { "code": null, "e": 29469, "s": 29465, "text": "C++" }, { "code": "// C++ code to demonstrate difference between// emplace and insert#include<bits/stdc++.h>using namespace std; int main(){ // declaring priority queue priority_queue<pair<char, int>> pqueue; // using emplace() to insert pair in-place pqueue.emplace('a', 24); // Below line would not compile // pqueue.push('b', 25); // using push() to insert pair pqueue.push(make_pair('b', 25)); // printing the priority_queue while (!pqueue.empty()) { pair<char, int> p = pqueue.top(); cout << p.first << \" \" << p.second << endl; pqueue.pop(); } return 0;}", "e": 30119, "s": 29469, "text": null }, { "code": null, "e": 30129, "s": 30119, "text": "b 25\na 24" }, { "code": null, "e": 30139, "s": 30131, "text": "clintra" }, { "code": null, "e": 30158, "s": 30139, "text": "cpp-priority-queue" }, { "code": null, "e": 30162, "s": 30158, "text": "STL" }, { "code": null, "e": 30166, "s": 30162, "text": "C++" }, { "code": null, "e": 30170, "s": 30166, "text": "STL" }, { "code": null, "e": 30174, "s": 30170, "text": "CPP" }, { "code": null, "e": 30272, "s": 30174, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30291, "s": 30272, "text": "Inheritance in C++" }, { "code": null, "e": 30334, "s": 30291, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 30358, "s": 30334, "text": "C++ Classes and Objects" }, { "code": null, "e": 30385, "s": 30358, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 30409, "s": 30385, "text": "Virtual Function in C++" }, { "code": null, "e": 30440, "s": 30409, "text": "Templates in C++ with Examples" }, { "code": null, "e": 30460, "s": 30440, "text": "Constructors in C++" }, { "code": null, "e": 30488, "s": 30460, "text": "Operator Overloading in C++" }, { "code": null, "e": 30516, "s": 30488, "text": "Socket Programming in C/C++" } ]
Operator Overloading in Python - GeeksforGeeks
21 Feb, 2022 Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because ‘+’ operator is overloaded by int class and str class. You might have noticed that the same built-in operator or function shows different behavior for objects of different classes, this is called Operator Overloading. Python3 # Python program to show use of# + operator for different purposes. print(1 + 2) # concatenate two stringsprint("Geeks"+"For") # Product two numbersprint(3 * 4) # Repeat the Stringprint("Geeks"*4) 3 GeeksFor 12 GeeksGeeksGeeksGeeks Output: 3 GeeksFor 12 GeeksGeeksGeeksGeeks How to overload the operators in Python? Consider that we have two objects which are a physical representation of a class (user-defined data type) and we have to add two objects with binary ‘+’ operator it throws an error, because compiler don’t know how to add two objects. So we define a method for an operator and that process is called operator overloading. We can overload all existing operators but we can’t create a new operator. To perform operator overloading, Python provides some special function or magic function that is automatically invoked when it is associated with that particular operator. For example, when we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined.Overloading binary + operator in Python : When we use an operator on user defined data types then automatically a special function or magic function associated with that operator is invoked. Changing the behavior of operator is as simple as changing the behavior of method or function. You define methods in your class and operators work according to that behavior defined in methods. When we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined. There by changing this magic method’s code, we can give extra meaning to the + operator. Code 1: Python3 # Python Program illustrate how# to overload an binary + operator class A: def __init__(self, a): self.a = a # adding two objects def __add__(self, o): return self.a + o.aob1 = A(1)ob2 = A(2)ob3 = A("Geeks")ob4 = A("For") print(ob1 + ob2)print(ob3 + ob4) 3 GeeksFor Output : 3 GeeksFor Code 2: Python3 # Python Program to perform addition# of two complex numbers using binary# + operator overloading. class complex: def __init__(self, a, b): self.a = a self.b = b # adding two objects def __add__(self, other): return self.a + other.a, self.b + other.b Ob1 = complex(1, 2)Ob2 = complex(2, 3)Ob3 = Ob1 + Ob2print(Ob3) (3, 5) Output : (3, 5) Overloading comparison operators in Python : Python3 # Python program to overload# a comparison operators class A: def __init__(self, a): self.a = a def __gt__(self, other): if(self.a>other.a): return True else: return Falseob1 = A(2)ob2 = A(3)if(ob1>ob2): print("ob1 is greater than ob2")else: print("ob2 is greater than ob1") Output : ob2 is greater than ob1 Overloading equality and less than operators : Python3 # Python program to overload equality# and less than operators class A: def __init__(self, a): self.a = a def __lt__(self, other): if(self.a<other.a): return "ob1 is lessthan ob2" else: return "ob2 is less than ob1" def __eq__(self, other): if(self.a == other.a): return "Both are equal" else: return "Not equal" ob1 = A(2)ob2 = A(3)print(ob1 < ob2) ob3 = A(4)ob4 = A(4)print(ob1 == ob2) Output : ob1 is lessthan ob2 Not equal Note: It is not possible to change the number of operands of an operator. For ex. you cannot overload a unary operator as a binary operator. The following code will throw a syntax error. Python3 # Python program which attempts to# overload ~ operator as binary operator class A: def __init__(self, a): self.a = a # Overloading ~ operator, but with two operands def __invert__(self, other): return "This is the ~ operator, overloaded as binary operator." ob1 = A(2)ob2 = A(3) print(ob1~ob2) bestharadhakrishna somanyusamal kannasockalingam ovd0312 Picked Python-Operators Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace()
[ { "code": null, "e": 42677, "s": 42649, "text": "\n21 Feb, 2022" }, { "code": null, "e": 43118, "s": 42677, "text": "Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because ‘+’ operator is overloaded by int class and str class. You might have noticed that the same built-in operator or function shows different behavior for objects of different classes, this is called Operator Overloading. " }, { "code": null, "e": 43126, "s": 43118, "text": "Python3" }, { "code": "# Python program to show use of# + operator for different purposes. print(1 + 2) # concatenate two stringsprint(\"Geeks\"+\"For\") # Product two numbersprint(3 * 4) # Repeat the Stringprint(\"Geeks\"*4)", "e": 43323, "s": 43126, "text": null }, { "code": null, "e": 43359, "s": 43323, "text": "3\nGeeksFor\n12\nGeeksGeeksGeeksGeeks\n" }, { "code": null, "e": 43369, "s": 43359, "text": "Output: " }, { "code": null, "e": 43404, "s": 43369, "text": "3\nGeeksFor\n12\nGeeksGeeksGeeksGeeks" }, { "code": null, "e": 44757, "s": 43404, "text": "How to overload the operators in Python? Consider that we have two objects which are a physical representation of a class (user-defined data type) and we have to add two objects with binary ‘+’ operator it throws an error, because compiler don’t know how to add two objects. So we define a method for an operator and that process is called operator overloading. We can overload all existing operators but we can’t create a new operator. To perform operator overloading, Python provides some special function or magic function that is automatically invoked when it is associated with that particular operator. For example, when we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined.Overloading binary + operator in Python : When we use an operator on user defined data types then automatically a special function or magic function associated with that operator is invoked. Changing the behavior of operator is as simple as changing the behavior of method or function. You define methods in your class and operators work according to that behavior defined in methods. When we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined. There by changing this magic method’s code, we can give extra meaning to the + operator. Code 1: " }, { "code": null, "e": 44765, "s": 44757, "text": "Python3" }, { "code": "# Python Program illustrate how# to overload an binary + operator class A: def __init__(self, a): self.a = a # adding two objects def __add__(self, o): return self.a + o.aob1 = A(1)ob2 = A(2)ob3 = A(\"Geeks\")ob4 = A(\"For\") print(ob1 + ob2)print(ob3 + ob4)", "e": 45044, "s": 44765, "text": null }, { "code": null, "e": 45056, "s": 45044, "text": "3\nGeeksFor\n" }, { "code": null, "e": 45067, "s": 45056, "text": "Output : " }, { "code": null, "e": 45078, "s": 45067, "text": "3\nGeeksFor" }, { "code": null, "e": 45088, "s": 45078, "text": "Code 2: " }, { "code": null, "e": 45096, "s": 45088, "text": "Python3" }, { "code": "# Python Program to perform addition# of two complex numbers using binary# + operator overloading. class complex: def __init__(self, a, b): self.a = a self.b = b # adding two objects def __add__(self, other): return self.a + other.a, self.b + other.b Ob1 = complex(1, 2)Ob2 = complex(2, 3)Ob3 = Ob1 + Ob2print(Ob3)", "e": 45443, "s": 45096, "text": null }, { "code": null, "e": 45451, "s": 45443, "text": "(3, 5)\n" }, { "code": null, "e": 45462, "s": 45451, "text": "Output : " }, { "code": null, "e": 45469, "s": 45462, "text": "(3, 5)" }, { "code": null, "e": 45516, "s": 45469, "text": "Overloading comparison operators in Python : " }, { "code": null, "e": 45524, "s": 45516, "text": "Python3" }, { "code": "# Python program to overload# a comparison operators class A: def __init__(self, a): self.a = a def __gt__(self, other): if(self.a>other.a): return True else: return Falseob1 = A(2)ob2 = A(3)if(ob1>ob2): print(\"ob1 is greater than ob2\")else: print(\"ob2 is greater than ob1\")", "e": 45854, "s": 45524, "text": null }, { "code": null, "e": 45865, "s": 45854, "text": "Output : " }, { "code": null, "e": 45889, "s": 45865, "text": "ob2 is greater than ob1" }, { "code": null, "e": 45938, "s": 45889, "text": "Overloading equality and less than operators : " }, { "code": null, "e": 45946, "s": 45938, "text": "Python3" }, { "code": "# Python program to overload equality# and less than operators class A: def __init__(self, a): self.a = a def __lt__(self, other): if(self.a<other.a): return \"ob1 is lessthan ob2\" else: return \"ob2 is less than ob1\" def __eq__(self, other): if(self.a == other.a): return \"Both are equal\" else: return \"Not equal\" ob1 = A(2)ob2 = A(3)print(ob1 < ob2) ob3 = A(4)ob4 = A(4)print(ob1 == ob2)", "e": 46438, "s": 45946, "text": null }, { "code": null, "e": 46449, "s": 46438, "text": "Output : " }, { "code": null, "e": 46479, "s": 46449, "text": "ob1 is lessthan ob2\nNot equal" }, { "code": null, "e": 46666, "s": 46479, "text": "Note: It is not possible to change the number of operands of an operator. For ex. you cannot overload a unary operator as a binary operator. The following code will throw a syntax error." }, { "code": null, "e": 46674, "s": 46666, "text": "Python3" }, { "code": "# Python program which attempts to# overload ~ operator as binary operator class A: def __init__(self, a): self.a = a # Overloading ~ operator, but with two operands def __invert__(self, other): return \"This is the ~ operator, overloaded as binary operator.\" ob1 = A(2)ob2 = A(3) print(ob1~ob2)", "e": 46994, "s": 46674, "text": null }, { "code": null, "e": 47015, "s": 46996, "text": "bestharadhakrishna" }, { "code": null, "e": 47028, "s": 47015, "text": "somanyusamal" }, { "code": null, "e": 47045, "s": 47028, "text": "kannasockalingam" }, { "code": null, "e": 47053, "s": 47045, "text": "ovd0312" }, { "code": null, "e": 47060, "s": 47053, "text": "Picked" }, { "code": null, "e": 47077, "s": 47060, "text": "Python-Operators" }, { "code": null, "e": 47084, "s": 47077, "text": "Python" }, { "code": null, "e": 47182, "s": 47084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47210, "s": 47182, "text": "Read JSON file using Python" }, { "code": null, "e": 47260, "s": 47210, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 47282, "s": 47260, "text": "Python map() function" }, { "code": null, "e": 47326, "s": 47282, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 47361, "s": 47326, "text": "Read a file line by line in Python" }, { "code": null, "e": 47393, "s": 47361, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 47415, "s": 47393, "text": "Enumerate() in Python" }, { "code": null, "e": 47457, "s": 47415, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 47487, "s": 47457, "text": "Iterate over a list in Python" } ]